mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-03 15:21:17 -05:00
color-w8: net change of 2 commits
- color-w8: written from its sheet - color-w8: repair 1
This commit is contained in:
@@ -1,41 +0,0 @@
|
||||
//! Linux: Sample Color from Screen (`vectorcraft_ui_egui::screen_color`) through the XDG desktop
|
||||
//! portal's color sampler ([`portal`]). A thread of its own asks the portal and waits for the
|
||||
//! person, so the UI keeps drawing; it sends the color to the UI and wakes the window. The dialog's
|
||||
//! parent is the window, named on that thread as for the portal's save dialog (`portal_save`).
|
||||
|
||||
mod portal;
|
||||
|
||||
/// The portal's color sampler over the window `parent` holds; `ui` is woken when it answers.
|
||||
pub fn sampler(ui: egui::Context, parent: super::host_services::Parent) -> vectorcraft_ui_egui::screen_color::StartSampler {
|
||||
Box::new(move || {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let (ui, window) = (ui.clone(), parent.clone());
|
||||
std::thread::Builder::new()
|
||||
.name("screen-color".into())
|
||||
.spawn(move || {
|
||||
// The thread names the window and holds it until the export that names it is dropped.
|
||||
let (handle, export) = match window.as_deref() {
|
||||
Some(window) => {
|
||||
let (handle, export) = super::portal_save::exported_parent(window);
|
||||
(handle, Some(export))
|
||||
}
|
||||
None => (String::new(), None),
|
||||
};
|
||||
let picked = portal::connect(zbus::blocking::connection::Builder::session()).and_then(|conn| portal::pick(&conn, &handle));
|
||||
drop(export);
|
||||
drop(window);
|
||||
let answer = picked.map_err(|failure| {
|
||||
log::warn!("the portal's screen color sampler gave no color: {}", failure.detail());
|
||||
failure.message().to_string()
|
||||
});
|
||||
// The UI may be gone (the app quitting): nothing waits for the color then.
|
||||
let _ = tx.send(answer);
|
||||
ui.request_repaint();
|
||||
})
|
||||
.map_err(|e| {
|
||||
log::warn!("could not start the screen color sampler's thread: {e}");
|
||||
"the screen color sampler failed".to_string()
|
||||
})?;
|
||||
Ok(rx)
|
||||
})
|
||||
}
|
||||
@@ -1,291 +0,0 @@
|
||||
//! The XDG desktop portal's `Screenshot.PickColor`
|
||||
//! (<https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html>):
|
||||
//! the call returns a request path at once, and the request's `Response` signal later carries the
|
||||
//! color the person picked, as sRGB components from 0 to 1, or a code for a cancel or another end.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use zbus::blocking::{Connection, Proxy};
|
||||
use zbus::zvariant::{OwnedValue, Value};
|
||||
|
||||
/// How long the portal has to return a request path for `PickColor`. VectorCraft's own limit,
|
||||
/// 25 seconds as libdbus's default for a method call. The portal returns the path before it shows
|
||||
/// the sampler, so the person's time with the sampler does not count.
|
||||
const CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(25);
|
||||
|
||||
/// Why no color came back, as the status bar shows it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(super) enum Failure {
|
||||
/// No session bus, no portal, or a portal without the Screenshot interface's `PickColor`.
|
||||
Unavailable(String),
|
||||
/// The portal did not return a request path in time, or it left the bus before it answered.
|
||||
NoAnswer(String),
|
||||
/// The portal ended the request without a color, or its answer can't be read.
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
impl Failure {
|
||||
/// The status bar's message (English; the status bar translates it).
|
||||
pub(super) fn message(&self) -> &'static str {
|
||||
match self {
|
||||
Failure::Unavailable(_) => "this system has no screen color sampler",
|
||||
Failure::NoAnswer(_) => "the screen color sampler did not answer",
|
||||
Failure::Failed(_) => "the screen color sampler failed",
|
||||
}
|
||||
}
|
||||
|
||||
/// What went wrong, for the log.
|
||||
pub(super) fn detail(&self) -> &str {
|
||||
match self {
|
||||
Failure::Unavailable(d) | Failure::NoAnswer(d) | Failure::Failed(d) => d,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// D-Bus errors that mean the session has no portal, or none that answers `PickColor`.
|
||||
const UNAVAILABLE: &[&str] = &[
|
||||
"org.freedesktop.DBus.Error.ServiceUnknown",
|
||||
"org.freedesktop.DBus.Error.NameHasNoOwner",
|
||||
"org.freedesktop.DBus.Error.UnknownMethod",
|
||||
"org.freedesktop.DBus.Error.UnknownInterface",
|
||||
"org.freedesktop.DBus.Error.UnknownObject",
|
||||
];
|
||||
|
||||
/// The connection `builder` makes, with [`CALL_TIMEOUT`] for its method calls.
|
||||
pub(super) fn connect(builder: zbus::Result<zbus::blocking::connection::Builder<'_>>) -> Result<Connection, Failure> {
|
||||
builder.and_then(|b| b.method_timeout(CALL_TIMEOUT).build()).map_err(|e| Failure::Unavailable(e.to_string()))
|
||||
}
|
||||
|
||||
/// Shows the portal's color sampler over the window `parent` names and waits for the color, `None`
|
||||
/// when the person canceled it. `conn`'s method timeout bounds the call; the wait for the person
|
||||
/// after it has no bound, and ends when the portal answers or leaves the bus.
|
||||
pub(super) fn pick(conn: &Connection, parent: &str) -> Result<Option<[f32; 3]>, Failure> {
|
||||
const DESKTOP: &str = "org.freedesktop.portal.Desktop";
|
||||
let token = crate::portal_request::token("vectorcraft_color").map_err(Failure::Failed)?;
|
||||
// Made before the call: a portal can send its answer before the call returns.
|
||||
let replies = crate::portal_request::Responses::new(conn).map_err(Failure::Failed)?;
|
||||
let proxy = Proxy::new(conn, DESKTOP, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Screenshot")
|
||||
.map_err(|e| Failure::Failed(e.to_string()))?;
|
||||
let options = HashMap::from([("handle_token", Value::from(token.as_str()))]);
|
||||
let call = proxy.call_method("PickColor", &(parent, options)).map_err(|e| call_failure(&e))?;
|
||||
let reply = replies.wait(&call).map_err(Failure::NoAnswer)?;
|
||||
let (code, results): (u32, HashMap<String, OwnedValue>) = reply.body().deserialize().map_err(|e| Failure::Failed(e.to_string()))?;
|
||||
answer(code, &results)
|
||||
}
|
||||
|
||||
/// The [`Failure`] for an error the `PickColor` call returned. zbus reports a call that outlives
|
||||
/// the connection's method timeout as an `InputOutput` error of kind `TimedOut`.
|
||||
fn call_failure(e: &zbus::Error) -> Failure {
|
||||
match e {
|
||||
zbus::Error::MethodError(name, ..) if UNAVAILABLE.contains(&name.as_str()) => Failure::Unavailable(e.to_string()),
|
||||
zbus::Error::InputOutput(io) if io.kind() == std::io::ErrorKind::TimedOut => Failure::NoAnswer(e.to_string()),
|
||||
_ => Failure::Failed(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The color in a `Response` with `code` and `results`: response 0 carries it, 1 is a cancel, and
|
||||
/// any other code ends the request without one. The components are passed on as given;
|
||||
/// `screen_color::sampled` clamps them to 0 to 1, as for the other systems' samplers.
|
||||
fn answer(code: u32, results: &HashMap<String, OwnedValue>) -> Result<Option<[f32; 3]>, Failure> {
|
||||
match code {
|
||||
0 => {}
|
||||
1 => return Ok(None),
|
||||
_ => return Err(Failure::Failed(format!("the portal ended the request (response {code})"))),
|
||||
}
|
||||
let color = results.get("color").ok_or_else(|| Failure::Failed("no color in the portal's answer".into()))?;
|
||||
// Matched field by field: zvariant's tuple conversion panics on a structure with fewer fields.
|
||||
match &**color {
|
||||
Value::Structure(s) => match s.fields() {
|
||||
[Value::F64(r), Value::F64(g), Value::F64(b)] => Ok(Some([*r, *g, *b].map(|v| v as f32))),
|
||||
_ => Err(Failure::Failed(format!("the portal's color is not three numbers: {color:?}"))),
|
||||
},
|
||||
_ => Err(Failure::Failed(format!("the portal's color is not three numbers: {color:?}"))),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::portal_request::test_bus::private_bus;
|
||||
|
||||
fn color(rgb: (f64, f64, f64)) -> HashMap<String, OwnedValue> {
|
||||
HashMap::from([("color".into(), OwnedValue::try_from(Value::from(rgb)).unwrap())])
|
||||
}
|
||||
|
||||
fn failed<T: std::fmt::Debug>(r: Result<T, Failure>) -> bool {
|
||||
matches!(r, Err(Failure::Failed(_)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_picked_color_keeps_its_srgb_values() {
|
||||
assert_eq!(answer(0, &color((0.25, 0.5, 0.75))), Ok(Some([0.25, 0.5, 0.75])));
|
||||
assert_eq!(answer(0, &color((0.0, 1.0, 0.0))), Ok(Some([0.0, 1.0, 0.0])));
|
||||
// Outside 0 to 1: passed on for `screen_color::sampled` to clamp.
|
||||
assert_eq!(answer(0, &color((-0.5, 1.5, 1.0))), Ok(Some([-0.5, 1.5, 1.0])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_needs_no_color() {
|
||||
assert_eq!(answer(1, &HashMap::new()), Ok(None));
|
||||
assert_eq!(answer(1, &color((0.25, 0.5, 0.75))), Ok(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_response_codes_are_failures() {
|
||||
for code in [2, 3, u32::MAX] {
|
||||
assert!(failed(answer(code, &color((0.25, 0.5, 0.75)))), "{code}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_success_without_a_valid_color_is_a_failure() {
|
||||
assert!(failed(answer(0, &HashMap::new())));
|
||||
let wrong = HashMap::from([("color".into(), OwnedValue::from(1_u32))]);
|
||||
assert!(failed(answer(0, &wrong)));
|
||||
// Fewer fields, more fields, and fields of another type: an error, not a panic.
|
||||
for wrong in [Value::from((0.5, 0.5)), Value::from((0.5, 0.5, 0.5, 0.5)), Value::from((1_u32, 0.5, 0.5)), Value::from(vec![0.5, 0.5, 0.5])] {
|
||||
let wrong = HashMap::from([("color".into(), OwnedValue::try_from(wrong).unwrap())]);
|
||||
assert!(failed(answer(0, &wrong)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_errors_say_whether_the_system_has_a_sampler() {
|
||||
let reply = |name: &str| {
|
||||
let call = zbus::Message::method_call("/org/freedesktop/portal/desktop", "PickColor").unwrap().build(&()).unwrap();
|
||||
let error = zbus::Message::error(&call.header(), name).unwrap().build(&("detail",)).unwrap();
|
||||
zbus::Error::from(error)
|
||||
};
|
||||
for name in UNAVAILABLE {
|
||||
assert!(matches!(call_failure(&reply(name)), Failure::Unavailable(_)), "{name}");
|
||||
}
|
||||
assert!(matches!(call_failure(&reply("org.freedesktop.portal.Error.NotAllowed")), Failure::Failed(_)));
|
||||
let timed_out = zbus::Error::InputOutput(std::sync::Arc::new(std::io::ErrorKind::TimedOut.into()));
|
||||
assert!(matches!(call_failure(&timed_out), Failure::NoAnswer(_)));
|
||||
let broken = zbus::Error::InputOutput(std::sync::Arc::new(std::io::ErrorKind::BrokenPipe.into()));
|
||||
assert!(matches!(call_failure(&broken), Failure::Failed(_)));
|
||||
let messages = [Failure::Unavailable(String::new()), Failure::NoAnswer(String::new()), Failure::Failed(String::new())].map(|f| f.message());
|
||||
assert_eq!(
|
||||
messages,
|
||||
["this system has no screen color sampler", "the screen color sampler did not answer", "the screen color sampler failed"]
|
||||
);
|
||||
assert_eq!(call_failure(&broken).detail(), broken.to_string());
|
||||
}
|
||||
|
||||
/// Every language that translates the sampler's other messages translates these too. The
|
||||
/// i18n tests of `vectorcraft-ui-egui` do not read this crate's messages.
|
||||
#[test]
|
||||
fn the_messages_are_translated_where_the_sampler_is() {
|
||||
use vectorcraft_ui_egui::i18n::{Lang, message};
|
||||
const OPEN: &str = "the screen color sampler is already open";
|
||||
let langs: Vec<Lang> = Lang::all().filter(|&lang| message(lang, OPEN) != OPEN).collect();
|
||||
assert!(!langs.is_empty(), "no language translates {OPEN:?}");
|
||||
for lang in langs {
|
||||
for failure in [Failure::Unavailable(String::new()), Failure::NoAnswer(String::new()), Failure::Failed(String::new())] {
|
||||
assert_ne!(message(lang, failure.message()), failure.message(), "{}", lang.code());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The client's connection to the private bus at `address`, made as the sampler makes its own.
|
||||
fn client(address: &str) -> Connection {
|
||||
connect(zbus::blocking::connection::Builder::address(address)).unwrap()
|
||||
}
|
||||
|
||||
/// The portal's name, owned on the private bus at `address` before any call, so the bus never
|
||||
/// starts an installed portal in its place.
|
||||
fn portal(address: &str) -> Connection {
|
||||
zbus::blocking::connection::Builder::address(address).unwrap().name("org.freedesktop.portal.Desktop").unwrap().build().unwrap()
|
||||
}
|
||||
|
||||
/// Through a real D-Bus: an answer that comes before the call returns is kept; answers on
|
||||
/// other request paths or from other connections are ignored; a cancel gives no color; and a
|
||||
/// portal that leaves the bus while the person picks ends the wait.
|
||||
#[test]
|
||||
fn the_answer_is_the_portals_response_on_the_returned_path() {
|
||||
use zbus::blocking::MessageIterator;
|
||||
use zbus::zvariant::OwnedObjectPath;
|
||||
|
||||
let Some((_daemon, address)) = private_bus() else { return };
|
||||
let address = address.as_str();
|
||||
let server = portal(address);
|
||||
let impostor = zbus::blocking::connection::Builder::address(address).unwrap().build().unwrap();
|
||||
let incoming = MessageIterator::from(&server);
|
||||
let worker = std::thread::spawn(move || {
|
||||
let mut calls = Vec::new();
|
||||
for msg in incoming {
|
||||
let msg = msg.unwrap();
|
||||
let header = msg.header();
|
||||
if header.message_type() != zbus::message::Type::MethodCall || header.member().map(|m| m.as_str()) != Some("PickColor") {
|
||||
continue;
|
||||
}
|
||||
let (parent, options): (String, HashMap<String, OwnedValue>) = msg.body().deserialize().unwrap();
|
||||
let token = String::try_from(options.get("handle_token").unwrap().try_clone().unwrap()).unwrap();
|
||||
assert!(token.starts_with("vectorcraft_color_"));
|
||||
assert!(token.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_'));
|
||||
assert!(!calls.iter().any(|(_, old)| old == &token));
|
||||
calls.push((parent, token));
|
||||
// A portal older than version 0.9 answers on a path of its own, not the token's.
|
||||
let path = format!("/org/freedesktop/portal/desktop/request/independent/pick_{}", calls.len());
|
||||
let handle = OwnedObjectPath::try_from(path.as_str()).unwrap();
|
||||
if calls.len() == 4 {
|
||||
server.reply(&header, &handle).unwrap();
|
||||
assert!(server.release_name("org.freedesktop.portal.Desktop").unwrap());
|
||||
break;
|
||||
}
|
||||
let to = header.sender().cloned().map(zbus::names::BusName::from);
|
||||
// Another connection can't end the wait by claiming the portal left.
|
||||
impostor
|
||||
.emit_signal(
|
||||
to.clone(),
|
||||
"/org/freedesktop/DBus",
|
||||
"org.freedesktop.DBus",
|
||||
"NameOwnerChanged",
|
||||
&("org.freedesktop.portal.Desktop", server.unique_name().unwrap().as_str(), ""),
|
||||
)
|
||||
.unwrap();
|
||||
let wrong = color((1.0, 0.0, 0.0));
|
||||
impostor.emit_signal(to.clone(), path.as_str(), "org.freedesktop.portal.Request", "Response", &(0_u32, &wrong)).unwrap();
|
||||
let unrelated = "/org/freedesktop/portal/desktop/request/unrelated";
|
||||
server.emit_signal(to.clone(), unrelated, "org.freedesktop.portal.Request", "Response", &(0_u32, &wrong)).unwrap();
|
||||
let code = if calls.len() == 2 { 1_u32 } else { 0_u32 };
|
||||
server.emit_signal(to, path.as_str(), "org.freedesktop.portal.Request", "Response", &(code, &color((0.25, 0.5, 0.75)))).unwrap();
|
||||
// The reply that names the path goes last: every answer above came before it.
|
||||
server.reply(&header, &handle).unwrap();
|
||||
}
|
||||
calls
|
||||
});
|
||||
let client = client(address);
|
||||
assert_eq!(pick(&client, "x11:12"), Ok(Some([0.25, 0.5, 0.75])));
|
||||
assert_eq!(pick(&client, "wayland:example"), Ok(None));
|
||||
assert_eq!(pick(&client, ""), Ok(Some([0.25, 0.5, 0.75])));
|
||||
assert!(matches!(pick(&client, ""), Err(Failure::NoAnswer(_))));
|
||||
let calls = worker.join().unwrap();
|
||||
assert_eq!(calls.iter().map(|(parent, _)| parent.as_str()).collect::<Vec<_>>(), ["x11:12", "wayland:example", "", ""]);
|
||||
}
|
||||
|
||||
/// Through a real D-Bus: a portal without `PickColor` ends the request as a system without a
|
||||
/// sampler, and the sampler's connection gives the call [`CALL_TIMEOUT`].
|
||||
#[test]
|
||||
fn a_portal_without_pick_color_ends_the_request() {
|
||||
let Some((_daemon, address)) = private_bus() else { return };
|
||||
let address = address.as_str();
|
||||
let server = portal(address);
|
||||
let incoming = zbus::blocking::MessageIterator::from(&server);
|
||||
let worker = std::thread::spawn(move || {
|
||||
for msg in incoming {
|
||||
let msg = msg.unwrap();
|
||||
let header = msg.header();
|
||||
if header.member().map(|m| m.as_str()) == Some("PickColor") {
|
||||
server.reply_error(&header, "org.freedesktop.DBus.Error.UnknownMethod", &("no PickColor",)).unwrap();
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let client = client(address);
|
||||
assert_eq!(client.method_timeout(), Some(CALL_TIMEOUT));
|
||||
let failure = pick(&client, "");
|
||||
assert!(matches!(failure, Err(Failure::Unavailable(_))), "{failure:?}");
|
||||
worker.join().unwrap();
|
||||
}
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
//! macOS: Sample Color from Screen (`vectorcraft_ui_egui::screen_color`) through the system's color
|
||||
//! sampler, `NSColorSampler` (macOS 10.15 and later), which "displays the system’s color-sampling
|
||||
//! interface and returns the selected color to your app"
|
||||
//! (<https://developer.apple.com/documentation/appkit/nscolorsampler>). AppKit calls the handler on
|
||||
//! the main thread with the color the person clicked, or with nil when they pressed Escape. The
|
||||
//! color is converted to sRGB before it is sent to the UI; AppKit clips a color outside sRGB to it
|
||||
//! (Display P3 red arrives as sRGB red).
|
||||
//!
|
||||
//! `showSamplerWithSelectionHandler:` has no safe binding; this module allows `unsafe_code`.
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use std::sync::mpsc::channel;
|
||||
|
||||
use block2::RcBlock;
|
||||
use objc2::MainThreadMarker;
|
||||
use objc2_app_kit::{NSColor, NSColorSampler, NSColorSpace};
|
||||
use vectorcraft_ui_egui::screen_color::{Answer, StartSampler};
|
||||
|
||||
/// The system's color sampler; `ui` is woken when it answers.
|
||||
pub fn sampler(ui: egui::Context) -> StartSampler {
|
||||
Box::new(move || {
|
||||
MainThreadMarker::new().ok_or("the color sampler can only be shown from the main thread")?;
|
||||
let (tx, rx) = channel();
|
||||
let ui = ui.clone();
|
||||
let handler = RcBlock::new(move |color: *mut NSColor| {
|
||||
// SAFETY: AppKit passes the selected color, or nil when the person canceled, and keeps
|
||||
// it alive while the handler runs.
|
||||
let answer: Answer = match unsafe { color.as_ref() } {
|
||||
None => Ok(None),
|
||||
Some(color) => srgb(color).map(Some).ok_or_else(|| "the sampled color has no sRGB value".into()),
|
||||
};
|
||||
// The UI may be gone (the app quitting): nothing waits for the color then.
|
||||
let _ = tx.send(answer);
|
||||
ui.request_repaint();
|
||||
});
|
||||
let sampler = NSColorSampler::new();
|
||||
// SAFETY: on the main thread (checked above); the handler has the signature AppKit calls it
|
||||
// with, and AppKit keeps the block and the sampler until the session ends.
|
||||
unsafe { sampler.showSamplerWithSelectionHandler(&handler) };
|
||||
Ok(rx)
|
||||
})
|
||||
}
|
||||
|
||||
/// The components of `color` in sRGB, or `None` when it has no RGB form (a pattern color).
|
||||
fn srgb(color: &NSColor) -> Option<[f32; 3]> {
|
||||
let c = color.colorUsingColorSpace(&NSColorSpace::sRGBColorSpace())?;
|
||||
Some([c.redComponent() as f32, c.greenComponent() as f32, c.blueComponent() as f32])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A color in another space arrives as its sRGB components.
|
||||
#[test]
|
||||
fn sampled_colors_convert_to_srgb() {
|
||||
let red = NSColor::colorWithSRGBRed_green_blue_alpha(1.0, 0.0, 0.0, 1.0);
|
||||
assert_eq!(srgb(&red), Some([1.0, 0.0, 0.0]));
|
||||
// Display P3 (0.6, 0.4, 0.3) lies inside sRGB with other numbers: more red, less green and blue.
|
||||
let p3 = NSColor::colorWithDisplayP3Red_green_blue_alpha(0.6, 0.4, 0.3, 1.0);
|
||||
let [r, g, b] = srgb(&p3).unwrap();
|
||||
assert!(r > 0.61 && g < 0.39 && b < 0.29, "converted, not read as sRGB numbers: {r} {g} {b}");
|
||||
// A color outside sRGB is clipped to it.
|
||||
assert_eq!(srgb(&NSColor::colorWithDisplayP3Red_green_blue_alpha(1.0, 0.0, 0.0, 1.0)), Some([1.0, 0.0, 0.0]));
|
||||
let gray = NSColor::colorWithWhite_alpha(0.5, 1.0);
|
||||
let [r, g, b] = srgb(&gray).unwrap();
|
||||
assert!((r - g).abs() < 1e-4 && (g - b).abs() < 1e-4, "{r} {g} {b}");
|
||||
}
|
||||
}
|
||||
@@ -1,655 +0,0 @@
|
||||
//! Windows: Sample Color from Screen (`vectorcraft_ui_egui::screen_color`). Windows has no system
|
||||
//! color sampler, so a thread of its own copies the virtual screen, the bounding rectangle of all
|
||||
//! the monitors (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getsystemmetrics>),
|
||||
//! into a bitmap with `BitBlt` from the screen's device context
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getdc>), then covers
|
||||
//! the virtual screen with a borderless topmost window that shows that copy under a crosshair
|
||||
//! cursor. The window has its own message loop on that thread, so the UI keeps drawing.
|
||||
//!
|
||||
//! A left click answers the copied pixel under the pointer as sRGB; Escape, a click of any other
|
||||
//! button, closing the window, and the window losing the keyboard focus or the mouse capture answer
|
||||
//! `None`. Each
|
||||
//! click is answered when its button is released, so the release does not reach the window
|
||||
//! underneath. The color comes from the copy taken before the window was shown, so the window
|
||||
//! never samples itself, and moving content shows the frame it had when the copy was taken.
|
||||
//!
|
||||
//! The pixels are 8-bit GDI colors, read as sRGB: GDI content is taken to be sRGB when the display
|
||||
//! does not use Advanced Color
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/wcs/advanced-color-icc-profiles>). The colors
|
||||
//! of HDR and wide-gamut displays are not converted.
|
||||
//!
|
||||
//! winit makes the process per-monitor DPI aware, so the virtual screen, the pointer and the copy
|
||||
//! are in physical pixels on every monitor, whatever its scale, and a monitor left of or above the
|
||||
//! main one has negative coordinates
|
||||
//! (<https://learn.microsoft.com/en-us/windows/win32/hidpi/high-dpi-desktop-application-development-on-windows>).
|
||||
//!
|
||||
//! The Win32 calls have no safe binding; [`overlay`] allows `unsafe_code`.
|
||||
#![cfg_attr(not(windows), allow(dead_code))]
|
||||
|
||||
/// The status message for every failure; the details go to the log.
|
||||
const FAILED: &str = "the screen color sampler failed";
|
||||
|
||||
/// The largest copy of the virtual screen, in bytes of 32-bit pixels: 1 GiB, eight 7680 × 4320
|
||||
/// monitors. VectorCraft's own limit.
|
||||
const MAX_SNAPSHOT_BYTES: u64 = 1 << 30;
|
||||
|
||||
/// `CLR_INVALID` (`wingdi.h`): what `GetPixel` answers for a pixel it can't read.
|
||||
const CLR_INVALID: u32 = 0xFFFF_FFFF;
|
||||
|
||||
/// The virtual screen in physical pixels: its top-left corner (negative when a monitor is left of
|
||||
/// or above the main one) and its size.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct VirtualScreen {
|
||||
left: i32,
|
||||
top: i32,
|
||||
width: i32,
|
||||
height: i32,
|
||||
}
|
||||
|
||||
impl VirtualScreen {
|
||||
/// The virtual screen `GetSystemMetrics` reports, checked before any memory is taken for its
|
||||
/// copy: an error when it is empty, larger than [`MAX_SNAPSHOT_BYTES`], or reaches past the
|
||||
/// coordinates Windows can address.
|
||||
fn new(left: i32, top: i32, width: i32, height: i32) -> Result<Self, String> {
|
||||
if width <= 0 || height <= 0 {
|
||||
return Err(format!("the virtual screen is {width} × {height} pixels"));
|
||||
}
|
||||
let bytes = u64::from(width.unsigned_abs()).saturating_mul(u64::from(height.unsigned_abs())).saturating_mul(4);
|
||||
if bytes > MAX_SNAPSHOT_BYTES {
|
||||
return Err(format!("the virtual screen ({width} × {height} pixels) is larger than the {MAX_SNAPSHOT_BYTES}-byte limit"));
|
||||
}
|
||||
if left.checked_add(width).is_none() || top.checked_add(height).is_none() {
|
||||
return Err(format!("the virtual screen at ({left}, {top}) reaches past the coordinate range"));
|
||||
}
|
||||
Ok(Self { left, top, width, height })
|
||||
}
|
||||
|
||||
/// The pixel of the copy at the screen point (`x`, `y`), or `None` when the point is outside the
|
||||
/// virtual screen.
|
||||
fn pixel(&self, x: i32, y: i32) -> Option<(i32, i32)> {
|
||||
let (px, py) = (x.checked_sub(self.left)?, y.checked_sub(self.top)?);
|
||||
((0..self.width).contains(&px) && (0..self.height).contains(&py)).then_some((px, py))
|
||||
}
|
||||
}
|
||||
|
||||
/// The sRGB components (0 to 1) of a `COLORREF` (`0x00bbggrr`), or `None` for `CLR_INVALID` or any
|
||||
/// other value with its high byte set.
|
||||
fn srgb(colorref: u32) -> Option<[f32; 3]> {
|
||||
if colorref == CLR_INVALID {
|
||||
return None;
|
||||
}
|
||||
let [r, g, b, high] = colorref.to_le_bytes();
|
||||
(high == 0).then(|| [r, g, b].map(|v| f32::from(v) / 255.0))
|
||||
}
|
||||
|
||||
/// The client point of a mouse message. Its `lParam` holds each coordinate as a signed 16-bit
|
||||
/// value (`GET_X_LPARAM` and `GET_Y_LPARAM`,
|
||||
/// <https://learn.microsoft.com/en-us/windows/win32/inputdev/wm-lbuttonup>), so a coordinate past
|
||||
/// 32,767 pixels in a wide virtual screen loses its high bits. Each coordinate becomes the value
|
||||
/// with the same low 16 bits nearest to `near`, the message's own pointer position (`MSG.pt`,
|
||||
/// <https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-msg>) in client
|
||||
/// coordinates.
|
||||
fn message_point(lparam: isize, near: (i32, i32)) -> (i32, i32) {
|
||||
let widen = |low: i16, near: i32| near.saturating_add(i32::from(i32::from(low).wrapping_sub(near) as i16));
|
||||
(widen(lparam as i16, near.0), widen((lparam >> 16) as i16, near.1))
|
||||
}
|
||||
|
||||
/// A mouse button: the left one picks, and any other one cancels.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Button {
|
||||
Left,
|
||||
Right,
|
||||
/// The middle button or a side button.
|
||||
Other,
|
||||
}
|
||||
|
||||
/// What the person did in the sampler's window.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Input {
|
||||
Down(Button),
|
||||
Up(Button),
|
||||
Escape,
|
||||
/// The window became the active window.
|
||||
Activated,
|
||||
/// The window stopped being the active window.
|
||||
Deactivated,
|
||||
/// Another window took the mouse capture.
|
||||
CaptureLost,
|
||||
/// The window was asked to close (Alt+F4).
|
||||
Closed,
|
||||
}
|
||||
|
||||
/// What the sampler does next.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Step {
|
||||
Wait,
|
||||
Pick,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
/// The mouse button last pressed in the window, and whether the window has been active.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
struct Press {
|
||||
down: Option<Button>,
|
||||
active: bool,
|
||||
}
|
||||
|
||||
impl Press {
|
||||
/// A release picks or cancels only after its button went down in the window. Losing the focus
|
||||
/// cancels only after the window had it, so a window that never became active still takes a
|
||||
/// click.
|
||||
fn step(&mut self, input: Input) -> Step {
|
||||
match input {
|
||||
Input::Down(button) => {
|
||||
self.down = Some(button);
|
||||
Step::Wait
|
||||
}
|
||||
Input::Up(button) if self.down == Some(button) => {
|
||||
if button == Button::Left {
|
||||
Step::Pick
|
||||
} else {
|
||||
Step::Cancel
|
||||
}
|
||||
}
|
||||
Input::Up(_) => Step::Wait,
|
||||
Input::Activated => {
|
||||
self.active = true;
|
||||
Step::Wait
|
||||
}
|
||||
Input::Deactivated if !self.active => Step::Wait,
|
||||
Input::Escape | Input::Deactivated | Input::CaptureLost | Input::Closed => Step::Cancel,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The screen color sampler; `ui` is woken when it answers.
|
||||
#[cfg(windows)]
|
||||
pub fn sampler(ui: egui::Context) -> vectorcraft_ui_egui::screen_color::StartSampler {
|
||||
Box::new(move || {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let ui = ui.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("screen-color".into())
|
||||
.spawn(move || {
|
||||
let answer = overlay::run().map_err(|detail| {
|
||||
log::warn!("the screen color sampler gave no color: {detail}");
|
||||
FAILED.to_string()
|
||||
});
|
||||
// The UI may be gone (the app quitting): nothing waits for the color then.
|
||||
let _ = tx.send(answer);
|
||||
ui.request_repaint();
|
||||
})
|
||||
.map_err(|e| {
|
||||
log::warn!("could not start the screen color sampler's thread: {e}");
|
||||
FAILED.to_string()
|
||||
})?;
|
||||
Ok(rx)
|
||||
})
|
||||
}
|
||||
|
||||
/// The copy of the virtual screen and the window that shows it, on the sampler's thread.
|
||||
#[cfg(windows)]
|
||||
mod overlay {
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, WPARAM};
|
||||
use windows::Win32::Graphics::Gdi::{
|
||||
BeginPaint, BitBlt, CAPTUREBLT, ClientToScreen, CreateCompatibleBitmap, CreateCompatibleDC, DeleteDC, DeleteObject, EndPaint, GetDC,
|
||||
GetPixel, HBITMAP, HDC, HGDIOBJ, PAINTSTRUCT, ReleaseDC, SRCCOPY, SelectObject,
|
||||
};
|
||||
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
|
||||
use windows::Win32::UI::Input::KeyboardAndMouse::{ReleaseCapture, SetCapture, VK_ESCAPE};
|
||||
use windows::Win32::UI::WindowsAndMessaging::{
|
||||
CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GetCursorPos, GetMessageW, GetSystemMetrics, HCURSOR, IDC_CROSS,
|
||||
LoadCursorW, MSG, PostQuitMessage, RegisterClassExW, SM_CXVIRTUALSCREEN, SM_CYVIRTUALSCREEN, SM_XVIRTUALSCREEN, SM_YVIRTUALSCREEN, SW_SHOW,
|
||||
SetCursor, SetForegroundWindow, ShowWindow, TranslateMessage, WA_INACTIVE, WM_ACTIVATE, WM_CAPTURECHANGED, WM_CLOSE, WM_DESTROY,
|
||||
WM_DPICHANGED, WM_ERASEBKGND, WM_KEYDOWN, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_MOUSEMOVE, WM_PAINT, WM_RBUTTONDOWN,
|
||||
WM_RBUTTONUP, WM_SETCURSOR, WM_XBUTTONDOWN, WM_XBUTTONUP, WNDCLASSEXW, WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP,
|
||||
};
|
||||
use windows::core::{PCWSTR, w};
|
||||
|
||||
use super::{Button, Input, Press, Step, VirtualScreen, message_point, srgb};
|
||||
|
||||
/// The window class of the sampler's window.
|
||||
const CLASS: PCWSTR = w!("VectorCraftScreenColor");
|
||||
|
||||
/// The picked color, `None` when canceled, or the details of a failure.
|
||||
type Picked = Result<Option<[f32; 3]>, String>;
|
||||
|
||||
/// A copy of the virtual screen in a memory device context. Dropping it frees the bitmap and
|
||||
/// the device context.
|
||||
struct Snapshot {
|
||||
dc: HDC,
|
||||
bitmap: HBITMAP,
|
||||
/// The bitmap the device context held before [`Snapshot::bitmap`] replaced it.
|
||||
old: HGDIOBJ,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
/// Copies `screen` from the screen's device context, which is released on this thread, as
|
||||
/// `ReleaseDC` requires.
|
||||
fn take(screen: VirtualScreen) -> Result<Self, String> {
|
||||
// SAFETY: `GetDC(None)` takes no pointers; the device context is released below.
|
||||
let screen_dc = unsafe { GetDC(None) };
|
||||
if screen_dc.is_invalid() {
|
||||
return Err("GetDC(NULL) gave no device context".into());
|
||||
}
|
||||
let copied = Self::copy(screen_dc, screen);
|
||||
// SAFETY: the device context `GetDC(None)` gave on this thread, released once.
|
||||
unsafe { ReleaseDC(None, screen_dc) };
|
||||
copied
|
||||
}
|
||||
|
||||
fn copy(screen_dc: HDC, s: VirtualScreen) -> Result<Self, String> {
|
||||
// SAFETY: `screen_dc` is a live device context; a failure answers a null handle.
|
||||
let dc = unsafe { CreateCompatibleDC(Some(screen_dc)) };
|
||||
if dc.is_invalid() {
|
||||
return Err("CreateCompatibleDC failed".into());
|
||||
}
|
||||
// SAFETY: as above; the size was checked by `VirtualScreen::new`.
|
||||
let bitmap = unsafe { CreateCompatibleBitmap(screen_dc, s.width, s.height) };
|
||||
if bitmap.is_invalid() {
|
||||
// SAFETY: the device context made above, deleted once.
|
||||
unsafe {
|
||||
let _ = DeleteDC(dc);
|
||||
}
|
||||
return Err(format!("CreateCompatibleBitmap gave no {} × {} bitmap", s.width, s.height));
|
||||
}
|
||||
// SAFETY: both handles are live and made above.
|
||||
let old = unsafe { SelectObject(dc, bitmap.into()) };
|
||||
if old.is_invalid() {
|
||||
// SAFETY: the handles made above, deleted once.
|
||||
unsafe {
|
||||
let _ = DeleteObject(bitmap.into());
|
||||
let _ = DeleteDC(dc);
|
||||
}
|
||||
return Err("SelectObject failed".into());
|
||||
}
|
||||
let snapshot = Self { dc, bitmap, old };
|
||||
// SAFETY: both device contexts are live; the rectangle is the virtual screen.
|
||||
unsafe { BitBlt(dc, 0, 0, s.width, s.height, Some(screen_dc), s.left, s.top, SRCCOPY | CAPTUREBLT) }
|
||||
.map_err(|e| format!("BitBlt of the virtual screen failed: {e}"))?;
|
||||
Ok(snapshot)
|
||||
}
|
||||
|
||||
/// The `COLORREF` of the copy's pixel (`x`, `y`).
|
||||
fn colorref(&self, x: i32, y: i32) -> u32 {
|
||||
// SAFETY: the device context is live while `self` is; GetPixel checks the coordinates.
|
||||
unsafe { GetPixel(self.dc, x, y) }.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Snapshot {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the handles `copy` made, freed once, the bitmap after the device context
|
||||
// lets go of it.
|
||||
unsafe {
|
||||
SelectObject(self.dc, self.old);
|
||||
let _ = DeleteObject(self.bitmap.into());
|
||||
let _ = DeleteDC(self.dc);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The sampler shown on this thread.
|
||||
struct Session {
|
||||
snapshot: Snapshot,
|
||||
screen: VirtualScreen,
|
||||
cursor: HCURSOR,
|
||||
press: Press,
|
||||
/// The pointer position, in screen coordinates, of the message being dispatched (`MSG.pt`).
|
||||
message_pt: Option<POINT>,
|
||||
/// The answer, set once.
|
||||
answer: Option<Picked>,
|
||||
/// The window has been destroyed.
|
||||
destroyed: bool,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static SESSION: RefCell<Option<Session>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// Runs `f` on this thread's session, or answers `None` when there is none or it is in use.
|
||||
/// Win32 calls that send messages to the window (which come back to [`window_proc`]) are made
|
||||
/// outside it.
|
||||
fn with<R>(f: impl FnOnce(&mut Session) -> R) -> Option<R> {
|
||||
SESSION.with(|s| s.try_borrow_mut().ok()?.as_mut().map(f))
|
||||
}
|
||||
|
||||
fn put(session: Option<Session>) -> Option<Session> {
|
||||
SESSION.with(|s| s.try_borrow_mut().ok().map(|mut s| std::mem::replace(&mut *s, session)))?
|
||||
}
|
||||
|
||||
/// Shows the sampler and waits for the person; answers on this thread.
|
||||
pub(super) fn run() -> Picked {
|
||||
// SAFETY: `GetSystemMetrics` takes no pointers.
|
||||
let (left, top, width, height) = unsafe {
|
||||
(
|
||||
GetSystemMetrics(SM_XVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_YVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_CXVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_CYVIRTUALSCREEN),
|
||||
)
|
||||
};
|
||||
let screen = VirtualScreen::new(left, top, width, height)?;
|
||||
let snapshot = Snapshot::take(screen)?;
|
||||
register()?;
|
||||
// SAFETY: a system cursor, loaded by its id.
|
||||
let cursor = unsafe { LoadCursorW(None, IDC_CROSS) }.map_err(|e| format!("LoadCursorW: {e}"))?;
|
||||
// Each sampler runs on a thread of its own, so the thread has no session yet.
|
||||
let _ = put(Some(Session { snapshot, screen, cursor, press: Press::default(), message_pt: None, answer: None, destroyed: false }));
|
||||
let shown = show(screen, cursor);
|
||||
if let Ok(hwnd) = shown {
|
||||
pump();
|
||||
if with(|s| s.destroyed) == Some(false) {
|
||||
// SAFETY: the window made by `show` on this thread, not yet destroyed.
|
||||
let _ = unsafe { DestroyWindow(hwnd) };
|
||||
}
|
||||
}
|
||||
let session = put(None);
|
||||
shown?;
|
||||
session.and_then(|s| s.answer).unwrap_or(Ok(None))
|
||||
}
|
||||
|
||||
/// Registers the window class once for the process.
|
||||
fn register() -> Result<(), String> {
|
||||
static REGISTERED: OnceLock<Result<(), String>> = OnceLock::new();
|
||||
REGISTERED
|
||||
.get_or_init(|| {
|
||||
// SAFETY: the module handle of this program; it is not freed.
|
||||
let instance = unsafe { GetModuleHandleW(None) }.map_err(|e| format!("GetModuleHandleW: {e}"))?;
|
||||
let class = WNDCLASSEXW {
|
||||
cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
|
||||
lpfnWndProc: Some(window_proc),
|
||||
hInstance: instance.into(),
|
||||
lpszClassName: CLASS,
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: `class` is a complete `WNDCLASSEXW` whose strings are static.
|
||||
if unsafe { RegisterClassExW(&class) } == 0 {
|
||||
return Err(format!("RegisterClassExW: {}", windows::core::Error::from_thread()));
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Shows the window over the virtual screen in front of every other window and takes the mouse.
|
||||
fn show(s: VirtualScreen, cursor: HCURSOR) -> Result<HWND, String> {
|
||||
// SAFETY: the module handle of this program; it is not freed.
|
||||
let instance = unsafe { GetModuleHandleW(None) }.map_err(|e| format!("GetModuleHandleW: {e}"))?;
|
||||
// SAFETY: the class was registered by `register`; the strings are static.
|
||||
let hwnd = unsafe {
|
||||
CreateWindowExW(
|
||||
WS_EX_TOPMOST | WS_EX_TOOLWINDOW,
|
||||
CLASS,
|
||||
w!("Sample Color from Screen"),
|
||||
WS_POPUP,
|
||||
s.left,
|
||||
s.top,
|
||||
s.width,
|
||||
s.height,
|
||||
None,
|
||||
None,
|
||||
Some(instance.into()),
|
||||
None,
|
||||
)
|
||||
}
|
||||
.map_err(|e| format!("CreateWindowExW: {e}"))?;
|
||||
// SAFETY: the window made above, on this thread.
|
||||
unsafe {
|
||||
let _ = ShowWindow(hwnd, SW_SHOW);
|
||||
let _ = SetForegroundWindow(hwnd);
|
||||
SetCapture(hwnd);
|
||||
SetCursor(Some(cursor));
|
||||
}
|
||||
Ok(hwnd)
|
||||
}
|
||||
|
||||
/// The window's message loop, until the window is destroyed.
|
||||
fn pump() {
|
||||
let mut msg = MSG::default();
|
||||
// SAFETY: `msg` is a valid `MSG` for each call. `GetMessageW` answers 0 for `WM_QUIT` and -1
|
||||
// for an error; both end the loop.
|
||||
while unsafe { GetMessageW(&mut msg, None, 0, 0) }.0 > 0 {
|
||||
with(|s| s.message_pt = Some(msg.pt));
|
||||
// SAFETY: the message `GetMessageW` just filled in.
|
||||
unsafe {
|
||||
let _ = TranslateMessage(&msg);
|
||||
DispatchMessageW(&msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Answers once, then lets go of the mouse and destroys the window.
|
||||
fn finish(hwnd: HWND, answer: impl FnOnce(&mut Session) -> Picked) {
|
||||
let first = with(|s| {
|
||||
let first = s.answer.is_none();
|
||||
if first {
|
||||
s.answer = Some(answer(s));
|
||||
}
|
||||
first
|
||||
});
|
||||
if first == Some(true) {
|
||||
// SAFETY: the window on this thread; both calls send messages that `window_proc`
|
||||
// handles outside the session.
|
||||
unsafe {
|
||||
let _ = ReleaseCapture();
|
||||
let _ = DestroyWindow(hwnd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The copy's color at the point where the left button was released: `lparam` of that
|
||||
/// `WM_LBUTTONUP`, in `hwnd`'s client coordinates, not where the pointer is now. The pointer's
|
||||
/// current position stands in for `MSG.pt` only when the release was not dispatched by
|
||||
/// [`pump`].
|
||||
fn pick(s: &mut Session, hwnd: HWND, lparam: LPARAM) -> Picked {
|
||||
let mut origin = POINT::default();
|
||||
// SAFETY: the window on this thread and a valid `POINT`; the call sends no message.
|
||||
unsafe { ClientToScreen(hwnd, &mut origin) }.ok().map_err(|e| format!("ClientToScreen: {e}"))?;
|
||||
let pt = match s.message_pt {
|
||||
Some(pt) => pt,
|
||||
None => {
|
||||
let mut now = POINT::default();
|
||||
// SAFETY: `now` is a valid `POINT`.
|
||||
unsafe { GetCursorPos(&mut now) }.map_err(|e| format!("GetCursorPos: {e}"))?;
|
||||
now
|
||||
}
|
||||
};
|
||||
let near = (pt.x.wrapping_sub(origin.x), pt.y.wrapping_sub(origin.y));
|
||||
let (cx, cy) = message_point(lparam.0, near);
|
||||
let at = POINT { x: cx.saturating_add(origin.x), y: cy.saturating_add(origin.y) };
|
||||
let (x, y) = s.screen.pixel(at.x, at.y).ok_or_else(|| format!("the release at ({}, {}) is outside the virtual screen", at.x, at.y))?;
|
||||
let colorref = s.snapshot.colorref(x, y);
|
||||
srgb(colorref).map(Some).ok_or_else(|| format!("GetPixel({x}, {y}) answered {colorref:#010x}"))
|
||||
}
|
||||
|
||||
/// Draws the copy where the virtual screen is, wherever the window's client area is.
|
||||
fn paint(hwnd: HWND) {
|
||||
let copy = with(|s| (s.snapshot.dc, s.screen));
|
||||
let mut ps = PAINTSTRUCT::default();
|
||||
let mut origin = POINT::default();
|
||||
// SAFETY: the window on this thread, with a `PAINTSTRUCT` for `BeginPaint` and `EndPaint`;
|
||||
// the copy's device context lives as long as the session.
|
||||
unsafe {
|
||||
let _ = ClientToScreen(hwnd, &mut origin);
|
||||
let target = BeginPaint(hwnd, &mut ps);
|
||||
if let Some((dc, s)) = copy
|
||||
&& !target.is_invalid()
|
||||
{
|
||||
let _ = BitBlt(target, s.left.saturating_sub(origin.x), s.top.saturating_sub(origin.y), s.width, s.height, Some(dc), 0, 0, SRCCOPY);
|
||||
}
|
||||
let _ = EndPaint(hwnd, &ps);
|
||||
}
|
||||
}
|
||||
|
||||
/// What `msg` means for the sampler.
|
||||
fn input(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> Option<Input> {
|
||||
match msg {
|
||||
WM_LBUTTONDOWN => Some(Input::Down(Button::Left)),
|
||||
WM_LBUTTONUP => Some(Input::Up(Button::Left)),
|
||||
WM_RBUTTONDOWN => Some(Input::Down(Button::Right)),
|
||||
WM_RBUTTONUP => Some(Input::Up(Button::Right)),
|
||||
WM_MBUTTONDOWN | WM_XBUTTONDOWN => Some(Input::Down(Button::Other)),
|
||||
WM_MBUTTONUP | WM_XBUTTONUP => Some(Input::Up(Button::Other)),
|
||||
WM_KEYDOWN if wparam.0 == usize::from(VK_ESCAPE.0) => Some(Input::Escape),
|
||||
WM_ACTIVATE if wparam.0 & 0xFFFF == WA_INACTIVE as usize => Some(Input::Deactivated),
|
||||
WM_ACTIVATE => Some(Input::Activated),
|
||||
// `lParam` is the window that takes the capture.
|
||||
WM_CAPTURECHANGED if lparam.0 != hwnd.0 as isize => Some(Input::CaptureLost),
|
||||
WM_CLOSE => Some(Input::Closed),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "system" fn window_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
|
||||
// Activation also gives the window the keyboard focus, for Escape.
|
||||
// SAFETY: the arguments Windows passed in, for the window on this thread.
|
||||
let result = if msg == WM_ACTIVATE { unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) } } else { LRESULT(0) };
|
||||
if let Some(input) = input(hwnd, msg, wparam, lparam) {
|
||||
match with(|s| s.press.step(input)) {
|
||||
Some(Step::Pick) => finish(hwnd, |s| pick(s, hwnd, lparam)),
|
||||
Some(Step::Cancel) => finish(hwnd, |_| Ok(None)),
|
||||
Some(Step::Wait) | None => {}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
match msg {
|
||||
WM_SETCURSOR | WM_MOUSEMOVE => {
|
||||
// The cursor is set by hand: a window with the mouse capture gets no WM_SETCURSOR.
|
||||
if let Some(cursor) = with(|s| s.cursor) {
|
||||
// SAFETY: a system cursor loaded by `run`.
|
||||
unsafe { SetCursor(Some(cursor)) };
|
||||
}
|
||||
LRESULT(1)
|
||||
}
|
||||
// The copy covers the whole window.
|
||||
WM_ERASEBKGND => LRESULT(1),
|
||||
WM_PAINT => {
|
||||
paint(hwnd);
|
||||
LRESULT(0)
|
||||
}
|
||||
// The window keeps covering the virtual screen when it reaches a monitor of another scale.
|
||||
WM_DPICHANGED => LRESULT(0),
|
||||
WM_DESTROY => {
|
||||
with(|s| s.destroyed = true);
|
||||
// SAFETY: ends this thread's message loop.
|
||||
unsafe { PostQuitMessage(0) };
|
||||
LRESULT(0)
|
||||
}
|
||||
// SAFETY: the arguments Windows passed in, for the window on this thread.
|
||||
_ => unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// `COLORREF` is `0x00bbggrr`: red in the low byte. `CLR_INVALID` and other values with the high
|
||||
/// byte set are not colors.
|
||||
#[test]
|
||||
fn colorrefs_read_as_srgb() {
|
||||
assert_eq!(srgb(0x0000_00FF), Some([1.0, 0.0, 0.0]));
|
||||
assert_eq!(srgb(0x00FF_0000), Some([0.0, 0.0, 1.0]));
|
||||
assert_eq!(srgb(0x0056_3412), Some([0x12, 0x34, 0x56].map(|v| v as f32 / 255.0)));
|
||||
assert_eq!(srgb(0), Some([0.0; 3]));
|
||||
assert_eq!(srgb(0x00FF_FFFF), Some([1.0; 3]));
|
||||
assert_eq!(srgb(CLR_INVALID), None);
|
||||
assert_eq!(srgb(0x0100_0000), None);
|
||||
}
|
||||
|
||||
/// The pointer maps to the copy's pixels through the virtual screen's corner, which is negative
|
||||
/// when a monitor is left of or above the main one. A 1920 × 1080 monitor at 100% left of and
|
||||
/// lower than a 3840 × 2160 one at 150% gives a 5760 × 2160 virtual screen from (−1920, 0), in
|
||||
/// physical pixels on both.
|
||||
#[test]
|
||||
fn screen_points_map_to_pixels_of_the_copy() {
|
||||
let s = VirtualScreen::new(-1920, 0, 5760, 2160).unwrap();
|
||||
assert_eq!(s.pixel(-1920, 0), Some((0, 0)));
|
||||
assert_eq!(s.pixel(-1, 300), Some((1919, 300)));
|
||||
assert_eq!(s.pixel(0, 0), Some((1920, 0)));
|
||||
assert_eq!(s.pixel(3839, 2159), Some((5759, 2159)));
|
||||
for (x, y) in [(-1921, 0), (3840, 0), (0, -1), (0, 2160), (i32::MIN, 0), (i32::MAX, i32::MAX)] {
|
||||
assert_eq!(s.pixel(x, y), None, "({x}, {y})");
|
||||
}
|
||||
// A monitor above the main one.
|
||||
let s = VirtualScreen::new(-200, -1440, 2760, 2520).unwrap();
|
||||
assert_eq!(s.pixel(0, 0), Some((200, 1440)));
|
||||
assert_eq!(s.pixel(-200, -1440), Some((0, 0)));
|
||||
// A virtual screen at the far corner of the coordinates maps without overflowing.
|
||||
let s = VirtualScreen::new(i32::MIN, i32::MIN, 10, 10).unwrap();
|
||||
assert_eq!(s.pixel(i32::MIN + 9, i32::MIN), Some((9, 0)));
|
||||
assert_eq!(s.pixel(i32::MAX, 0), None);
|
||||
}
|
||||
|
||||
/// The release's own point picks, with signed coordinates: left of or above the client area
|
||||
/// they are negative. Past 32,767 pixels they are widened by the message's pointer position.
|
||||
#[test]
|
||||
fn the_release_point_comes_from_the_message() {
|
||||
let lparam = |x: i32, y: i32| ((y as u16 as isize) << 16) | x as u16 as isize;
|
||||
assert_eq!(message_point(lparam(100, 200), (140, 260)), (100, 200), "the lParam point wins over a nearby position");
|
||||
assert_eq!(message_point(lparam(65_636, 0), (65_636, 0)), (65_636, 0), "MSG.pt gives the high bits past 65,535 pixels");
|
||||
assert_eq!(message_point(lparam(100, 0), (100, 0)), (100, 0));
|
||||
assert_eq!(message_point(lparam(-5, -1), (10, 10)), (-5, -1));
|
||||
assert_eq!(message_point(lparam(0, 0), (0, 0)), (0, 0));
|
||||
assert_eq!(message_point(lparam(32_767, -32_768), (32_767, -32_768)), (32_767, -32_768));
|
||||
assert_eq!(message_point(lparam(40_010, 2_000), (40_000, 2_100)), (40_010, 2_000), "eight 8K monitors in a row");
|
||||
assert_eq!(message_point(lparam(61_439, 0), (61_000, 0)), (61_439, 0));
|
||||
assert_eq!(message_point(lparam(32_770, 0), (32_760, 0)), (32_770, 0));
|
||||
// A negative `lParam` on 64-bit Windows keeps only its low 32 bits as the point.
|
||||
assert_eq!(message_point(lparam(-3, -4) | !0xFFFF_FFFF, (0, 0)), (-3, -4));
|
||||
assert_eq!(message_point(lparam(5, 5), (i32::MAX, i32::MIN)), (i32::MAX, i32::MIN + 5), "saturates at the coordinate range");
|
||||
}
|
||||
|
||||
/// The size is checked before the copy is made: an empty, negative, oversized or out-of-range
|
||||
/// virtual screen is an error.
|
||||
#[test]
|
||||
fn the_copy_size_is_checked_first() {
|
||||
assert!(VirtualScreen::new(0, 0, 7680 * 8, 4320).is_ok(), "eight 8K monitors in a row");
|
||||
for (left, top, width, height) in [
|
||||
(0, 0, 0, 1080),
|
||||
(0, 0, 1920, 0),
|
||||
(0, 0, -1920, 1080),
|
||||
(0, 0, 7680 * 8, 4370),
|
||||
(0, 0, i32::MAX, i32::MAX),
|
||||
(i32::MAX - 100, 0, 1920, 1080),
|
||||
(0, i32::MAX - 100, 1920, 1080),
|
||||
] {
|
||||
assert!(VirtualScreen::new(left, top, width, height).is_err(), "{left} {top} {width} {height}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A left click picks when it is released; Escape, a click of any other button, closing the
|
||||
/// window and losing the mouse cancel; losing the focus cancels once the window had it. A
|
||||
/// release whose press began elsewhere does nothing.
|
||||
#[test]
|
||||
fn clicks_and_keys_pick_or_cancel() {
|
||||
let run = |inputs: &[Input]| {
|
||||
let mut press = Press::default();
|
||||
inputs.iter().map(|&i| press.step(i)).find(|&s| s != Step::Wait).unwrap_or(Step::Wait)
|
||||
};
|
||||
use Input::{Activated, CaptureLost, Closed, Deactivated, Escape};
|
||||
let (left_down, left_up) = (Input::Down(Button::Left), Input::Up(Button::Left));
|
||||
let (right_down, right_up) = (Input::Down(Button::Right), Input::Up(Button::Right));
|
||||
let (other_down, other_up) = (Input::Down(Button::Other), Input::Up(Button::Other));
|
||||
assert_eq!(run(&[Activated, left_down, left_up]), Step::Pick);
|
||||
assert_eq!(run(&[left_down, left_up]), Step::Pick, "a window that never became active still takes a click");
|
||||
assert_eq!(run(&[Activated, right_down, right_up]), Step::Cancel);
|
||||
assert_eq!(run(&[Activated, other_down, other_up]), Step::Cancel, "the middle and side buttons cancel");
|
||||
assert_eq!(run(&[Activated, other_down, left_up]), Step::Wait);
|
||||
assert_eq!(run(&[Activated, Escape]), Step::Cancel);
|
||||
assert_eq!(run(&[Activated, Deactivated]), Step::Cancel);
|
||||
assert_eq!(run(&[Deactivated]), Step::Wait);
|
||||
assert_eq!(run(&[CaptureLost]), Step::Cancel);
|
||||
assert_eq!(run(&[Closed]), Step::Cancel);
|
||||
assert_eq!(run(&[Activated, left_up, right_up, other_up]), Step::Wait, "releases of presses made before the window showed");
|
||||
assert_eq!(run(&[left_down, right_down, left_up]), Step::Wait, "the right button replaced the left one");
|
||||
assert_eq!(run(&[right_down, left_down, left_up]), Step::Pick);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,19 +1,20 @@
|
||||
use craft::color_ui::ui::{ScreenPickGesture, StillCapture};
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use super::*;
|
||||
use crate::panels::color::in_gamut;
|
||||
|
||||
fn app() -> VectorcraftApp {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
fn frame(app: &mut VectorcraftApp) {
|
||||
fn app() -> (VectorcraftApp, egui::Context) {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut out = ctx.run_ui(Default::default(), |ui| super::super::show(app, ui.ctx()));
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.ui_ctx = Some(ctx.clone());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
|
||||
(app, ctx)
|
||||
}
|
||||
|
||||
fn frame(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let mut out = ctx.run_ui(Default::default(), |ui| super::pump(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
|
||||
@@ -21,868 +22,195 @@ fn fill_hex(app: &VectorcraftApp) -> String {
|
||||
crate::panels::current_paints(app).0.color().unwrap().to_hex()
|
||||
}
|
||||
|
||||
/// Runs one frame of the dialog with `events` in `ctx`, which keeps the keyboard focus from
|
||||
/// frame to frame, and returns the texts drawn with their screen rects.
|
||||
fn frame_in(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>) -> Vec<(String, Rect)> {
|
||||
let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| super::super::show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
fn collect(s: &egui::Shape, out: &mut Vec<(String, Rect)>) {
|
||||
match s {
|
||||
egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())),
|
||||
egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let mut texts = vec![];
|
||||
out.shapes.iter().for_each(|c| collect(&c.shape, &mut texts));
|
||||
texts
|
||||
fn id(app: &VectorcraftApp) -> DialogId {
|
||||
app.color_dialogs.pickers.last().unwrap().id
|
||||
}
|
||||
|
||||
/// Returns the label of the value field that has the keyboard, which is the letter (or `#`)
|
||||
/// nearest to the field's left on its row, and the field's rect. Returns `None` when no text
|
||||
/// field has the keyboard.
|
||||
fn focused_field(ctx: &egui::Context, texts: &[(String, Rect)]) -> Option<(String, Rect)> {
|
||||
let id = ctx.memory(|m| m.focused()).filter(|&id| egui::TextEdit::load_state(ctx, id).is_some())?;
|
||||
let field = ctx.read_response(id)?.rect;
|
||||
let labels = ["H", "S", "B", "R", "G", "#", "L", "a", "b", "C", "M", "Y", "K"];
|
||||
let (label, _) = texts
|
||||
.iter()
|
||||
.filter(|(t, r)| labels.contains(&t.as_str()) && r.max.x <= field.min.x && field.y_range().contains(r.center().y))
|
||||
.max_by(|a, b| a.1.max.x.total_cmp(&b.1.max.x))?;
|
||||
Some((label.clone(), field))
|
||||
/// `ui.dialog.set {field: "color"}` on the newest picker, then a pass.
|
||||
fn set_hex(app: &mut VectorcraftApp, ctx: &egui::Context, hex: &str) {
|
||||
let id = id(app);
|
||||
app.dialogs().unwrap().with(|h| h.set_json_field(ctx, id, "color", json!(hex)).unwrap());
|
||||
frame(app, ctx);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn field_and_slider_map_back_per_channel() {
|
||||
let p = Picked::of(Color::rgb8(51, 153, 204));
|
||||
for ch in Channel::ALL {
|
||||
let (z, x, y) = field_pos(ch, &p);
|
||||
assert_eq!(field_pick(ch, z, x, y).color.to_hex(), "#3399cc", "{ch:?}");
|
||||
assert_eq!(Channel::parse(ch.id()), Some(ch));
|
||||
}
|
||||
// Hue: x is saturation, y brightness (white at the top left, black along the bottom).
|
||||
assert_eq!(field_pick(Channel::Hue, 0.0, 0.0, 0.0).color.to_hex(), "#ffffff");
|
||||
assert_eq!(field_pick(Channel::Hue, 0.0, 1.0, 0.0).color.to_hex(), "#ff0000");
|
||||
assert_eq!(field_pick(Channel::Hue, 0.5, 1.0, 1.0).color.to_hex(), "#000000");
|
||||
// Red: the slider is red, x blue and y green (green grows upwards).
|
||||
assert_eq!(field_pick(Channel::Red, 1.0, 1.0, 0.0).color.to_hex(), "#ffffff");
|
||||
assert_eq!(field_pick(Channel::Red, 0.0, 1.0, 1.0).color.to_hex(), "#0000ff");
|
||||
assert_eq!(field_pick(Channel::Green, 1.0, 0.0, 1.0).color.to_hex(), "#00ff00");
|
||||
assert_eq!(field_pick(Channel::Blue, 0.0, 1.0, 1.0).color.to_hex(), "#ff0000");
|
||||
// The hue slider shows the spectrum whatever the colour; the others vary one component.
|
||||
assert_eq!(slider_color(Channel::Hue, 1.0 / 3.0, 0.0, 1.0).to_hex(), "#00ff00");
|
||||
assert_eq!(slider_color(Channel::Saturation, 0.0, 0.0, 0.0).to_hex(), "#ffffff");
|
||||
// A grey keeps the hue it was picked with.
|
||||
let grey = field_pick(Channel::Hue, 0.5, 0.0, 0.5);
|
||||
assert_eq!(grey.hsb[0], 180.0);
|
||||
assert_eq!(field_pos(Channel::Hue, &grey).0, 0.5);
|
||||
fn ok(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let id = id(app);
|
||||
assert!(app.dialogs().unwrap().with(|h| h.confirm_by_id(ctx, id)));
|
||||
frame(app, ctx);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_web_colors_snaps() {
|
||||
let p = Picked::of(Color::rgb8(230, 120, 40));
|
||||
assert_eq!(p.snapped(false), p);
|
||||
assert_eq!(p.snapped(true).color.to_hex(), "#ff6633");
|
||||
assert!(is_web_safe(&p.snapped(true).color));
|
||||
let mut d = Dialog::new(KIND, json!({"color": "#e67828", "webOnly": true}));
|
||||
assert_eq!(picked(&d).color.to_hex(), "#ff6633");
|
||||
d.fields.insert("webOnly".into(), json!(false));
|
||||
assert_eq!(picked(&d).color.to_hex(), "#e67828");
|
||||
fn cancel(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let id = id(app);
|
||||
assert!(app.dialogs().unwrap().with(|h| h.cancel_by_id(ctx, id)));
|
||||
frame(app, ctx);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gamut_correction_gives_a_printable_colour() {
|
||||
let mut app = app();
|
||||
let blue = Color::rgb(0.0, 0.0, 1.0);
|
||||
assert!(blue.out_of_gamut());
|
||||
let fix = in_gamut(&mut app, &blue).expect("pure blue can't be printed");
|
||||
assert!(!fix.out_of_gamut(), "{fix:?}");
|
||||
assert!(matches!(fix, Color::Rgb { .. }));
|
||||
assert_eq!(in_gamut(&mut app, &Color::rgb8(128, 128, 128)), None);
|
||||
// The dialog and the Color panel ask through a cache.
|
||||
let ctx = egui::Context::default();
|
||||
assert_eq!(gamut_fix(&mut app, &ctx, "picker-gamut", &blue), Some(fix));
|
||||
assert_eq!(gamut_fix(&mut app, &ctx, "picker-gamut", &blue), Some(fix));
|
||||
assert_eq!(gamut_fix(&mut app, &ctx, "picker-gamut", &Color::rgb8(128, 128, 128)), None);
|
||||
fn undo_len(app: &VectorcraftApp) -> usize {
|
||||
app.session.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// The cached warning follows the CMYK space it is checked in: assigning the document a CMYK
|
||||
/// profile, removing it, or changing the working CMYK space updates it for the same color.
|
||||
#[test]
|
||||
fn gamut_warning_follows_a_profile_change() {
|
||||
const CHILD: &str = "VECTORCRAFT_TEST_GAMUT_PROFILE_CHANGE";
|
||||
if std::env::var_os(CHILD).is_none() {
|
||||
// Color settings are process-wide: change them in a separate test process.
|
||||
let output = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "dialogs::color_picker::tests::gamut_warning_follows_a_profile_change", "--nocapture"])
|
||||
.env(CHILD, "1")
|
||||
.output()
|
||||
.unwrap();
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
|
||||
"isolated gamut test failed:\n{stdout}\n{}",
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
return;
|
||||
}
|
||||
use vectorcraft_color::cms;
|
||||
let mut app = app();
|
||||
let ctx = egui::Context::default();
|
||||
let blue = Color::rgb(0.0, 0.0, 1.0);
|
||||
let fix = gamut_fix(&mut app, &ctx, "picker-gamut", &blue);
|
||||
assert!(fix.is_some(), "pure blue is out of the default CMYK gamut");
|
||||
// Device CMYK has no gamut to fall outside of.
|
||||
app.run("edit.assignProfile", json!({"cmyk": cms::DEVICE_CMYK})).unwrap();
|
||||
assert_eq!(gamut_fix(&mut app, &ctx, "picker-gamut", &blue), None);
|
||||
app.run("edit.assignProfile", json!({"cmyk": null})).unwrap();
|
||||
assert_eq!(gamut_fix(&mut app, &ctx, "picker-gamut", &blue), fix);
|
||||
app.run("edit.colorSettings", json!({"cmyk": cms::DEVICE_CMYK})).unwrap();
|
||||
assert_eq!(gamut_fix(&mut app, &ctx, "picker-gamut", &blue), None);
|
||||
app.run("edit.colorSettings", json!({"cmyk": cms::GENERIC_CMYK})).unwrap();
|
||||
assert_eq!(gamut_fix(&mut app, &ctx, "picker-gamut", &blue), fix);
|
||||
}
|
||||
|
||||
/// Loading a new file of the document's assigned CMYK profile, under the same name, updates the
|
||||
/// cached warning for the same color.
|
||||
#[test]
|
||||
fn gamut_warning_follows_a_profile_loaded_again() {
|
||||
const CHILD: &str = "VECTORCRAFT_TEST_GAMUT_PROFILE_RELOAD";
|
||||
if std::env::var_os(CHILD).is_none() {
|
||||
// Color settings and loaded profiles are process-wide: change them in a separate test process.
|
||||
let output = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "dialogs::color_picker::tests::gamut_warning_follows_a_profile_loaded_again", "--nocapture"])
|
||||
.env(CHILD, "1")
|
||||
.output()
|
||||
.unwrap();
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(
|
||||
output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"),
|
||||
"isolated gamut test failed:\n{stdout}\n{}",
|
||||
String::from_utf8_lossy(&output.stderr),
|
||||
);
|
||||
return;
|
||||
}
|
||||
use vectorcraft_color::cms;
|
||||
// A built-in CMYK profile's file renamed `name`: padded with spaces, which names drop.
|
||||
let renamed = |builtin: &str, name: &str| {
|
||||
let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
|
||||
let mut bytes = cms::icc_bytes(builtin).unwrap().to_vec();
|
||||
let (from, to) = (utf16(builtin), utf16(&format!("{name:<width$}", width = builtin.len())));
|
||||
let at = bytes.windows(from.len()).position(|w| w == from).unwrap();
|
||||
bytes[at..at + to.len()].copy_from_slice(&to);
|
||||
bytes
|
||||
};
|
||||
let name = "Gamut Reload CMYK";
|
||||
let dir = vectorcraft_testkit::temp_dir("gamut-reload-cmyk");
|
||||
let mut app = app();
|
||||
let load = |app: &mut VectorcraftApp, builtin: &str| {
|
||||
let path = dir.join(format!("{}.icc", builtin.len()));
|
||||
std::fs::write(&path, renamed(builtin, name)).unwrap();
|
||||
let r = app.run("color.loadProfile", json!({"path": path.to_str().unwrap()})).unwrap();
|
||||
assert_eq!(r["name"], name);
|
||||
};
|
||||
let ctx = egui::Context::default();
|
||||
let blue = Color::rgb(0.0, 0.0, 1.0);
|
||||
load(&mut app, cms::GENERIC_CMYK);
|
||||
app.run("edit.assignProfile", json!({"cmyk": name})).unwrap();
|
||||
let before = gamut_fix(&mut app, &ctx, "picker-gamut", &blue);
|
||||
assert!(before.is_some(), "pure blue is out of the loaded profile's gamut");
|
||||
load(&mut app, cms::DEVICE_CMYK);
|
||||
let fresh = in_gamut(&mut app, &blue);
|
||||
assert_ne!(fresh, before, "the new file gives another answer");
|
||||
assert_eq!(gamut_fix(&mut app, &ctx, "picker-gamut", &blue), fresh);
|
||||
fn artboard_color(app: &VectorcraftApp) -> Option<Color> {
|
||||
app.session.doc().unwrap().doc.artboards[1].color
|
||||
}
|
||||
|
||||
/// The selected art takes each colour as it is picked; OK keeps the last as one undo step and
|
||||
/// Cancel puts the art back.
|
||||
#[test]
|
||||
fn the_selection_shows_the_colour_live() {
|
||||
let mut app = app();
|
||||
let undo = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len();
|
||||
let before = undo(&app);
|
||||
let (mut app, ctx) = app();
|
||||
let before = undo_len(&app);
|
||||
app.run("ui.colorPicker", json!({})).unwrap();
|
||||
frame(&mut app);
|
||||
frame(&mut app, &ctx);
|
||||
assert!(!app.session.in_interaction(), "nothing previews before the colour changes");
|
||||
for hex in ["ff0000", "00ff00"] {
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!(hex));
|
||||
frame(&mut app);
|
||||
assert_eq!(fill_hex(&app), format!("#{hex}"), "live, before OK");
|
||||
for hex in ["#ff0000", "#00ff00"] {
|
||||
set_hex(&mut app, &ctx, hex);
|
||||
assert_eq!(fill_hex(&app), hex, "live, before OK");
|
||||
}
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
ok(&mut app, &ctx);
|
||||
assert_eq!(fill_hex(&app), "#00ff00");
|
||||
assert_eq!(undo(&app), before + 1, "one step");
|
||||
// Cancel: back to the colour it had.
|
||||
assert_eq!(undo_len(&app), before + 1, "one step");
|
||||
app.run("ui.colorPicker", json!({})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!("0000ff"));
|
||||
frame(&mut app);
|
||||
set_hex(&mut app, &ctx, "#0000ff");
|
||||
assert_eq!(fill_hex(&app), "#0000ff");
|
||||
super::super::cancel(&mut app);
|
||||
cancel(&mut app, &ctx);
|
||||
assert_eq!(fill_hex(&app), "#00ff00");
|
||||
assert_eq!(undo(&app), before + 1);
|
||||
assert_eq!(undo_len(&app), before + 1);
|
||||
}
|
||||
|
||||
/// Opened for an artboard (Properties › Artboards › Fill), the picker starts from the artboard's
|
||||
/// background color (white without one) and shows each color on its paper live, with nothing
|
||||
/// selected. OK keeps the last as one undo step, the art's fill unchanged, and Cancel puts the
|
||||
/// artboard back.
|
||||
/// Opened for an artboard, the picker shows each colour on its paper, with the art's fill unchanged.
|
||||
#[test]
|
||||
fn an_artboard_shows_its_background_color_live() {
|
||||
let mut app = app();
|
||||
let (mut app, ctx) = app();
|
||||
app.run("select.set", json!({"ids": []})).unwrap();
|
||||
app.run("artboard.new", json!({})).unwrap();
|
||||
let color = |app: &VectorcraftApp| app.session.doc().unwrap().doc.artboards[1].color.map(|c| c.to_hex());
|
||||
let undo = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len();
|
||||
let art = app.session.doc().unwrap().doc.layers.clone();
|
||||
let before = undo(&app);
|
||||
let before = undo_len(&app);
|
||||
app.run("ui.colorPicker", json!({"artboard": 1})).unwrap();
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().str("hex"), "FFFFFF", "starts from white paper");
|
||||
frame(&mut app);
|
||||
frame(&mut app, &ctx);
|
||||
assert!(!app.session.in_interaction(), "nothing previews before the color changes");
|
||||
for hex in ["ff0000", "00ff00"] {
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!(hex));
|
||||
frame(&mut app);
|
||||
assert_eq!(color(&app), Some(format!("#{hex}")), "live, before OK");
|
||||
for hex in ["#ff0000", "#00ff00"] {
|
||||
set_hex(&mut app, &ctx, hex);
|
||||
assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some(hex), "live, before OK");
|
||||
}
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert_eq!(color(&app).as_deref(), Some("#00ff00"));
|
||||
assert_eq!(undo(&app), before + 1, "one step");
|
||||
ok(&mut app, &ctx);
|
||||
assert_eq!(undo_len(&app), before + 1, "one step");
|
||||
assert_eq!(app.session.doc().unwrap().doc.layers, art, "the art keeps its fill");
|
||||
// Cancel: back to the color it had, which the picker starts from.
|
||||
app.run("ui.colorPicker", json!({"artboard": 1})).unwrap();
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().str("hex"), "00FF00");
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!("0000ff"));
|
||||
frame(&mut app);
|
||||
assert_eq!(color(&app).as_deref(), Some("#0000ff"));
|
||||
super::super::cancel(&mut app);
|
||||
assert_eq!(color(&app).as_deref(), Some("#00ff00"));
|
||||
assert_eq!(undo(&app), before + 1);
|
||||
set_hex(&mut app, &ctx, "#0000ff");
|
||||
cancel(&mut app, &ctx);
|
||||
assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#00ff00"));
|
||||
assert!(app.run("ui.colorPicker", json!({"artboard": 9})).is_err());
|
||||
}
|
||||
|
||||
/// OK on a picker opened for an artboard without a background color, with the color left at the
|
||||
/// white it starts from, leaves the artboard without one and adds no undo step. A white the
|
||||
/// opener passes as `color` is set.
|
||||
/// OK on an untouched picker for an artboard without a color leaves it without one and adds no
|
||||
/// undo step; a white the opener passes as `color` is set.
|
||||
#[test]
|
||||
fn an_untouched_picker_leaves_an_artboard_without_a_color() {
|
||||
let mut app = app();
|
||||
let (mut app, ctx) = app();
|
||||
app.run("artboard.new", json!({})).unwrap();
|
||||
let color = |app: &VectorcraftApp| app.session.doc().unwrap().doc.artboards[1].color.map(|c| c.to_hex());
|
||||
let undo = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len();
|
||||
let before = undo(&app);
|
||||
let before = undo_len(&app);
|
||||
app.run("ui.colorPicker", json!({"artboard": 1})).unwrap();
|
||||
frame(&mut app);
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert!(app.ui.dialog.is_none(), "OK closes the picker");
|
||||
assert_eq!(color(&app), None, "no color");
|
||||
assert_eq!(undo(&app), before, "no undo step");
|
||||
frame(&mut app, &ctx);
|
||||
ok(&mut app, &ctx);
|
||||
assert_eq!(artboard_color(&app), None, "no color");
|
||||
assert_eq!(undo_len(&app), before, "no undo step");
|
||||
app.run("ui.colorPicker", json!({"artboard": 1, "color": "#ffffff"})).unwrap();
|
||||
frame(&mut app);
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert_eq!(color(&app).as_deref(), Some("#ffffff"));
|
||||
assert_eq!(undo(&app), before + 1);
|
||||
frame(&mut app, &ctx);
|
||||
ok(&mut app, &ctx);
|
||||
assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#ffffff"));
|
||||
assert_eq!(undo_len(&app), before + 1);
|
||||
}
|
||||
|
||||
/// OK on an untouched picker opened for an artboard with an RGB background color in a CMYK
|
||||
/// document keeps the RGB color and adds no undo step. A color picked in it is set as CMYK.
|
||||
/// The same for an RGB color in a CMYK document: kept untouched, CMYK once a color is picked.
|
||||
#[test]
|
||||
fn an_untouched_picker_keeps_an_artboards_rgb_color_in_a_cmyk_document() {
|
||||
let mut app = app();
|
||||
let (mut app, ctx) = app();
|
||||
app.run("artboard.new", json!({})).unwrap();
|
||||
app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap();
|
||||
app.run("artboard.setProps", json!({"index": 1, "color": "#ff0000"})).unwrap();
|
||||
let color = |app: &VectorcraftApp| app.session.doc().unwrap().doc.artboards[1].color;
|
||||
let undo = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len();
|
||||
let start = color(&app);
|
||||
let start = artboard_color(&app);
|
||||
assert!(matches!(start, Some(Color::Rgb { .. })), "set as RGB");
|
||||
let before = undo(&app);
|
||||
let before = undo_len(&app);
|
||||
app.run("ui.colorPicker", json!({"artboard": 1})).unwrap();
|
||||
frame(&mut app);
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert!(app.ui.dialog.is_none(), "OK closes the picker");
|
||||
assert_eq!(color(&app), start, "the RGB color is kept");
|
||||
assert_eq!(undo(&app), before, "no undo step");
|
||||
frame(&mut app, &ctx);
|
||||
ok(&mut app, &ctx);
|
||||
assert_eq!(artboard_color(&app), start, "the RGB color is kept");
|
||||
assert_eq!(undo_len(&app), before, "no undo step");
|
||||
app.run("ui.colorPicker", json!({"artboard": 1})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!("00ff00"));
|
||||
frame(&mut app);
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert!(matches!(color(&app), Some(Color::Cmyk { .. })), "a picked color is set as CMYK");
|
||||
assert_eq!(undo(&app), before + 1);
|
||||
}
|
||||
|
||||
/// OK on an untouched picker opened for an artboard with a background color in an RGB
|
||||
/// document keeps the color and adds no undo step.
|
||||
#[test]
|
||||
fn an_untouched_picker_adds_no_undo_step_for_an_artboards_color() {
|
||||
let mut app = app();
|
||||
app.run("artboard.new", json!({})).unwrap();
|
||||
app.run("artboard.setProps", json!({"index": 1, "color": "#ff0000"})).unwrap();
|
||||
let color = |app: &VectorcraftApp| app.session.doc().unwrap().doc.artboards[1].color.map(|c| c.to_hex());
|
||||
let undo = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len();
|
||||
let before = undo(&app);
|
||||
app.run("ui.colorPicker", json!({"artboard": 1})).unwrap();
|
||||
frame(&mut app);
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert!(app.ui.dialog.is_none(), "OK closes the picker");
|
||||
assert_eq!(color(&app).as_deref(), Some("#ff0000"));
|
||||
assert_eq!(undo(&app), before, "no undo step");
|
||||
set_hex(&mut app, &ctx, "#00ff00");
|
||||
ok(&mut app, &ctx);
|
||||
assert!(matches!(artboard_color(&app), Some(Color::Cmyk { .. })), "a picked color is set as CMYK");
|
||||
assert_eq!(undo_len(&app), before + 1);
|
||||
}
|
||||
|
||||
/// The opener's params reach the dialog and OK writes the fill or the stroke.
|
||||
#[test]
|
||||
fn open_set_hex_and_confirm_fills() {
|
||||
let mut app = app();
|
||||
let (mut app, ctx) = app();
|
||||
app.run("ui.colorPicker", json!({})).unwrap();
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!(super::super::DialogKind::of(&d.kind), Some(super::super::DialogKind::ColorPicker));
|
||||
assert_eq!(d.str("hex"), "FFFFFF", "starts from the fill");
|
||||
assert!(!d.bool("stroke"));
|
||||
frame(&mut app);
|
||||
// `ui.dialog.set {field: "hex"}` then `ui.dialog.confirm`.
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!("00ff00"));
|
||||
frame(&mut app);
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().str("hex"), "00FF00");
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert!(app.ui.dialog.is_none());
|
||||
set_hex(&mut app, &ctx, "#00ff00");
|
||||
ok(&mut app, &ctx);
|
||||
assert_eq!(fill_hex(&app), "#00ff00");
|
||||
// Without a frame in between, a set hex still wins; `color` works as well.
|
||||
app.run("ui.colorPicker", json!({"stroke": true})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!("#3366CC"));
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
set_hex(&mut app, &ctx, "#3366cc");
|
||||
ok(&mut app, &ctx);
|
||||
assert_eq!(crate::panels::current_paints(&app).1.color().unwrap().to_hex(), "#3366cc");
|
||||
// The stroke proxy is in front now: the opener follows it unless told otherwise.
|
||||
app.run("ui.colorPicker", json!({})).unwrap();
|
||||
assert!(app.ui.dialog.as_ref().unwrap().bool("stroke"));
|
||||
app.run("ui.colorPicker", json!({"stroke": false})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!({"c": 0, "m": 1, "y": 1, "k": 0}));
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert!(matches!(crate::panels::current_paints(&app).0.color(), Some(Color::Cmyk { .. })), "CMYK is kept");
|
||||
assert!(app.run("ui.colorPicker", json!({"color": "nope"})).is_err());
|
||||
// Colours take every form the paint commands take (CMYK in percent too).
|
||||
app.run("ui.colorPicker", json!({"stroke": false, "color": {"c": 0, "m": 100, "y": 100, "k": 0}})).unwrap();
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
frame(&mut app, &ctx);
|
||||
ok(&mut app, &ctx);
|
||||
assert_eq!(crate::panels::current_paints(&app).0.color(), Some(Color::cmyk(0.0, 1.0, 1.0, 0.0)));
|
||||
}
|
||||
|
||||
/// OK makes the picked fill or stroke color the Color Guide's base color (#3137); Cancel and a
|
||||
/// color picked for an artboard leave the base as it is.
|
||||
/// OK makes the picked fill or stroke color the Color Guide's base color; Cancel and an artboard's
|
||||
/// color leave the base as it is.
|
||||
#[test]
|
||||
fn ok_makes_the_picked_color_the_color_guides_base() {
|
||||
let mut app = app();
|
||||
let (mut app, ctx) = app();
|
||||
let base = |app: &VectorcraftApp| crate::panels::color_guide::base_color(app).to_hex();
|
||||
app.ui.color_guide_base = Some(Color::WHITE);
|
||||
app.run("ui.colorPicker", json!({})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!("2050a0"));
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
set_hex(&mut app, &ctx, "#2050a0");
|
||||
ok(&mut app, &ctx);
|
||||
assert_eq!(base(&app), "#2050a0");
|
||||
app.run("ui.colorPicker", json!({"stroke": true})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!("a02050"));
|
||||
frame(&mut app);
|
||||
super::super::cancel(&mut app);
|
||||
set_hex(&mut app, &ctx, "#a02050");
|
||||
cancel(&mut app, &ctx);
|
||||
assert_eq!(base(&app), "#2050a0", "Cancel keeps the base");
|
||||
app.run("select.set", json!({"ids": []})).unwrap();
|
||||
app.run("artboard.new", json!({})).unwrap();
|
||||
app.run("ui.colorPicker", json!({"artboard": 1})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!("00ff00"));
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
set_hex(&mut app, &ctx, "#00ff00");
|
||||
ok(&mut app, &ctx);
|
||||
assert_eq!(base(&app), "#2050a0", "an artboard's color leaves the base");
|
||||
}
|
||||
|
||||
/// #1692: Tab goes through one color model's fields before the next: H, S, B, then R, G, B, the
|
||||
/// hex field, then L, a, b, then C, M, Y, K. Each Lab or CMYK field is level with the field on
|
||||
/// its left.
|
||||
#[test]
|
||||
fn tab_goes_through_one_color_models_fields_before_the_next() {
|
||||
let mut app = app();
|
||||
app.run("ui.colorPicker", json!({})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let tab = egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
|
||||
// The picker opens with the keyboard in H. The loop presses Tab until K has the keyboard
|
||||
// and records each stop. A stop is `None` when no text field has the keyboard, as at a
|
||||
// channel's radio button.
|
||||
let mut texts = vec![];
|
||||
for _ in 0..3 {
|
||||
texts = frame_in(&ctx, &mut app, vec![]);
|
||||
}
|
||||
let mut stops = vec![focused_field(&ctx, &texts)];
|
||||
while stops.len() < 40 && stops.last().and_then(|s| s.as_ref()).is_none_or(|(label, _)| label != "K") {
|
||||
texts = frame_in(&ctx, &mut app, vec![tab.clone()]);
|
||||
stops.push(focused_field(&ctx, &texts));
|
||||
}
|
||||
let names: Vec<Option<&str>> = stops.iter().map(|s| s.as_ref().map(|(label, _)| label.as_str())).collect();
|
||||
let fields: Vec<&str> = names.iter().flatten().copied().collect();
|
||||
assert_eq!(fields, ["H", "S", "B", "R", "G", "B", "#", "L", "a", "b", "C", "M", "Y", "K"], "{names:?}");
|
||||
assert_eq!(names[names.len() - 2..], [Some("Y"), Some("K")], "one Tab takes Y to K");
|
||||
let found: Vec<&(String, Rect)> = stops.iter().flatten().collect();
|
||||
for (left, right) in found[..7].iter().zip(&found[7..]) {
|
||||
// Two grids: their rows land on the same subpixel-rounded line, not necessarily bit-equal.
|
||||
assert!((left.1.center().y - right.1.center().y).abs() <= 0.5, "{} and {} are level", left.0, right.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A confirmed colour in a CMYK document is CMYK.
|
||||
#[test]
|
||||
fn every_mode_draws_and_cmyk_documents_get_cmyk() {
|
||||
let mut app = app();
|
||||
for fields in
|
||||
[json!({"channel": "red"}), json!({"channel": "brightness", "webOnly": true}), json!({"swatches": true}), json!({"color": "#0000ff"})]
|
||||
{
|
||||
app.run("ui.colorPicker", json!({})).unwrap();
|
||||
let d = app.ui.dialog.as_mut().unwrap();
|
||||
for (k, v) in fields.as_object().unwrap() {
|
||||
d.fields.insert(k.clone(), v.clone());
|
||||
}
|
||||
frame(&mut app);
|
||||
assert!(app.ui.dialog.is_some());
|
||||
}
|
||||
let (mut app, ctx) = app();
|
||||
app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap();
|
||||
app.run("ui.colorPicker", json!({"color": "#ff0000"})).unwrap();
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
frame(&mut app, &ctx);
|
||||
ok(&mut app, &ctx);
|
||||
assert!(matches!(crate::panels::current_paints(&app).0.color(), Some(Color::Cmyk { .. })));
|
||||
}
|
||||
/// Inspect actual painted controls, rather than a second implementation of the layout.
|
||||
#[derive(Default)]
|
||||
struct Drawn {
|
||||
texts: Vec<(String, Rect)>,
|
||||
visible_texts: Vec<String>,
|
||||
boxes: Vec<Rect>,
|
||||
fields: Vec<Rect>,
|
||||
}
|
||||
|
||||
impl Drawn {
|
||||
/// Collects painted text, control bounds and color meshes, recording text visibility
|
||||
/// against the clip rectangle so tests can detect clipped labels.
|
||||
fn collect(&mut self, shape: &egui::Shape, clip: Rect) {
|
||||
match shape {
|
||||
egui::Shape::Text(t) => {
|
||||
self.texts.push((t.galley.text().into(), t.visual_bounding_rect()));
|
||||
if clip.expand(1.0).contains_rect(t.visual_bounding_rect()) {
|
||||
self.visible_texts.push(t.galley.text().into());
|
||||
}
|
||||
}
|
||||
egui::Shape::Rect(r) => self.boxes.push(r.rect),
|
||||
egui::Shape::Mesh(m) if m.vertices.len() > 100 => self.fields.push(m.calc_bounds()),
|
||||
egui::Shape::Vec(v) => v.iter().for_each(|s| self.collect(s, clip)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the bounds of exactly one painted label, failing on missing or duplicate text.
|
||||
fn text(&self, label: &str) -> Rect {
|
||||
let found: Vec<_> = self.texts.iter().filter(|(s, _)| s == label).collect();
|
||||
assert_eq!(found.len(), 1, "one {label}, including no duplicate footer: {:?}", self.texts);
|
||||
found[0].1
|
||||
}
|
||||
|
||||
/// Finds the smallest painted control containing a unique label's center.
|
||||
fn control(&self, label: &str) -> Rect {
|
||||
let center = self.text(label).center();
|
||||
self.boxes.iter().filter(|r| r.contains(center)).min_by(|a, b| a.area().total_cmp(&b.area())).copied().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs a dialog frame with real egui input at a physical window size, accounting for UI zoom,
|
||||
/// and returns the painted controls for layout and interaction assertions.
|
||||
fn draw(ctx: &egui::Context, app: &mut VectorcraftApp, size: egui::Vec2, events: Vec<egui::Event>) -> Drawn {
|
||||
let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, size / ctx.zoom_factor())), events, ..Default::default() };
|
||||
let mut out = ctx.run_ui(input, |ui| {
|
||||
crate::shortcuts::handle(app, ui.ctx());
|
||||
super::super::show(app, ui.ctx());
|
||||
});
|
||||
let mut drawn = Drawn::default();
|
||||
for shape in &out.shapes {
|
||||
drawn.collect(&shape.shape, shape.clip_rect);
|
||||
}
|
||||
out.textures_delta.clear();
|
||||
drawn
|
||||
}
|
||||
|
||||
/// The physical window size used for pointer and keyboard interaction tests.
|
||||
fn screen() -> egui::Vec2 {
|
||||
vec2(1280.0, 900.0)
|
||||
}
|
||||
|
||||
/// Lets the auto-sized dialog settle over six frames and returns the next frame's controls.
|
||||
fn settled(ctx: &egui::Context, app: &mut VectorcraftApp, size: egui::Vec2) -> Drawn {
|
||||
for _ in 0..6 {
|
||||
draw(ctx, app, size, vec![]);
|
||||
}
|
||||
draw(ctx, app, size, vec![])
|
||||
}
|
||||
|
||||
/// Creates a persistent test context with the application's fonts and default theme.
|
||||
fn context() -> egui::Context {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
crate::theme::apply(&ctx, Default::default());
|
||||
ctx
|
||||
}
|
||||
|
||||
/// Sends a primary pointer press and release in separate frames at the given position.
|
||||
fn click_at(ctx: &egui::Context, app: &mut VectorcraftApp, at: egui::Pos2) {
|
||||
for pressed in [true, false] {
|
||||
draw(
|
||||
ctx,
|
||||
app,
|
||||
screen(),
|
||||
vec![
|
||||
egui::Event::PointerMoved(at),
|
||||
egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() },
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an unmodified, non-repeating key press for dialog shortcut tests.
|
||||
fn key(key: egui::Key) -> egui::Event {
|
||||
egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }
|
||||
}
|
||||
|
||||
/// Checks accessible action names and each channel slider's displayed value, range and units.
|
||||
#[test]
|
||||
fn compact_picker_preserves_screen_reader_controls_and_channel_values() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
for (channel, value, maximum, text) in [
|
||||
(Channel::Hue, 210.0, 360.0, "210°"),
|
||||
(Channel::Saturation, 67.0, 100.0, "67%"),
|
||||
(Channel::Brightness, 60.0, 100.0, "60%"),
|
||||
(Channel::Red, 51.0, 255.0, "51"),
|
||||
(Channel::Green, 102.0, 255.0, "102"),
|
||||
(Channel::Blue, 153.0, 255.0, "153"),
|
||||
] {
|
||||
let mut app = app();
|
||||
app.services.screen_color = Some(Box::new(|| Ok(std::sync::mpsc::channel().1)));
|
||||
open(&mut app, &json!({"color": "#336699"})).unwrap();
|
||||
let mut d = app.ui.dialog.take().unwrap();
|
||||
d.fields.insert("channel".into(), json!(channel.id()));
|
||||
let tree = widgets::accessibility_tests::tree(|ui| {
|
||||
body(&mut app, ui, &mut d);
|
||||
});
|
||||
let slider = tree.iter().find(|n| n.role() == Role::Slider && n.label() == Some(channel.label())).unwrap();
|
||||
assert_eq!(slider.numeric_value(), Some(value));
|
||||
assert_eq!(slider.min_numeric_value(), Some(0.0));
|
||||
assert_eq!(slider.max_numeric_value(), Some(maximum));
|
||||
assert_eq!(slider.value(), Some(text));
|
||||
for label in ["OK", "Cancel", "Color Swatches", "Sample Color from Screen"] {
|
||||
assert!(tree.iter().any(|n| n.role() == Role::Button && n.label() == Some(label)), "missing button: {label}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks aligned actions and input rows at two UI scales, and stable dimensions when
|
||||
/// switching between color models and swatches.
|
||||
#[test]
|
||||
fn inline_actions_are_aligned_and_modes_keep_the_window_size() {
|
||||
// Language selection is process-global; German is checked in the native app instead
|
||||
// of racing the other parallel UI tests by changing the locale here.
|
||||
for zoom in [1.0, 1.5] {
|
||||
let (ctx, mut app) = (context(), app());
|
||||
ctx.set_zoom_factor(zoom);
|
||||
app.run("ui.colorPicker", json!({})).unwrap();
|
||||
let drawn = settled(&ctx, &mut app, screen());
|
||||
let ok = drawn.control(tl!("OK"));
|
||||
let cancel = drawn.control(tl!("Cancel"));
|
||||
let toggle = drawn.control(tl!("Color Swatches"));
|
||||
assert!(ok.bottom() < cancel.top() && cancel.bottom() < toggle.top());
|
||||
for r in [cancel, toggle] {
|
||||
assert!((r.left() - ok.left()).abs() < 1.0 && (r.width() - ok.width()).abs() < 1.0);
|
||||
}
|
||||
let field = drawn.fields.iter().max_by(|a, b| a.area().total_cmp(&b.area())).unwrap();
|
||||
assert!((field.width() - field.height()).abs() < 1.0);
|
||||
assert!((field.top() - ok.top()).abs() < 1.0);
|
||||
let k = drawn.text("K");
|
||||
let last_input = drawn
|
||||
.boxes
|
||||
.iter()
|
||||
.find(|r| (r.width() - VALUE_W).abs() < 0.5 && r.left() > k.right() && r.contains(egui::pos2(r.center().x, k.center().y)))
|
||||
.unwrap();
|
||||
assert!((last_input.bottom() - field.bottom()).abs() < 2.0, "{last_input:?} vs {field:?}");
|
||||
// Fonts and translated actions may leave one normal gutter, but never an unused column.
|
||||
assert!((last_input.right() - ok.right()).abs() < COLUMN_GAP, "no unused column beside the inputs: {last_input:?} vs {ok:?}");
|
||||
let id = egui::Id::unique(("dialog", KIND));
|
||||
let before = ctx.memory(|m| m.area_rect(id)).unwrap();
|
||||
assert!(drawn.boxes.iter().all(|r| r.left() >= before.left() - 1.0 && r.right() <= before.right() + 1.0), "controls fit horizontally");
|
||||
let title = drawn.text(tl!("Color Picker"));
|
||||
assert!((title.center().x - before.center().x).abs() < 1.0, "centred heading");
|
||||
assert!(title.bottom() < field.top(), "a separate title band above the content");
|
||||
assert!(drawn.visible_texts.iter().any(|s| s == tl!("Only Web Colors")), "the checkbox label is fully visible");
|
||||
assert!(drawn.text("L").top() - toggle.bottom() >= PREVIEW_GAP, "space below the actions");
|
||||
click_at(&ctx, &mut app, toggle.center());
|
||||
assert!(app.ui.dialog.as_ref().unwrap().bool("swatches"));
|
||||
let drawn = settled(&ctx, &mut app, screen());
|
||||
assert!((drawn.control(tl!("Color Models")).width() - ok.width()).abs() < 1.0);
|
||||
let after = ctx.memory(|m| m.area_rect(id)).unwrap();
|
||||
assert!((before.size() - after.size()).length() < 1.0, "{before:?} vs {after:?}");
|
||||
assert!(drawn.boxes.iter().all(|r| r.left() >= after.left() - 1.0 && r.right() <= after.right() + 1.0), "swatch controls fit horizontally");
|
||||
click_at(&ctx, &mut app, drawn.text(tl!("Color Models")).center());
|
||||
assert!(!app.ui.dialog.as_ref().unwrap().bool("swatches"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Clicks the sampler above the field, receives a color and checks Cancel restores the paint.
|
||||
/// The pipette's pick reaches the dialog, previews on the art, and Cancel restores the original.
|
||||
#[test]
|
||||
fn sampler_above_the_field_previews_and_cancel_restores_the_original() {
|
||||
let (ctx, mut app) = (context(), app());
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let mut receiver = Some(rx);
|
||||
app.services.screen_color = Some(Box::new(move || receiver.take().ok_or("sampler already started".into())));
|
||||
let (mut app, ctx) = app();
|
||||
app.run("ui.colorPicker", json!({})).unwrap();
|
||||
let original = fill_hex(&app);
|
||||
let drawn = settled(&ctx, &mut app, screen());
|
||||
let field = drawn.fields.iter().max_by(|a, b| a.area().total_cmp(&b.area())).unwrap();
|
||||
let hover = egui::pos2(field.right() - 12.0, field.top() - 20.0);
|
||||
draw(&ctx, &mut app, screen(), vec![egui::Event::PointerMoved(hover)]);
|
||||
let drawn = settled(&ctx, &mut app, screen());
|
||||
let sampler = drawn.boxes.iter().find(|r| r.size() == vec2(24.0, 24.0) && r.bottom() < field.top()).unwrap();
|
||||
assert!(sampler.top() > drawn.text(tl!("Color Picker")).bottom() && sampler.right() <= field.right());
|
||||
click_at(&ctx, &mut app, sampler.center());
|
||||
assert!(app.screen_sampler.is_some(), "the button above the field starts the host sampler");
|
||||
tx.send(Ok(Some([0.0, 1.0, 0.0]))).unwrap();
|
||||
crate::screen_color::poll(&mut app, &ctx);
|
||||
let drawn = settled(&ctx, &mut app, screen());
|
||||
let owner = super::owner(id(&app));
|
||||
assert_eq!(screen_color::hold(&mut app, &ctx, owner, ScreenPickGesture::Clicked), None);
|
||||
assert!(app.screen_pick.busy());
|
||||
let green = Srgba { r: 0.0, g: 1.0, b: 0.0, a: 1.0 };
|
||||
for _ in 0..2 {
|
||||
app.screen_pick.tick_with(&ctx, screen_color::target(&ctx), &|| Box::new(StillCapture::color(green)));
|
||||
}
|
||||
frame(&mut app, &ctx);
|
||||
assert_eq!(fill_hex(&app), "#00ff00");
|
||||
click_at(&ctx, &mut app, drawn.text(tl!("Cancel")).center());
|
||||
assert!(app.ui.dialog.is_none());
|
||||
cancel(&mut app, &ctx);
|
||||
assert_eq!(fill_hex(&app), original);
|
||||
}
|
||||
|
||||
/// Checks both correction warnings fit below the preview without widening the dialog,
|
||||
/// and that clicking the web warning still corrects the color.
|
||||
#[test]
|
||||
fn warnings_fit_below_the_preview_without_widening_the_dialog() {
|
||||
let (ctx, mut app) = (context(), app());
|
||||
app.run("ui.colorPicker", json!({"color":"#ffffff"})).unwrap();
|
||||
settled(&ctx, &mut app, screen());
|
||||
let id = egui::Id::unique(("dialog", KIND));
|
||||
let before = ctx.memory(|m| m.area_rect(id)).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!("0000FE"));
|
||||
let drawn = settled(&ctx, &mut app, screen());
|
||||
let ok = drawn.control(tl!("OK"));
|
||||
let toggle = drawn.control(tl!("Color Swatches"));
|
||||
let h = drawn.text("H");
|
||||
let mut warnings: Vec<_> =
|
||||
drawn.boxes.iter().filter(|r| (r.width() - 16.0).abs() < 0.5 && (r.height() - 16.0).abs() < 0.5 && r.bottom() < h.top()).copied().collect();
|
||||
warnings.dedup(); // The tile's fill and border share one rectangle.
|
||||
assert_eq!(warnings.len(), 2, "gamut and web correction chips are both present");
|
||||
for r in &warnings {
|
||||
assert!(r.right() < ok.left() && r.bottom() <= toggle.bottom());
|
||||
assert!(r.top() > ok.top() + CHIP_H, "warnings below the preview");
|
||||
}
|
||||
let after = ctx.memory(|m| m.area_rect(id)).unwrap();
|
||||
assert!((before.size() - after.size()).length() < 1.0, "{before:?} vs {after:?}");
|
||||
// The cube icon left of the web correction corrects the color too.
|
||||
click_at(&ctx, &mut app, warnings[1].center() - vec2(19.0, 0.0));
|
||||
assert!(is_web_safe(&picked(app.ui.dialog.as_ref().unwrap()).color), "web correction remains clickable");
|
||||
}
|
||||
|
||||
/// Drags the custom title band and checks the dialog moves by the pointer's displacement.
|
||||
#[test]
|
||||
fn colour_picker_moves_by_its_title_band() {
|
||||
let (ctx, mut app) = (context(), app());
|
||||
app.run("ui.colorPicker", json!({})).unwrap();
|
||||
let drawn = settled(&ctx, &mut app, screen());
|
||||
let title = drawn.text(tl!("Color Picker")).center();
|
||||
let id = egui::Id::unique(("dialog", KIND));
|
||||
let before = ctx.memory(|m| m.area_rect(id)).unwrap();
|
||||
let pointer = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
draw(&ctx, &mut app, screen(), vec![egui::Event::PointerMoved(title), pointer(title, true)]);
|
||||
for i in 1..=4 {
|
||||
draw(&ctx, &mut app, screen(), vec![egui::Event::PointerMoved(title + vec2(6.0, 4.0) * i as f32)]);
|
||||
}
|
||||
draw(&ctx, &mut app, screen(), vec![pointer(title + vec2(24.0, 16.0), false)]);
|
||||
settled(&ctx, &mut app, screen());
|
||||
let after = ctx.memory(|m| m.area_rect(id)).unwrap();
|
||||
assert!((after.center() - before.center() - vec2(24.0, 16.0)).length() < 1.5);
|
||||
assert!(app.ui.dialog.is_some());
|
||||
}
|
||||
|
||||
/// Checks OK and Enter commit typed values as one undo step, while Cancel and Escape
|
||||
/// restore the original paint after a live preview.
|
||||
#[test]
|
||||
fn inline_ok_commits_typed_input_and_cancel_restores_the_preview() {
|
||||
for enter in [false, true] {
|
||||
let (ctx, mut app) = (context(), app());
|
||||
app.run("ui.colorPicker", json!({"color": "#ff0000"})).unwrap();
|
||||
let drawn = settled(&ctx, &mut app, screen());
|
||||
let undo = app.session.doc().unwrap().history.undo.len();
|
||||
// The first numeric field has selected text, just as in the other form dialogs.
|
||||
draw(&ctx, &mut app, screen(), vec![egui::Event::Text("120".into())]);
|
||||
if enter {
|
||||
draw(&ctx, &mut app, screen(), vec![key(egui::Key::Enter)]);
|
||||
} else {
|
||||
click_at(&ctx, &mut app, drawn.text(tl!("OK")).center());
|
||||
}
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert_eq!(fill_hex(&app), "#00ff00");
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1);
|
||||
app.run("ui.colorPicker", json!({})).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("hex".into(), json!("0000ff"));
|
||||
let drawn = settled(&ctx, &mut app, screen());
|
||||
assert_eq!(fill_hex(&app), "#0000ff");
|
||||
if enter {
|
||||
draw(&ctx, &mut app, screen(), vec![key(egui::Key::Escape)]);
|
||||
} else {
|
||||
click_at(&ctx, &mut app, drawn.text(tl!("Cancel")).center());
|
||||
}
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert_eq!(fill_hex(&app), "#00ff00");
|
||||
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks shrinking and stacking keep the dialog inside small windows, vertical scrolling
|
||||
/// reaches the actions and last input, and Enter can still confirm.
|
||||
#[test]
|
||||
fn compact_picker_shrinks_then_scrolls_without_enlarging_the_window() {
|
||||
for size in [vec2(740.0, 600.0), vec2(540.0, 420.0), vec2(400.0, 280.0)] {
|
||||
let (ctx, mut app) = (context(), app());
|
||||
app.run("ui.colorPicker", json!({"color": "#0000ff"})).unwrap();
|
||||
let drawn = settled(&ctx, &mut app, size);
|
||||
let outer = ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", KIND)))).unwrap();
|
||||
assert!(outer.width() <= size.x && outer.height() <= size.y, "{outer:?} in {size:?}");
|
||||
let field = drawn.fields.iter().max_by(|a, b| a.area().total_cmp(&b.area())).unwrap();
|
||||
assert!((MIN_FIELD..=FIELD).contains(&field.width()));
|
||||
assert!((field.width() - field.height()).abs() < 1.0);
|
||||
assert!(drawn.boxes.iter().all(|r| r.left() >= outer.left() - 1.0 && r.right() <= outer.right() + 1.0), "controls fit horizontally");
|
||||
if size.x < 500.0 {
|
||||
assert!(drawn.control(tl!("OK")).top() > field.bottom(), "narrow windows stack the controls below the field");
|
||||
let mut actions_visible = false;
|
||||
let mut last_input_visible = false;
|
||||
for _ in 0..30 {
|
||||
draw(
|
||||
&ctx,
|
||||
&mut app,
|
||||
size,
|
||||
vec![
|
||||
egui::Event::PointerMoved(outer.min + vec2(30.0, 80.0)),
|
||||
egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: vec2(0.0, -20.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
modifiers: Default::default(),
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
},
|
||||
],
|
||||
);
|
||||
let scrolled = settled(&ctx, &mut app, size);
|
||||
actions_visible |= scrolled.visible_texts.iter().any(|s| s == tl!("OK"));
|
||||
last_input_visible |= scrolled.visible_texts.iter().any(|s| s == "K");
|
||||
}
|
||||
assert!(actions_visible && last_input_visible, "vertical scrolling reveals actions and the last input");
|
||||
}
|
||||
// Keyboard confirmation remains available even when the actions require scrolling.
|
||||
draw(&ctx, &mut app, size, vec![key(egui::Key::Enter)]);
|
||||
assert!(app.ui.dialog.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
/// #5941: in a window short enough to scroll the picker, at any width, its scroll bar shows
|
||||
/// inside the window and the content fits beside it: no label is cut off at the side.
|
||||
#[test]
|
||||
fn a_scrolling_picker_shows_its_bar_and_fits_its_content_beside_it() {
|
||||
fn sideways_clipped(shape: &egui::Shape, clip: Rect, out: &mut Vec<String>) {
|
||||
match shape {
|
||||
egui::Shape::Text(t) => {
|
||||
let r = t.visual_bounding_rect();
|
||||
let rows_shown = clip.top() <= r.top() && r.bottom() <= clip.bottom();
|
||||
if rows_shown && !t.galley.text().trim().is_empty() && (r.left() < clip.left() - 1.0 || r.right() > clip.right() + 1.0) {
|
||||
out.push(format!("{:?} {r:?} in {clip:?}", t.galley.text()));
|
||||
}
|
||||
}
|
||||
egui::Shape::Vec(v) => v.iter().for_each(|s| sideways_clipped(s, clip, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for width in (400..=800).step_by(8) {
|
||||
let size = vec2(width as f32, 380.0);
|
||||
let (ctx, mut app) = (context(), app());
|
||||
app.run("ui.colorPicker", json!({"color": "#0000ff"})).unwrap();
|
||||
settled(&ctx, &mut app, size);
|
||||
let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, size)), ..Default::default() };
|
||||
let mut out = ctx.run_ui(input, |ui| super::super::show(&mut app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
let mut clipped = vec![];
|
||||
for s in &out.shapes {
|
||||
sideways_clipped(&s.shape, s.clip_rect, &mut clipped);
|
||||
}
|
||||
assert!(clipped.is_empty(), "{size:?}: {clipped:?}");
|
||||
let outer = ctx.memory(|m| m.area_rect(egui::Id::unique(("dialog", KIND)))).unwrap();
|
||||
assert!(outer.left() >= -0.5 && outer.right() <= size.x + 0.5, "{size:?}: the window {outer:?} stays on screen");
|
||||
// The content's scroll bar: a narrow filled rectangle taller than a row, inside the window.
|
||||
let mut bars = vec![];
|
||||
let mut walk = vec![];
|
||||
out.shapes.iter().for_each(|c| walk.push(c.shape.clone()));
|
||||
while let Some(s) = walk.pop() {
|
||||
match s {
|
||||
egui::Shape::Vec(v) => walk.extend(v),
|
||||
egui::Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() <= 8.0 && r.rect.height() > 40.0 => bars.push(r.rect),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert!(bars.iter().any(|b| outer.contains_rect(*b)), "{size:?}: the content scrolls and its bar shows in {outer:?}: {bars:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #5941: while the body scrolls, the heading sets the dialog's width to the one the body lays its
|
||||
/// field and columns out in, with the scroll bar's column, so the body measures the same layout from
|
||||
/// it and does not leave out the bar's column a second time.
|
||||
#[test]
|
||||
fn the_heading_leaves_the_body_the_width_of_the_layout_it_measured() {
|
||||
let ctx = context();
|
||||
for width in (400..=800).step_by(4) {
|
||||
let size = vec2(width as f32, 380.0);
|
||||
let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, size)), ..Default::default() };
|
||||
let mut out = ctx.run_ui(raw, |ui| {
|
||||
let (side, _, _, stacked, bar) = layout_size(ui);
|
||||
assert!(bar > 0.0, "{size:?}: the body scrolls");
|
||||
header(ui, "Color Picker");
|
||||
let (body_side, _, _, body_stacked, _) = layout_size(ui);
|
||||
assert_eq!((body_side, body_stacked), (side, stacked), "{size:?}: the body lays out the field and columns the heading measured");
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Type all three Lab components through the numeric fields, then apply the picked color.
|
||||
#[test]
|
||||
fn native_lab_entry_in_color_picker() {
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
|
||||
let mut app = app();
|
||||
app.run("ui.colorPicker", json!({"color": {"l": 50, "a": 0, "b": 0}})).unwrap();
|
||||
let mut first = true;
|
||||
let builder = egui_kittest::Harness::builder().with_size(screen());
|
||||
let builder = if std::env::var_os("VECTORCRAFT_RECOLOR_CAPTURE_DIR").is_some() { builder.wgpu() } else { builder };
|
||||
let mut h = builder.build_ui_state(
|
||||
move |ui, app: &mut VectorcraftApp| {
|
||||
if std::mem::replace(&mut first, false) {
|
||||
crate::theme::install_fonts(ui.ctx());
|
||||
return;
|
||||
}
|
||||
super::super::show(app, ui.ctx());
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(4);
|
||||
for (label, text) in [("L", "70"), ("a", "-25"), ("b", "40")] {
|
||||
h.get_by_role_and_label(Role::TextInput, label).focus();
|
||||
h.run_steps(2);
|
||||
h.key_press_modifiers(egui::Modifiers { ctrl: true, command: true, ..Default::default() }, egui::Key::A);
|
||||
h.get_by_role_and_label(Role::TextInput, label).type_text(text);
|
||||
h.key_press(egui::Key::Tab);
|
||||
h.run_steps(2);
|
||||
assert!(matches!(picked(h.state().ui.dialog.as_ref().unwrap()).color, Color::Lab { .. }), "{label} keeps Lab");
|
||||
}
|
||||
let expected = Color::lab(70.0, -25.0, 40.0);
|
||||
assert_eq!(picked(h.state().ui.dialog.as_ref().unwrap()).color, expected);
|
||||
if let Some(dir) = std::env::var_os("VECTORCRAFT_RECOLOR_CAPTURE_DIR") {
|
||||
let dir = std::path::PathBuf::from(dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
h.render().unwrap().save(dir.join("picker-lab.png")).unwrap();
|
||||
}
|
||||
h.get_by_role_and_label(Role::Button, "OK").click();
|
||||
h.run_steps(2);
|
||||
assert!(h.state().ui.dialog.is_none());
|
||||
assert_eq!(crate::panels::current_paints(h.state()).0.color(), Some(expected));
|
||||
}
|
||||
|
||||
@@ -1,95 +1,87 @@
|
||||
//! Sample Color from Screen (`ui.sampleScreenColor`): the system's color sampler picks a color
|
||||
//! anywhere on the screen ([`crate::Services::screen_color`]: `NSColorSampler` on macOS, the XDG
|
||||
//! desktop portal's `PickColor` on Linux, a copy of the screen shown in a window of the app's own on
|
||||
//! Windows, the browser's EyeDropper where the browser has one). The command shows the sampler and
|
||||
//! answers at once. The color arrives in a later frame ([`poll`]) and becomes the fill or the
|
||||
//! stroke through `paint.setFill` / `paint.setStroke` (one undo step), or the open Color Picker's
|
||||
//! color. When the person cancels the sampler (Escape on macOS, Windows and in browsers), the
|
||||
//! colors stay as they were.
|
||||
//! Sample Color from Screen (`ui.sampleScreenColor`): the platform's screen capture
|
||||
//! (`craft::platform::screen`, through the framework's [`ScreenPick`]) picks a color anywhere on the
|
||||
//! screen. The command answers at once; the color arrives in a later frame ([`tick`]) and becomes
|
||||
//! the fill or the stroke through `paint.setFill` / `paint.setStroke` (one undo step), or the open
|
||||
//! Color Picker's color. When the person cancels, the colors stay as they were.
|
||||
//!
|
||||
//! The sampler answers in sRGB (macOS clips a color outside sRGB to it; Windows reads the screen's
|
||||
//! 8-bit colors as sRGB). [`sampled`] converts that
|
||||
//! into the working RGB space, so when the working space is not sRGB, a color inside sRGB looks as
|
||||
//! it did on the screen.
|
||||
//! The capture answers in sRGB. [`sampled`] converts that into the working RGB space, so when the
|
||||
//! working space is not sRGB, a color inside sRGB looks as it did on the screen.
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::mpsc::{Receiver, TryRecvError};
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
use craft::color_ui::ui::{ScreenColorPicker, ScreenPickGesture, ScreenPickerWords};
|
||||
use craft::theme::Srgba;
|
||||
use craft_ui::runtime::env::Env;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Color;
|
||||
use vectorcraft_color::cms::{self, Cms};
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
use crate::menus::opt_bool;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
|
||||
/// What the sampler answers: the picked color's display sRGB components (0 to 1), `None` when the
|
||||
/// person canceled it, or an error.
|
||||
pub type Answer = Result<Option<[f32; 3]>, String>;
|
||||
/// The owner of a pick for the fill.
|
||||
const FILL: &str = "fill";
|
||||
/// The owner of a pick for the stroke.
|
||||
const STROKE: &str = "stroke";
|
||||
|
||||
/// Shows the system's color sampler. The answer arrives on the receiver when the person picks a
|
||||
/// color or cancels, and the host then asks the UI for a frame. An error when the sampler can't be
|
||||
/// shown.
|
||||
pub type StartSampler = Box<dyn FnMut() -> Result<Receiver<Answer>, String>>;
|
||||
|
||||
/// Where the sampled color goes.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Target {
|
||||
Fill,
|
||||
Stroke,
|
||||
/// The Color Picker that was open, known by its [`PICKER_ID`].
|
||||
Picker(u64),
|
||||
/// The window a pick belongs to: a pick whose window changed is cancelled.
|
||||
pub(crate) fn target(ctx: &egui::Context) -> u64 {
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
ctx.viewport_id().hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// The Color Picker's hidden field that holds a number unique to each Color Picker opened
|
||||
/// ([`picker_id`]). The sampled color goes only to the Color Picker the sampler was shown for.
|
||||
pub(crate) const PICKER_ID: &str = "__pickerId";
|
||||
|
||||
/// A new number for a Color Picker's [`PICKER_ID`].
|
||||
pub(crate) fn picker_id() -> u64 {
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
NEXT.fetch_add(1, Ordering::Relaxed)
|
||||
/// Where the document active when the pick started is kept until its color arrives.
|
||||
fn doc_key() -> egui::Id {
|
||||
egui::Id::new("screen-color-doc")
|
||||
}
|
||||
|
||||
/// A sampler that is shown and has not answered yet.
|
||||
pub struct Waiting {
|
||||
answer: Receiver<Answer>,
|
||||
target: Target,
|
||||
/// The document active when it was shown ([`vectorcraft_engine::DocState::uid`]).
|
||||
doc: Option<u64>,
|
||||
fn remember_doc(app: &VectorcraftApp, ctx: &egui::Context) {
|
||||
let uid = app.session.active().map(|d| d.uid);
|
||||
ctx.data_mut(|d| d.insert_temp(doc_key(), uid));
|
||||
}
|
||||
|
||||
/// The host can show a color sampler.
|
||||
/// The platform can capture the screen: the shell's capabilities say so and no capture has said it
|
||||
/// cannot. Without a window there is nothing to capture.
|
||||
pub fn available(app: &VectorcraftApp) -> bool {
|
||||
app.services.screen_color.is_some()
|
||||
let Some(ctx) = app.ui_ctx.as_ref() else { return false };
|
||||
app.screen_pick.available(Env::of_root(ctx).view().shell().caps)
|
||||
}
|
||||
|
||||
/// The open Color Picker dialog, as [`Target::Picker`] names it.
|
||||
fn open_picker(app: &VectorcraftApp) -> Option<Target> {
|
||||
let d = app.ui.dialog.as_ref().filter(|d| crate::dialogs::DialogKind::of(&d.kind) == Some(crate::dialogs::DialogKind::ColorPicker))?;
|
||||
d.fields.get(PICKER_ID).and_then(Value::as_u64).map(Target::Picker)
|
||||
}
|
||||
|
||||
/// `ui.sampleScreenColor {stroke?, picker?}`: show the sampler for the fill, the stroke (default:
|
||||
/// the proxy in front) or, with `picker`, the open Color Picker.
|
||||
/// `ui.sampleScreenColor {stroke?, picker?}`: start a pick for the fill, the stroke (default: the
|
||||
/// proxy in front) or, with `picker`, the open Color Picker.
|
||||
pub fn start(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
let stroke = opt_bool(p, "stroke")?.unwrap_or(!app.session.fill_active);
|
||||
let target = if opt_bool(p, "picker")?.unwrap_or(false) {
|
||||
open_picker(app).ok_or("the Color Picker is not open")?
|
||||
} else if stroke {
|
||||
Target::Stroke
|
||||
let picker = if opt_bool(p, "picker")?.unwrap_or(false) {
|
||||
Some(crate::dialogs::color_picker::open_picker(app).ok_or("the Color Picker is not open")?)
|
||||
} else {
|
||||
Target::Fill
|
||||
None
|
||||
};
|
||||
if app.screen_sampler.is_some() {
|
||||
if app.screen_pick.busy() {
|
||||
return Err("the screen color sampler is already open".into());
|
||||
}
|
||||
let show = app.services.screen_color.as_mut().ok_or("this system has no screen color sampler")?;
|
||||
let answer = show()?;
|
||||
let doc = app.session.active().map(|d| d.uid);
|
||||
app.screen_sampler = Some(Waiting { answer, target, doc });
|
||||
if !available(app) {
|
||||
return Err("this system has no screen color sampler".into());
|
||||
}
|
||||
if let Some(ctx) = app.ui_ctx.clone() {
|
||||
remember_doc(app, &ctx);
|
||||
}
|
||||
match picker {
|
||||
Some(id) => app.screen_pick.start(crate::dialogs::color_picker::owner(id)),
|
||||
None => app.screen_pick.start(if stroke { STROKE } else { FILL }),
|
||||
}
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// Follows a picker's pipette press for `owner`; the colour of a held drag or of a release inside
|
||||
/// the app comes back at once.
|
||||
pub(crate) fn hold(app: &mut VectorcraftApp, ctx: &egui::Context, owner: impl Hash, gesture: ScreenPickGesture) -> Option<Srgba> {
|
||||
if !app.screen_pick.busy() {
|
||||
remember_doc(app, ctx);
|
||||
}
|
||||
app.screen_pick.hold(ctx, owner, gesture)
|
||||
}
|
||||
|
||||
/// The color a display sRGB value stands for in `cms`'s working RGB space: it shows as that sRGB
|
||||
/// value. Components outside 0 to 1 are clamped, and a component that is not a number reads as 0.
|
||||
pub fn sampled(cms: &Cms, srgb: [f32; 3]) -> Color {
|
||||
@@ -97,63 +89,44 @@ pub fn sampled(cms: &Cms, srgb: [f32; 3]) -> Color {
|
||||
Color::rgb(r, g, b)
|
||||
}
|
||||
|
||||
/// The sRGB components of a sampler's hex answer (`#rrggbb` as the browser's EyeDropper gives
|
||||
/// `sRGBHex`; the Color panel's hex rules apply), or `None` when it is not hex.
|
||||
pub fn srgb_from_hex(hex: &str) -> Option<[f32; 3]> {
|
||||
match crate::panels::color::parse_hex(hex)? {
|
||||
Color::Rgb { r, g, b } => Some([r, g, b]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Each frame: take the sampler's answer when it has arrived.
|
||||
pub(crate) fn poll(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let Some(w) = &app.screen_sampler else { return };
|
||||
let answer = match w.answer.try_recv() {
|
||||
Ok(answer) => answer,
|
||||
Err(TryRecvError::Empty) => {
|
||||
// The host wakes the window when the sampler answers; this is in case it can't.
|
||||
ctx.request_repaint_after(std::time::Duration::from_secs(1));
|
||||
return;
|
||||
}
|
||||
// The sampler is gone without an answer: as canceled.
|
||||
Err(TryRecvError::Disconnected) => Ok(None),
|
||||
};
|
||||
let Some(Waiting { target, doc, .. }) = app.screen_sampler.take() else { return };
|
||||
let srgb = match answer {
|
||||
Ok(Some(srgb)) => srgb,
|
||||
Ok(None) => return,
|
||||
Err(e) => return app.status(e),
|
||||
};
|
||||
/// The color `owner` picked, once. One that arrives after another document became active is
|
||||
/// dropped, and the status line says why.
|
||||
pub(crate) fn take(app: &mut VectorcraftApp, ctx: &egui::Context, owner: impl Hash) -> Option<Srgba> {
|
||||
let color = app.screen_pick.take(owner)?;
|
||||
let doc = ctx.data(|d| d.get_temp::<Option<u64>>(doc_key())).flatten();
|
||||
if app.session.active().map(|d| d.uid) != doc {
|
||||
return app.status(tl!("The active document changed while the screen color sampler was open"));
|
||||
}
|
||||
let color = crate::panels::color_json(&sampled(&cms::active(), srgb));
|
||||
let cmd = match target {
|
||||
Target::Fill => "paint.setFill",
|
||||
Target::Stroke => "paint.setStroke",
|
||||
// The Color Picker previews it on the selection, as any pick. The color is dropped when the
|
||||
// Color Picker the sampler was shown for is no longer open (it was closed meanwhile, or
|
||||
// another Color Picker replaced it).
|
||||
picker @ Target::Picker(_) => {
|
||||
if open_picker(app) == Some(picker)
|
||||
&& let Some(d) = app.ui.dialog.as_mut()
|
||||
{
|
||||
d.fields.insert("color".into(), color);
|
||||
}
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Err(e) = app.run(cmd, json!({ "color": color })) {
|
||||
app.status(e);
|
||||
app.status(tl!("The active document changed while the screen color sampler was open"));
|
||||
return None;
|
||||
}
|
||||
Some(color)
|
||||
}
|
||||
|
||||
/// The eyedropper button that starts the sampler (gray without one). Returns true when clicked.
|
||||
pub(crate) fn button(app: &VectorcraftApp, ui: &mut egui::Ui) -> bool {
|
||||
let on = available(app);
|
||||
let tip = if on { tl!("Sample Color from Screen") } else { tl!("This system has no screen color sampler") };
|
||||
widgets::icon_button_enabled(ui, "pipette", tip, app.screen_sampler.is_some(), on, 24.0).clicked()
|
||||
/// Each pass after the UI: runs the pick and settles what finished.
|
||||
pub(crate) fn tick(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
app.screen_pick.tick(ctx, target(ctx));
|
||||
settle(app, ctx);
|
||||
}
|
||||
|
||||
/// The capture windows of a running pick; the last thing the app's UI shows in a pass.
|
||||
pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
|
||||
ScreenColorPicker::new(&mut app.screen_pick, "VectorCraft").show(ui);
|
||||
}
|
||||
|
||||
/// Applies the fill's and the stroke's color, and reports a failed capture. A Color Picker takes
|
||||
/// its own in its pass ([`crate::dialogs::color_picker::pump`]).
|
||||
fn settle(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
for (owner, cmd) in [(FILL, "paint.setFill"), (STROKE, "paint.setStroke")] {
|
||||
if let Some(c) = take(app, ctx, owner) {
|
||||
let color = crate::panels::color_json(&sampled(&cms::active(), [c.r, c.g, c.b]));
|
||||
if let Err(e) = app.run(cmd, json!({ "color": color })) {
|
||||
app.status(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(message) = app.screen_pick.take_status(&ScreenPickerWords::default()) {
|
||||
// PLAN: assumed `Label: Display`.
|
||||
app.status(message.text.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -1,35 +1,32 @@
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::mpsc::{Sender, channel};
|
||||
|
||||
use craft::color_ui::ui::StillCapture;
|
||||
use craft::platform::screen::ScreenError;
|
||||
use vectorcraft_color::cms::{ColorSettings, DISPLAY_P3};
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The senders of the samplers a stand-in host showed, newest last.
|
||||
type Shown = Rc<RefCell<Vec<Sender<Answer>>>>;
|
||||
|
||||
/// An app with a document and a selected rectangle, whose host has a stand-in sampler.
|
||||
fn app() -> (VectorcraftApp, Shown) {
|
||||
/// An app with a document and a selected rectangle, and the window the pick runs in.
|
||||
fn app() -> (VectorcraftApp, egui::Context) {
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.ui_ctx = Some(ctx.clone());
|
||||
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
|
||||
let shown = Shown::default();
|
||||
let host = shown.clone();
|
||||
app.services.screen_color = Some(Box::new(move || {
|
||||
let (tx, rx) = channel();
|
||||
host.borrow_mut().push(tx);
|
||||
Ok(rx)
|
||||
}));
|
||||
(app, shown)
|
||||
(app, ctx)
|
||||
}
|
||||
|
||||
/// The person picks `hex` (or cancels, `None`) in the last sampler shown; the next frame takes it.
|
||||
fn pick(app: &mut VectorcraftApp, shown: &Shown, hex: Option<&str>) {
|
||||
let srgb = hex.map(|h| Color::from_hex(h).unwrap().to_rgb());
|
||||
shown.borrow().last().unwrap().send(Ok(srgb)).unwrap();
|
||||
poll(app, &egui::Context::default());
|
||||
/// The capture ends in `result`, and the pass takes it.
|
||||
fn finish(app: &mut VectorcraftApp, ctx: &egui::Context, result: Result<Srgba, ScreenError>) {
|
||||
for _ in 0..2 {
|
||||
let result = result.clone();
|
||||
app.screen_pick.tick_with(ctx, target(ctx), &move || Box::new(StillCapture::new(result.clone().map(|c| craft::platform::screen::Capture::Color([c.r, c.g, c.b])))));
|
||||
}
|
||||
settle(app, ctx);
|
||||
}
|
||||
|
||||
fn srgba(hex: &str) -> Srgba {
|
||||
Srgba::from_hex(hex).unwrap()
|
||||
}
|
||||
|
||||
fn paints(app: &VectorcraftApp) -> (String, String) {
|
||||
@@ -41,197 +38,80 @@ fn undo_len(app: &VectorcraftApp) -> usize {
|
||||
app.session.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// The color picked on the screen becomes the fill, as one undo step.
|
||||
/// The color picked on the screen becomes the fill, or with `stroke` the stroke, as one undo step.
|
||||
#[test]
|
||||
fn a_sampled_color_fills_the_selection() {
|
||||
let (mut app, shown) = app();
|
||||
let (mut app, ctx) = app();
|
||||
let (_, stroke) = paints(&app);
|
||||
let before = undo_len(&app);
|
||||
assert_eq!(app.run("ui.sampleScreenColor", json!({})).unwrap(), Value::Null, "answers at once");
|
||||
assert_eq!(undo_len(&app), before, "nothing changes until the person picks");
|
||||
pick(&mut app, &shown, Some("#123456"));
|
||||
finish(&mut app, &ctx, Ok(srgba("#123456")));
|
||||
assert_eq!(paints(&app), ("#123456".into(), stroke));
|
||||
assert_eq!(undo_len(&app), before + 1, "one step");
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert_ne!(paints(&app).0, "#123456");
|
||||
}
|
||||
|
||||
/// `stroke: true`, or the stroke proxy in front, sets the stroke instead.
|
||||
#[test]
|
||||
fn stroke_takes_the_stroke() {
|
||||
let (mut app, shown) = app();
|
||||
let (fill, _) = paints(&app);
|
||||
app.run("ui.sampleScreenColor", json!({"stroke": true})).unwrap();
|
||||
pick(&mut app, &shown, Some("#336699"));
|
||||
assert_eq!(paints(&app), (fill.clone(), "#336699".into()));
|
||||
app.session.fill_active = false;
|
||||
app.run("ui.sampleScreenColor", json!({})).unwrap();
|
||||
pick(&mut app, &shown, Some("#996633"));
|
||||
assert_eq!(paints(&app), (fill, "#996633".into()));
|
||||
app.run("ui.sampleScreenColor", json!({"stroke": false})).unwrap();
|
||||
pick(&mut app, &shown, Some("#669933"));
|
||||
assert_eq!(paints(&app).0, "#669933");
|
||||
finish(&mut app, &ctx, Ok(srgba("#336699")));
|
||||
assert_eq!(paints(&app), (fill, "#336699".into()));
|
||||
}
|
||||
|
||||
/// With `picker`, the color goes to the open Color Picker, which shows it on the selection as any
|
||||
/// pick; Cancel puts the art back.
|
||||
/// With `picker`, the color goes to the open Color Picker only, which shows it on the selection.
|
||||
#[test]
|
||||
fn the_color_picker_takes_the_sampled_color() {
|
||||
let (mut app, shown) = app();
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let frame = |app: &mut VectorcraftApp| {
|
||||
let mut out = ctx.run_ui(Default::default(), |ui| crate::dialogs::show(app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
};
|
||||
let (mut app, ctx) = app();
|
||||
let before = paints(&app);
|
||||
assert!(app.run("ui.sampleScreenColor", json!({"picker": true})).is_err(), "no Color Picker open");
|
||||
assert!(app.screen_sampler.is_none());
|
||||
assert!(!app.screen_pick.busy());
|
||||
app.run("ui.colorPicker", json!({})).unwrap();
|
||||
frame(&mut app);
|
||||
app.run("ui.sampleScreenColor", json!({"picker": true})).unwrap();
|
||||
pick(&mut app, &shown, Some("#123456"));
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!(d.fields.get("color").and_then(vectorcraft_engine::cmd::color_value).map(|c| c.to_hex()).as_deref(), Some("#123456"));
|
||||
frame(&mut app);
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().str("hex"), "123456");
|
||||
finish(&mut app, &ctx, Ok(srgba("#123456")));
|
||||
assert_eq!(paints(&app), before, "the fill takes nothing");
|
||||
let mut out = ctx.run_ui(Default::default(), |ui| crate::dialogs::color_picker::pump(&mut app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
assert_eq!(paints(&app).0, "#123456", "previewed on the selection");
|
||||
crate::dialogs::cancel(&mut app);
|
||||
assert_eq!(paints(&app), before);
|
||||
// A Color Picker closed before the answer arrives takes nothing, and the art stays as it is.
|
||||
app.run("ui.colorPicker", json!({})).unwrap();
|
||||
app.run("ui.sampleScreenColor", json!({"picker": true})).unwrap();
|
||||
crate::dialogs::cancel(&mut app);
|
||||
pick(&mut app, &shown, Some("#654321"));
|
||||
assert_eq!(paints(&app), before);
|
||||
assert!(app.ui.dialog.is_none());
|
||||
// Nor does a new Color Picker for the same proxy and color that replaced it.
|
||||
app.run("ui.colorPicker", json!({})).unwrap();
|
||||
app.run("ui.sampleScreenColor", json!({"picker": true})).unwrap();
|
||||
crate::dialogs::cancel(&mut app);
|
||||
app.run("ui.colorPicker", json!({})).unwrap();
|
||||
pick(&mut app, &shown, Some("#654321"));
|
||||
frame(&mut app);
|
||||
assert_eq!(paints(&app), before);
|
||||
assert_ne!(app.ui.dialog.as_ref().unwrap().str("hex"), "654321");
|
||||
crate::dialogs::cancel(&mut app);
|
||||
// Nor does a Color Picker for the other proxy that replaced it.
|
||||
app.run("ui.colorPicker", json!({})).unwrap();
|
||||
app.run("ui.sampleScreenColor", json!({"picker": true})).unwrap();
|
||||
crate::dialogs::cancel(&mut app);
|
||||
app.run("ui.colorPicker", json!({"stroke": true})).unwrap();
|
||||
pick(&mut app, &shown, Some("#654321"));
|
||||
frame(&mut app);
|
||||
assert_eq!(paints(&app), before);
|
||||
assert_ne!(app.ui.dialog.as_ref().unwrap().str("hex"), "654321");
|
||||
crate::dialogs::cancel(&mut app);
|
||||
// Nor one in another document: the status bar says why.
|
||||
app.run("ui.colorPicker", json!({})).unwrap();
|
||||
app.run("ui.sampleScreenColor", json!({"picker": true})).unwrap();
|
||||
crate::dialogs::cancel(&mut app);
|
||||
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
app.run("ui.colorPicker", json!({})).unwrap();
|
||||
pick(&mut app, &shown, Some("#654321"));
|
||||
assert_ne!(app.ui.dialog.as_ref().unwrap().fields.get("color"), Some(&crate::panels::color_json(&Color::from_hex("#654321").unwrap())));
|
||||
assert_eq!(app.ui.status, "The active document changed while the screen color sampler was open");
|
||||
}
|
||||
|
||||
/// The Color Picker's eyedropper button shows the sampler for the Color Picker, and the color
|
||||
/// the frame takes goes there.
|
||||
/// The pipette's press runs the pick for the picker, and the color it answers previews in it.
|
||||
#[test]
|
||||
fn the_color_pickers_eyedropper_samples_into_it() {
|
||||
let (mut app, shown) = app();
|
||||
let (mut app, ctx) = app();
|
||||
app.run("ui.colorPicker", json!({})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 900.0));
|
||||
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| {
|
||||
app.logic(ui.ctx());
|
||||
crate::dialogs::show(app, ui.ctx());
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
};
|
||||
// The dialog's one square clickable widget of the button's size, once the window has settled.
|
||||
let buttons = || -> Vec<egui::Rect> {
|
||||
ctx.viewport(|v| {
|
||||
let widgets = v.this_pass.widgets.layers().flat_map(|(_, w)| w.iter());
|
||||
widgets.filter(|w| w.sense.senses_click() && w.rect.size() == egui::Vec2::splat(24.0)).map(|w| w.rect).collect()
|
||||
})
|
||||
};
|
||||
let mut last = vec![];
|
||||
for _ in 0..10 {
|
||||
frame(&mut app, vec![]);
|
||||
if !last.is_empty() && buttons() == last {
|
||||
break;
|
||||
}
|
||||
last = buttons();
|
||||
}
|
||||
let [button] = last[..] else { panic!("{last:?}") };
|
||||
let pos = button.center();
|
||||
let press = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
frame(&mut app, vec![egui::Event::PointerMoved(pos), press(true), press(false)]);
|
||||
assert_eq!(shown.borrow().len(), 1, "the sampler is shown");
|
||||
assert!(matches!(app.screen_sampler.as_ref().map(|w| &w.target), Some(Target::Picker(_))));
|
||||
assert_eq!(app.screen_sampler.as_ref().map(|w| &w.target), open_picker(&app).as_ref());
|
||||
shown.borrow().last().unwrap().send(Ok(Some([0x12, 0x34, 0x56].map(|v| v as f32 / 255.0)))).unwrap();
|
||||
frame(&mut app, vec![]);
|
||||
assert!(app.screen_sampler.is_none());
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().str("hex"), "123456");
|
||||
let id = app.color_dialogs.pickers.last().unwrap().id;
|
||||
let owner = crate::dialogs::color_picker::owner(id);
|
||||
assert_eq!(hold(&mut app, &ctx, owner, ScreenPickGesture::Clicked), None);
|
||||
assert!(app.screen_pick.busy());
|
||||
finish(&mut app, &ctx, Ok(srgba("#123456")));
|
||||
let mut out = ctx.run_ui(Default::default(), |ui| crate::dialogs::color_picker::pump(&mut app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
assert_eq!(paints(&app).0, "#123456");
|
||||
}
|
||||
|
||||
/// `ui.inspect` reports `screenSampler` while the sampler waits; one at a time.
|
||||
#[test]
|
||||
fn inspect_reports_the_open_sampler() {
|
||||
let (mut app, shown) = app();
|
||||
let ctx = egui::Context::default();
|
||||
let open = |app: &VectorcraftApp| crate::control::inspect(app, &ctx)["screenSampler"].clone();
|
||||
assert_eq!(open(&app), json!(false));
|
||||
app.run("ui.sampleScreenColor", json!({})).unwrap();
|
||||
assert_eq!(open(&app), json!(true));
|
||||
poll(&mut app, &ctx);
|
||||
assert_eq!(open(&app), json!(true), "still waiting");
|
||||
let e = app.run("ui.sampleScreenColor", json!({})).unwrap_err();
|
||||
assert!(e.contains("already open"), "{e}");
|
||||
assert_eq!(shown.borrow().len(), 1);
|
||||
pick(&mut app, &shown, None);
|
||||
assert_eq!(open(&app), json!(false));
|
||||
}
|
||||
|
||||
/// Escape (no color) changes nothing; an error from the host reaches the status bar; a sampler
|
||||
/// that is gone without answering counts as canceled.
|
||||
/// A canceled capture changes nothing; a failed one reaches the status line.
|
||||
#[test]
|
||||
fn cancel_and_errors_leave_the_art_alone() {
|
||||
let (mut app, shown) = app();
|
||||
let (mut app, ctx) = app();
|
||||
let before = (paints(&app), undo_len(&app));
|
||||
app.run("ui.sampleScreenColor", json!({})).unwrap();
|
||||
pick(&mut app, &shown, None);
|
||||
finish(&mut app, &ctx, Err(ScreenError::Cancelled));
|
||||
assert_eq!((paints(&app), undo_len(&app)), before);
|
||||
assert!(!app.screen_pick.busy());
|
||||
app.run("ui.sampleScreenColor", json!({})).unwrap();
|
||||
shown.borrow().last().unwrap().send(Err("the sampler failed".into())).unwrap();
|
||||
poll(&mut app, &egui::Context::default());
|
||||
assert_eq!(app.ui.status, "the sampler failed");
|
||||
app.run("ui.sampleScreenColor", json!({})).unwrap();
|
||||
shown.borrow_mut().clear();
|
||||
poll(&mut app, &egui::Context::default());
|
||||
assert!(app.screen_sampler.is_none());
|
||||
finish(&mut app, &ctx, Err(ScreenError::Failed("the sampler failed".into())));
|
||||
assert!(app.ui.status.contains("the sampler failed"), "{}", app.ui.status);
|
||||
assert_eq!((paints(&app), undo_len(&app)), before);
|
||||
// A sampler that can't be shown answers with its error and waits for nothing.
|
||||
app.services.screen_color = Some(Box::new(|| Err("no screen".into())));
|
||||
assert_eq!(app.run("ui.sampleScreenColor", json!({})).unwrap_err(), "no screen");
|
||||
assert!(app.screen_sampler.is_none());
|
||||
}
|
||||
|
||||
/// A color that arrives after another document became active paints nothing.
|
||||
#[test]
|
||||
fn a_new_active_document_takes_no_color() {
|
||||
let (mut app, shown) = app();
|
||||
let (mut app, ctx) = app();
|
||||
app.run("ui.sampleScreenColor", json!({})).unwrap();
|
||||
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
|
||||
let before = paints(&app);
|
||||
pick(&mut app, &shown, Some("#123456"));
|
||||
finish(&mut app, &ctx, Ok(srgba("#123456")));
|
||||
assert_eq!(paints(&app), before);
|
||||
assert_eq!(app.ui.status, "The active document changed while the screen color sampler was open");
|
||||
}
|
||||
@@ -254,50 +134,19 @@ fn a_wide_working_space_shows_the_sampled_color() {
|
||||
assert_eq!(sampled(&srgb_cms, [f32::NAN, 2.0, -1.0]), Color::rgb(0.0, 1.0, 0.0));
|
||||
}
|
||||
|
||||
/// The browser's EyeDropper answers `sRGBHex`; anything else isn't a color.
|
||||
#[test]
|
||||
fn hex_answers_read_as_srgb() {
|
||||
assert_eq!(srgb_from_hex("#123456"), Some([0x12, 0x34, 0x56].map(|v| v as f32 / 255.0)));
|
||||
assert_eq!(srgb_from_hex("#FFFFFF"), Some([1.0; 3]));
|
||||
for junk in ["", "#", "#12345", "#1234567", "#12345g", "+12345", "rgb(1, 2, 3)", "red"] {
|
||||
assert_eq!(srgb_from_hex(junk), None, "{junk}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Without a sampler (the BSDs, a browser without an EyeDropper) the command answers an
|
||||
/// error and is disabled, and the Color Picker draws its button gray.
|
||||
#[test]
|
||||
fn without_a_sampler_the_command_is_unavailable() {
|
||||
let (mut app, _) = app();
|
||||
assert!(crate::menus::enabled(&app, "ui.sampleScreenColor"));
|
||||
app.services.screen_color = None;
|
||||
assert!(!crate::menus::enabled(&app, "ui.sampleScreenColor"));
|
||||
assert_eq!(app.run("ui.sampleScreenColor", json!({})).unwrap_err(), "this system has no screen color sampler");
|
||||
assert!(app.screen_sampler.is_none());
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
let mut clicked = true;
|
||||
let mut out = ctx.run_ui(Default::default(), |ui| clicked = button(&app, ui));
|
||||
out.textures_delta.clear();
|
||||
assert!(!clicked);
|
||||
// Keyboard Shortcuts lists the command, so it can be given a key.
|
||||
assert!(crate::shortcut_editor::entries().iter().any(|e| e.key == "ui.sampleScreenColor"));
|
||||
}
|
||||
|
||||
/// The command answers every junk parameter without a panic.
|
||||
#[test]
|
||||
fn junk_params_never_panic() {
|
||||
let (mut app, shown) = app();
|
||||
let (mut app, ctx) = app();
|
||||
let doc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == "ui.sampleScreenColor").unwrap().3;
|
||||
let mut params = vectorcraft_testkit::strategies::junk_params(doc, "/nonexistent");
|
||||
params.extend(vectorcraft_testkit::strategies::junk_values());
|
||||
assert!(params.len() > 40);
|
||||
for p in params {
|
||||
let _ = app.run("ui.sampleScreenColor", p);
|
||||
if !shown.borrow().is_empty() {
|
||||
pick(&mut app, &shown, Some("#808080"));
|
||||
shown.borrow_mut().clear();
|
||||
if app.screen_pick.busy() {
|
||||
finish(&mut app, &ctx, Ok(srgba("#808080")));
|
||||
}
|
||||
}
|
||||
assert!(app.screen_sampler.is_none());
|
||||
assert!(!app.screen_pick.busy());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user