diff --git a/apps/vectorcraft/src/linux_screen_color.rs b/apps/vectorcraft/src/linux_screen_color.rs deleted file mode 100644 index cfb8d7d69f..0000000000 --- a/apps/vectorcraft/src/linux_screen_color.rs +++ /dev/null @@ -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) - }) -} diff --git a/apps/vectorcraft/src/linux_screen_color/portal.rs b/apps/vectorcraft/src/linux_screen_color/portal.rs deleted file mode 100644 index 21bcb34da5..0000000000 --- a/apps/vectorcraft/src/linux_screen_color/portal.rs +++ /dev/null @@ -1,291 +0,0 @@ -//! The XDG desktop portal's `Screenshot.PickColor` -//! (): -//! 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>) -> Result { - 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, 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) = 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) -> Result, 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 { - HashMap::from([("color".into(), OwnedValue::try_from(Value::from(rgb)).unwrap())]) - } - - fn failed(r: Result) -> 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::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) = 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::>(), ["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(); - } -} diff --git a/apps/vectorcraft/src/mac_screen_color.rs b/apps/vectorcraft/src/mac_screen_color.rs deleted file mode 100644 index 65e1f3cfde..0000000000 --- a/apps/vectorcraft/src/mac_screen_color.rs +++ /dev/null @@ -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" -//! (). 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}"); - } -} diff --git a/apps/vectorcraft/src/windows_screen_color.rs b/apps/vectorcraft/src/windows_screen_color.rs deleted file mode 100644 index 56ea45eb7d..0000000000 --- a/apps/vectorcraft/src/windows_screen_color.rs +++ /dev/null @@ -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 (), -//! into a bitmap with `BitBlt` from the screen's device context -//! (), 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 -//! (). 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 -//! (). -//! -//! 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 { - 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`, -/// ), 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`, -/// ) 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