shell-w13: net change of 2 commits

- shell-w13: written from its sheet
- shell-w13: repair 1
This commit is contained in:
bflatastic
2026-11-21 23:22:47 +07:00
parent d2b499cfe2
commit 40b354dbb6
5 changed files with 344 additions and 947 deletions
+30 -21
View File
@@ -6,7 +6,7 @@
//! canvas reads it), so holding it still opens the context menu (egui's long touch). It hovers
//! where the pen can (Apple Pencil hover).
//! - A press of the pen's eraser end (the eraser button, `button` 5 in Pointer Events) presses
//! like the tip, and the pen's samples go into a [`StylusFeed`] with that end, so the canvas
//! like the tip, and the pen's samples go into a [`PenSource`] with that end, so the canvas
//! selects the Eraser tool for the press. A press of the tip turns the pen back.
//! - Fingers are touch contacts: two pinch and pan the canvas, and tap to undo or redo. The first
//! finger also drives the pointer, so it taps the panels and menus; on the canvas it navigates
@@ -23,7 +23,8 @@ use std::cell::RefCell;
use std::rc::Rc;
use egui::{Event, PointerButton, Pos2, TouchDeviceId, TouchId, TouchPhase};
use vectorcraft_ui_egui::stylus::{PenPose, PenSample, StylusFeed};
use craft::behavior::PointerSample;
use craft::ui::runtime::pen::PenSource;
use vectorcraft_ui_egui::touch::{self, Source};
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::JsCast as _;
@@ -48,13 +49,14 @@ pub struct Pointers {
button: Option<PointerButton>,
/// The pen last pressed with its eraser end.
eraser: bool,
/// The pen's pressure and end for the canvas (`Services::stylus`).
stylus: StylusFeed,
/// The pen's pressure and end for the canvas, the source the install reads.
// PLAN: named `source`, not `pen`: `pen` is the pressing pen's pointer id above.
source: PenSource,
}
impl Default for Pointers {
fn default() -> Self {
Self { events: vec![], pen: None, fingers: vec![], primary: None, button: None, eraser: false, stylus: StylusFeed::on_ui_thread() }
Self { events: vec![], pen: None, fingers: vec![], primary: None, button: None, eraser: false, source: PenSource::default() }
}
}
@@ -88,14 +90,16 @@ impl Pointers {
std::mem::take(&mut self.events)
}
/// The feed the pen's samples go into, for `Services::stylus`.
pub fn stylus(&self) -> StylusFeed {
self.stylus.clone()
/// The source the pen's samples go into, for the runtime install.
pub fn pen(&self) -> PenSource {
self.source.clone()
}
/// A pen moved or pressed with `pressure`, with the end it last pressed with.
fn pen_sample(&self, pressure: f32) {
self.stylus.set_sample(Some(PenSample { pressure, eraser: self.eraser, pose: PenPose::default() }));
let mut sample = PointerSample::new(pressure);
sample.eraser = self.eraser;
self.source.set(Some(sample));
}
fn touch(&mut self, device: TouchDeviceId, id: i32, phase: TouchPhase, pos: Pos2, force: Option<f32>) {
@@ -140,7 +144,7 @@ impl Pointers {
if e.pointer_type != "pen" && self.pen.is_none() && matches!(kind, "pointerdown" | "pointermove") {
// Another pointer moved while no pen presses (a palm under a pen pressing is
// rejected): the canvas takes no pen pressure or pen end for it.
self.stylus.set(None);
self.source.set(None);
}
match e.pointer_type {
"pen" => {
@@ -440,7 +444,12 @@ mod tests {
assert!(!p.feed("pointerdown", &input("pen", 6), Pos2::ZERO, &[], true));
assert!(p.take().is_empty());
assert!(!touch::pen_seen());
assert_eq!(p.stylus().eraser(), None);
assert_eq!(p.pen().current(), None);
}
/// The end of the pen the source holds, `None` without a pen.
fn end(pen: &PenSource) -> Option<bool> {
pen.current().map(|s| s.eraser)
}
fn presses(p: &mut Pointers) -> Vec<(PointerButton, bool)> {
@@ -459,27 +468,27 @@ mod tests {
fn the_eraser_button_presses_with_the_eraser_end() {
reset();
let mut p = Pointers::default();
let feed = p.stylus();
let feed = p.pen();
let pos = Pos2::new(30.0, 40.0);
let eraser = input("pen", ERASER_BUTTON);
assert!(p.feed("pointerdown", &eraser, pos, &[], true));
assert_eq!(presses(&mut p), [(PointerButton::Primary, true)]);
assert!(touch::pen_seen());
assert_eq!((feed.eraser(), feed.held()), (Some(true), Some(0.6)));
assert_eq!((end(&feed), feed.current().map(|s| s.pressure)), (Some(true), Some(0.6)));
assert!(p.feed("pointermove", &input("pen", -1), pos, &[], true));
assert_eq!(feed.eraser(), Some(true));
assert_eq!(end(&feed), Some(true));
assert!(p.feed("pointerup", &eraser, pos, &[], true));
assert_eq!(presses(&mut p), [(PointerButton::Primary, false)]);
let mut hover = input("pen", -1);
hover.pressure = 0.0;
assert!(p.feed("pointermove", &hover, pos, &[], true));
assert_eq!(feed.eraser(), Some(true), "a hovering pen keeps the end it pressed with");
assert_eq!(end(&feed), Some(true), "a hovering pen keeps the end it pressed with");
// The barrel button leaves the end as it was.
assert!(p.feed("pointerdown", &input("pen", 2), pos, &[], true));
assert!(p.feed("pointerup", &input("pen", 2), pos, &[], true));
assert_eq!(feed.eraser(), Some(true));
assert_eq!(end(&feed), Some(true));
assert!(p.feed("pointerdown", &input("pen", 0), pos, &[], true));
assert_eq!(feed.eraser(), Some(false), "the tip");
assert_eq!(end(&feed), Some(false), "the tip");
reset();
}
@@ -490,13 +499,13 @@ mod tests {
for (pointer_type, kind) in [("mouse", "pointermove"), ("mouse", "pointerdown"), ("touch", "pointerdown"), ("touch", "pointermove")] {
reset();
let mut p = Pointers::default();
let feed = p.stylus();
let feed = p.pen();
assert!(p.feed("pointerdown", &input("pen", ERASER_BUTTON), Pos2::ZERO, &[], true));
assert!(p.feed("pointerup", &input("pen", ERASER_BUTTON), Pos2::ZERO, &[], true));
let mut other = input(pointer_type, 0);
other.id = 10;
p.feed(kind, &other, Pos2::ZERO, &[], true);
assert_eq!((feed.eraser(), feed.held()), (None, None), "{pointer_type} {kind}");
assert_eq!(feed.current(), None, "{pointer_type} {kind}");
}
reset();
}
@@ -507,14 +516,14 @@ mod tests {
fn a_rejected_palm_keeps_the_pen_end() {
reset();
let mut p = Pointers::default();
let feed = p.stylus();
let feed = p.pen();
assert!(p.feed("pointerdown", &input("pen", ERASER_BUTTON), Pos2::ZERO, &[], true));
let mut palm = input("touch", 0);
palm.id = 10;
for (pointer_type, kind) in [("touch", "pointerdown"), ("touch", "pointermove"), ("mouse", "pointermove")] {
palm.pointer_type = pointer_type;
p.feed(kind, &palm, Pos2::ZERO, &[], true);
assert_eq!(feed.eraser(), Some(true), "{pointer_type} {kind}");
assert_eq!(end(&feed), Some(true), "{pointer_type} {kind}");
}
reset();
}
+84 -78
View File
@@ -1,8 +1,8 @@
//! macOS: a drawing tablet's pen pressure (#852), tilt and barrel rotation (#764), and an airbrush
//! pen's finger wheel. winit 0.30
//! hands a pen to the window there as a mouse, without them, so the app reads them from AppKit
//! itself and writes them into the UI's [`StylusFeed`] (`Services::stylus`), which the canvas
//! reads, as on X11 ([`crate::tablet`]).
//! itself and writes them into the framework's [`PenSource`], which the tool host reads, as on X11
//! ([`crate::tablet`]).
//!
//! A local event monitor (`addLocalMonitorForEventsMatchingMask:handler:`, which AppKit calls "with
//! each event it is about to dispatch" in this app:
@@ -10,8 +10,8 @@
//! reads each mouse and tablet event on the main thread before winit's view handles it, and passes
//! it on unchanged:
//! - A mouse event whose `subtype` is `NSEventSubtypeTabletPoint` comes from a pen: its `pressure`
//! (0..1) goes into the feed, kept for the pointer move winit makes of the event
//! ([`StylusFeed::set_move`]), so each move of a fast stroke has its own pressure. Its `tilt`
//! (0..1) goes into the source, which queues every reading, so each move of a fast stroke has
//! its own pressure. Its `tilt`
//! (−1..1 on each axis, ±[`TILT_DEGREES`] at the ends) and its `rotation` go into the feed as the
//! pen's pose, kept for that move too. AppKit gives a rotation of 0 for a pen that does not read
//! one and a tilt of 0 for an upright pen, so one event cannot tell a pen without tilt or rotation
@@ -33,7 +33,8 @@
//! works on plain values and is tested on every platform; the monitor reads them.
#![cfg_attr(not(target_os = "macos"), allow(dead_code))]
use vectorcraft_ui_egui::stylus::{PenPose, PenSample, StylusFeed};
use craft::behavior::PointerSample;
use craft::ui::runtime::pen::PenSource;
use crate::tablet::TILT_DEGREES;
@@ -91,12 +92,12 @@ impl RawEvent {
self.kind == event_type::TABLET_POINT || (self.mouse() && self.subtype == subtype::TABLET_POINT)
}
/// The pen's tilt and rotation in [`PenPose`]'s units.
/// The pen's reading as a [`PointerSample`], tilt and rotation in radians.
///
/// AppKit's `tilt` is −1.0..1.0 on each axis and 0.0 on both with the pen perpendicular to the
/// tablet. A negative x is a tilt to the left and a positive x a tilt to the right; a negative y
/// is a tilt to the top and a positive y a tilt to the bottom
/// (<https://developer.apple.com/documentation/appkit/nsevent/tilt>). [`PenPose`]'s x is positive
/// (<https://developer.apple.com/documentation/appkit/nsevent/tilt>). The sample's x is positive
/// to the right and its y positive down the page, the same signs, so each axis keeps its sign.
/// Apple gives the ends of the range as maximum tilt and does not give them in degrees
/// (<https://developer.apple.com/documentation/coregraphics/cgeventfield/tableteventtiltx>), so
@@ -108,22 +109,29 @@ impl RawEvent {
/// no direction for rotation; the Cocoa Event Handling Guide gives the `rotation` accessor's
/// degrees as counterclockwise for the rotate gesture
/// (<https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/EventOverview/HandlingTouchEvents/HandlingTouchEvents.html>),
/// and the pen's rotation is taken the same way. [`PenPose`]'s rotation runs clockwise, so the
/// angle is negated and brought into 0..360.
/// and the pen's rotation is taken the same way. The sample's rotation runs clockwise, so the
/// angle is negated and brought into 0..360 degrees.
///
/// AppKit's `tangentialPressure` is −1.0..1.0, the finger wheel of an airbrush pen on the
/// devices that have one (<https://developer.apple.com/documentation/appkit/nsevent/tangentialpressure>).
/// It becomes [`PenPose`]'s wheel of 0..1, −1.0 at 0 and 1.0 at 1; a value past either end is
/// It becomes the sample's wheel of 0..1, −1.0 at 0 and 1.0 at 1; a value past either end is
/// clamped.
///
/// The tilt is left out unless `read.tilts`, the rotation unless `read.turns`, and the wheel
/// unless `read.wheels` ([`Pen`]).
fn pose(&self, read: Reads) -> PenPose {
let degrees = |v: f64| (v.clamp(-1.0, 1.0) * TILT_DEGREES) as f32;
// `0.0 - r` rather than `-r`: a rotation of 0 gives 0, not −0.
let rotation = read.turns.then(|| (0.0 - self.rotation).rem_euclid(360.0));
let wheel = read.wheels.then(|| (self.tangential.clamp(-1.0, 1.0) + 1.0) / 2.0);
PenPose { tilt: read.tilts.then(|| [degrees(self.tilt.0), degrees(self.tilt.1)]), rotation, wheel }
fn sample(&self, read: Reads, eraser: bool) -> PointerSample {
let radians = |v: f64| ((v.clamp(-1.0, 1.0) * TILT_DEGREES) as f32).to_radians();
let mut sample = PointerSample::new(self.pressure);
sample.eraser = eraser;
if read.tilts {
sample.tilt = [radians(self.tilt.0), radians(self.tilt.1)];
}
if read.turns {
// `0.0 - r` rather than `-r`: a rotation of 0 gives 0, not −0.
sample.rotation = (0.0 - self.rotation).rem_euclid(360.0).to_radians();
}
sample.wheel = read.wheels.then(|| (self.tangential.clamp(-1.0, 1.0) + 1.0) / 2.0);
sample
}
/// Whether the event reports a tilt other than 0, a rotation other than 0, and a tangential
@@ -161,17 +169,14 @@ enum Update {
/// Nothing: an event the monitor doesn't map.
Keep,
/// The sample of a pen, or `None` for a mouse.
Set(Option<PenSample>),
/// A pen's sample that comes with a pointer move.
Move(PenSample),
Set(Option<PointerSample>),
}
impl Update {
fn apply(self, feed: &StylusFeed) {
fn apply(self, pen: &PenSource) {
match self {
Update::Keep => {}
Update::Set(sample) => feed.set_sample(sample),
Update::Move(sample) => feed.set_move(sample),
Update::Set(sample) => pen.set(sample),
}
}
}
@@ -193,29 +198,25 @@ impl Pen {
self.eraser = e.entering && e.device == device::ERASER;
self.read = Reads::default();
let pen = e.entering && e.device != device::CURSOR;
return Update::Set(pen.then_some(PenSample { pressure: 0.0, eraser: self.eraser, ..PenSample::default() }));
let mut near = PointerSample::new(0.0);
near.eraser = self.eraser;
return Update::Set(pen.then_some(near));
}
if e.point() {
self.read.add(e.reads());
return Update::Set(Some(e.sample(self.read, self.eraser)));
}
let sample = PenSample { pressure: e.pressure, eraser: self.eraser, pose: e.pose(self.read) };
match (e.point(), e.mouse()) {
(true, true) => Update::Move(sample),
(true, false) => Update::Set(Some(sample)),
(false, true) => Update::Set(None),
(false, false) => Update::Keep,
}
if e.mouse() { Update::Set(None) } else { Update::Keep }
}
}
/// Start reading pen pressure: the feed the monitor writes into, or `None` (logged) when AppKit
/// Start reading pen pressure: the source the monitor writes into, or `None` (logged) when AppKit
/// refuses the monitor or this isn't the main thread.
#[cfg(target_os = "macos")]
pub fn start() -> Option<StylusFeed> {
// The monitor writes on the main thread before winit hands the event on: a press never waits.
let feed = StylusFeed::on_ui_thread();
match monitor::install(feed.clone()) {
Ok(()) => Some(feed),
pub fn start() -> Option<PenSource> {
let pen = PenSource::default();
match monitor::install(pen.clone()) {
Ok(()) => Some(pen),
Err(e) => {
log::warn!("tablet pressure: {e}");
None
@@ -231,12 +232,12 @@ mod monitor {
use block2::RcBlock;
use objc2::MainThreadMarker;
use objc2_app_kit::{NSEvent, NSEventMask};
use vectorcraft_ui_egui::stylus::StylusFeed;
use craft::ui::runtime::pen::PenSource;
use super::{Pen, RawEvent, event_mask};
/// Install the monitor for the life of the app. Main thread only.
pub(super) fn install(feed: StylusFeed) -> Result<(), &'static str> {
pub(super) fn install(source: PenSource) -> Result<(), &'static str> {
MainThreadMarker::new().ok_or("the event monitor can only be installed from the main thread")?;
let pen = Cell::new(Pen::default());
let handler = RcBlock::new(move |event: NonNull<NSEvent>| -> *mut NSEvent {
@@ -245,7 +246,7 @@ mod monitor {
#[allow(unsafe_code)]
let e = unsafe { event.as_ref() };
let mut p = pen.get();
p.handle(&read(e)).apply(&feed);
p.handle(&read(e)).apply(&source);
pen.set(p);
event.as_ptr()
});
@@ -298,20 +299,29 @@ mod tests {
}
/// A sample of the tip of a pen that has reported no tilt or rotation.
fn tip(pressure: f32) -> PenSample {
PenSample { pressure, eraser: false, pose: PenPose::default() }
fn tip(pressure: f32) -> PointerSample {
PointerSample::new(pressure)
}
/// A sample of the pen near the tablet but not yet read: no pose.
fn near(eraser: bool) -> PenSample {
PenSample { pressure: 0.0, eraser, pose: PenPose::default() }
/// A sample of the pen near the tablet but not yet read: no tilt or rotation.
fn near(eraser: bool) -> PointerSample {
let mut sample = PointerSample::new(0.0);
sample.eraser = eraser;
sample
}
/// `sample` held as `tilt` and `rotation` (radians).
fn held(mut sample: PointerSample, tilt: [f32; 2], rotation: f32) -> PointerSample {
sample.tilt = tilt;
sample.rotation = rotation;
sample
}
#[test]
fn a_pens_mouse_events_are_moves_with_its_pressure() {
let mut p = Pen::default();
assert_eq!(p.handle(&pen(DRAG, 0.5)), Update::Move(tip(0.5)));
assert_eq!(p.handle(&pen(1, 0.25)), Update::Move(tip(0.25)), "a press");
assert_eq!(p.handle(&pen(DRAG, 0.5)), Update::Set(Some(tip(0.5))));
assert_eq!(p.handle(&pen(1, 0.25)), Update::Set(Some(tip(0.25))), "a press");
assert_eq!(p.handle(&pen(event_type::TABLET_POINT, 0.8)), Update::Set(Some(tip(0.8))), "no move");
}
@@ -332,11 +342,11 @@ mod tests {
#[test]
fn proximity_says_which_end_is_near() {
let mut p = Pen::default();
let eraser = |pressure| PenSample { pressure, eraser: true, pose: PenPose::default() };
let eraser = |pressure| PointerSample { pressure, ..near(true) };
assert_eq!(p.handle(&proximity(device::ERASER, true)), Update::Set(Some(near(true))));
assert_eq!(p.handle(&pen(DRAG, 0.4)), Update::Move(eraser(0.4)));
assert_eq!(p.handle(&pen(DRAG, 0.4)), Update::Set(Some(eraser(0.4))));
assert_eq!(p.handle(&proximity(device::ERASER, false)), Update::Set(None), "it left");
assert_eq!(p.handle(&pen(DRAG, 0.4)), Update::Move(tip(0.4)));
assert_eq!(p.handle(&pen(DRAG, 0.4)), Update::Set(Some(tip(0.4))));
assert_eq!(p.handle(&proximity(1, true)), Update::Set(Some(near(false))), "the tip");
assert_eq!(p.handle(&proximity(0, true)), Update::Set(Some(near(false))), "an unknown tool draws as the tip");
assert_eq!(p.handle(&proximity(device::CURSOR, true)), Update::Set(None), "a puck is a mouse");
@@ -345,42 +355,39 @@ mod tests {
}
/// #764: AppKit's tilt (−1..1, x positive to the right, y positive to the bottom) reaches the
/// feed in degrees with the same signs, and its rotation, taken as counterclockwise, reaches it
/// clockwise.
/// source in radians with the same signs, and its rotation, taken as counterclockwise, reaches
/// it clockwise.
#[test]
fn a_pens_tilt_and_rotation_go_into_the_feed() {
let mut p = Pen::default();
let sample = |pressure, pose| PenSample { pressure, eraser: false, pose };
assert_eq!(p.handle(&pen(DRAG, 0.5)), Update::Move(tip(0.5)), "no tilt or rotation reported yet");
let deg = f32::to_radians;
assert_eq!(p.handle(&pen(DRAG, 0.5)), Update::Set(Some(tip(0.5))), "no tilt or rotation reported yet");
let leaning = RawEvent { tilt: (0.5, -0.25), rotation: 30.0, ..pen(DRAG, 0.5) };
let pose = PenPose { tilt: Some([30.0, -15.0]), rotation: Some(330.0), wheel: None };
assert_eq!(p.handle(&leaning), Update::Move(sample(0.5, pose)));
assert_eq!(p.handle(&leaning), Update::Set(Some(held(tip(0.5), [deg(30.0), deg(-15.0)], deg(330.0)))));
let past_the_ends = RawEvent { tilt: (-4.0, 1.5), rotation: 270.0, ..pen(event_type::TABLET_POINT, 0.8) };
let pose = PenPose { tilt: Some([-60.0, 60.0]), rotation: Some(90.0), wheel: None };
assert_eq!(p.handle(&past_the_ends), Update::Set(Some(sample(0.8, pose))), "clamped");
let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None };
let Update::Move(upright) = p.handle(&pen(DRAG, 0.6)) else { panic!("a pen's drag is a move") };
assert_eq!(upright, sample(0.6, pose), "once reported, 0 is upright and unturned");
assert!(upright.pose.rotation.is_some_and(f32::is_sign_positive), "{upright:?}");
let feed = StylusFeed::default();
p.handle(&RawEvent { tilt: (f64::NAN, 0.0), rotation: -90.0, ..pen(DRAG, 0.3) }).apply(&feed);
assert_eq!(feed.pose(), Some(PenPose { rotation: Some(90.0), ..PenPose::default() }), "a tilt that is not a number is left out");
assert_eq!(p.handle(&past_the_ends), Update::Set(Some(held(tip(0.8), [deg(-60.0), deg(60.0)], deg(90.0)))), "clamped");
let Update::Set(Some(upright)) = p.handle(&pen(DRAG, 0.6)) else { panic!("a pen's drag is a sample") };
assert_eq!(upright, tip(0.6), "once reported, 0 is upright and unturned");
assert!(upright.rotation.is_sign_positive(), "{upright:?}");
let source = PenSource::default();
p.handle(&RawEvent { tilt: (f64::NAN, 0.0), rotation: -90.0, ..pen(DRAG, 0.3) }).apply(&source);
let sample = source.current().unwrap();
assert_eq!((sample.tilt, sample.rotation), ([0.0, 0.0], deg(90.0)), "a tilt that is not a number is left out");
p.handle(&proximity(1, true));
let tilted = RawEvent { tilt: (0.0, 0.5), ..pen(event_type::TABLET_POINT, 0.8) };
let pose = PenPose { tilt: Some([0.0, 30.0]), ..PenPose::default() };
assert_eq!(p.handle(&tilted), Update::Set(Some(sample(0.8, pose))), "no rotation reported since the pen came near");
p.handle(&RawEvent { kind: DRAG, ..Default::default() }).apply(&feed);
assert_eq!(feed.pose(), None, "a mouse moved");
assert_eq!(p.handle(&tilted), Update::Set(Some(held(tip(0.8), [0.0, deg(30.0)], 0.0))), "no rotation reported since the pen came near");
p.handle(&RawEvent { kind: DRAG, ..Default::default() }).apply(&source);
assert_eq!(source.current(), None, "a mouse moved");
}
/// An airbrush pen's finger wheel (AppKit's `tangentialPressure`, −1..1) reaches the feed as
/// An airbrush pen's finger wheel (AppKit's `tangentialPressure`, −1..1) reaches the source as
/// 0..1, once the pen has reported a value other than 0 since it came near.
#[test]
fn an_airbrush_wheel_goes_into_the_feed() {
let mut p = Pen::default();
let wheel = |p: &mut Pen, tangential: f32| match p.handle(&RawEvent { tangential, ..pen(DRAG, 0.5) }) {
Update::Move(s) => s.pose.wheel,
u => panic!("a pen's drag is a move: {u:?}"),
Update::Set(Some(s)) => s.wheel,
u => panic!("a pen's drag is a sample: {u:?}"),
};
assert_eq!(wheel(&mut p, 0.0), None, "no wheel reported yet");
assert_eq!(wheel(&mut p, -1.0), Some(0.0));
@@ -393,15 +400,14 @@ mod tests {
#[test]
fn the_feed_gets_each_moves_pressure_within_0_to_1() {
let feed = StylusFeed::default();
let source = PenSource::default();
let mut p = Pen::default();
for e in [pen(DRAG, f32::NAN), pen(DRAG, 4.0), pen(DRAG, -1.0), pen(event_type::TABLET_POINT, 0.3)] {
p.handle(&e).apply(&feed);
for (e, expected) in [(pen(DRAG, f32::NAN), 1.0), (pen(DRAG, 4.0), 1.0), (pen(DRAG, -1.0), 0.0), (pen(event_type::TABLET_POINT, 0.3), 0.3)] {
p.handle(&e).apply(&source);
assert_eq!(source.current().map(|s| s.pressure), Some(expected));
}
let pressures: Vec<f32> = feed.take_moves().into_iter().map(|(p, _)| p).collect();
assert_eq!((pressures, feed.held()), (vec![1.0, 1.0, 0.0], Some(0.3)));
p.handle(&RawEvent { kind: DRAG, ..Default::default() }).apply(&feed);
assert_eq!(feed.held(), None, "a mouse moved");
p.handle(&RawEvent { kind: DRAG, ..Default::default() }).apply(&source);
assert_eq!(source.current(), None, "a mouse moved");
}
#[test]
+111 -98
View File
@@ -1,8 +1,8 @@
//! Linux: a drawing tablet's pen pressure, tilt, barrel rotation and airbrush finger wheel under
//! X11, XWayland included
//! (#764). winit 0.30 hands a pen to the window there as a mouse, without any of them, so the app
//! reads them from XInput2 itself and writes them into the UI's [`StylusFeed`]
//! (`Services::stylus`), which the canvas reads.
//! reads them from XInput2 itself and writes them into the framework's [`PenSource`], which the
//! tool host reads.
//!
//! The reader opens a second connection to the X server (x11rb's `RustConnection`, without
//! `unsafe` or libxcb) and selects XInput2 raw events for every device on the root window. Raw
@@ -43,7 +43,8 @@
use std::collections::HashMap;
use vectorcraft_ui_egui::stylus::{PenPose, PenSample, StylusFeed};
use craft::behavior::PointerSample;
use craft::ui::runtime::pen::PenSource;
/// The tilt of a valuator whose range does not fit in ±90 (so does not give degrees), at the ends
/// of its range.
@@ -180,7 +181,7 @@ enum Update {
/// Nothing: a device the last listing didn't have (a master, or one added since).
Keep,
/// The pressure, end, tilt and rotation of a pen, or `None` for another pointer.
Set(Option<PenSample>),
Set(Option<PointerSample>),
}
/// The pointer devices and the last pressure, tilt and rotation of each pen.
@@ -217,17 +218,21 @@ impl Pens {
// An axis the pen has reads 0 until an event carries it; one it lacks reads nothing. The
// wheel reads nothing until an event carries it: XWayland lists the axis for every pen.
let value = |kind: AxisKind| device.axis(kind).map(|_| last.get(kind.slot()).copied().flatten().unwrap_or(0.0));
let tilt = value(AxisKind::TiltX).zip(value(AxisKind::TiltY)).map(|(x, y)| [x, y]);
let wheel = device.axis(AxisKind::Wheel).and_then(|_| last.get(AxisKind::Wheel.slot()).copied().flatten());
let pose = PenPose { tilt, rotation: value(AxisKind::Rotation), wheel };
Update::Set(Some(PenSample { pressure: value(AxisKind::Pressure).unwrap_or(0.0), eraser: device.eraser, pose }))
// The valuators give degrees; the framework's samples are in radians.
let tilt = value(AxisKind::TiltX).zip(value(AxisKind::TiltY)).map_or([0.0, 0.0], |(x, y)| [x.to_radians(), y.to_radians()]);
let mut sample = PointerSample::new(value(AxisKind::Pressure).unwrap_or(0.0));
sample.tilt = tilt;
sample.rotation = value(AxisKind::Rotation).map_or(0.0, f32::to_radians);
sample.eraser = device.eraser;
sample.wheel = device.axis(AxisKind::Wheel).and_then(|_| last.get(AxisKind::Wheel.slot()).copied().flatten());
Update::Set(Some(sample))
}
/// A raw event as the X server sends it: its valuator mask and the values of the valuators
/// set in it. A pen's sample or another pointer's `None` goes into `feed`.
fn raw_event(&mut self, feed: &StylusFeed, id: u16, mask: &[u32], values: &[f64]) {
/// set in it. A pen's sample or another pointer's `None` goes into `pen`.
fn raw_event(&mut self, pen: &PenSource, id: u16, mask: &[u32], values: &[f64]) {
if let Update::Set(sample) = self.handle(id, valuators(mask, values)) {
feed.set_sample(sample);
pen.set(sample);
}
}
}
@@ -247,13 +252,13 @@ fn fp3232(integral: i32, frac: u32) -> f64 {
f64::from(integral) + f64::from(frac) / 4_294_967_296.0
}
/// Start reading pen pressure, tilt and rotation for a window on X11: the feed the reader writes
/// Start reading pen pressure, tilt and rotation for a window on X11: the source the reader writes
/// into, or `None` (logged) when the X server can't be reached or has no XInput 2.1.
#[cfg(target_os = "linux")]
pub fn start() -> Option<StylusFeed> {
let feed = StylusFeed::default();
match x11::spawn(feed.clone()) {
Ok(()) => Some(feed),
pub fn start() -> Option<PenSource> {
let pen = PenSource::default();
match x11::spawn(pen.clone()) {
Ok(()) => Some(pen),
Err(e) => {
log::warn!("tablet pressure: {e}");
None
@@ -265,7 +270,7 @@ pub fn start() -> Option<StylusFeed> {
mod x11 {
use std::collections::HashMap;
use vectorcraft_ui_egui::stylus::StylusFeed;
use craft::ui::runtime::pen::PenSource;
use x11rb::connection::{Connection as _, RequestConnection as _};
use x11rb::protocol::Event;
use x11rb::protocol::xinput::{self, ConnectionExt as _, DeviceClassData, DeviceType, XIEventMask};
@@ -280,7 +285,7 @@ mod x11 {
/// Connect to `$DISPLAY` (the display winit opened the window on), check for XInput 2.1 (raw
/// events for every client that selects them), select the raw events, and read them on a
/// thread of its own until the connection closes.
pub fn spawn(feed: StylusFeed) -> Result<(), String> {
pub fn spawn(pen: PenSource) -> Result<(), String> {
let (conn, screen) = RustConnection::connect(None).map_err(|e| format!("can't connect to the X server: {e}"))?;
let root = conn.setup().roots.get(screen).map(|s| s.root).ok_or_else(|| format!("X screen {screen} not found"))?;
let version =
@@ -301,12 +306,12 @@ mod x11 {
pens.set_devices(query_devices(&conn));
std::thread::Builder::new()
.name("vectorcraft-tablet-x11".into())
.spawn(move || run(&conn, &mut pens, &feed))
.spawn(move || run(&conn, &mut pens, &pen))
.map(drop)
.map_err(|e| format!("can't start the tablet thread: {e}"))
}
fn run(conn: &RustConnection, pens: &mut Pens, feed: &StylusFeed) {
fn run(conn: &RustConnection, pens: &mut Pens, pen: &PenSource) {
// A connection error (the display went away) ends the loop; an event that x11rb cannot
// parse is skipped, and `Pens` bounds what the rest can hold.
while let Ok(raw) = conn.wait_for_raw_event() {
@@ -314,7 +319,7 @@ mod x11 {
match event {
Event::XinputRawMotion(e) | Event::XinputRawButtonPress(e) | Event::XinputRawButtonRelease(e) => {
let values: Vec<f64> = e.axisvalues.iter().map(|v| fp3232(v.integral, v.frac)).collect();
pens.raw_event(feed, e.deviceid, &e.valuator_mask, &values);
pens.raw_event(pen, e.deviceid, &e.valuator_mask, &values);
}
Event::XinputHierarchy(_) | Event::XinputDeviceChanged(_) => pens.set_devices(query_devices(conn)),
_ => {}
@@ -384,6 +389,16 @@ mod tests {
Device::new(id, "Logitech USB Optical Mouse", Some("MOUSE"), [(0, "Rel X".to_string(), -1.0, -1.0), (1, "Rel Y".to_string(), -1.0, -1.0)])
}
/// A reading as the reader gives it: tilt and rotation in radians.
fn reading(pressure: f32, eraser: bool, tilt: [f32; 2], rotation: f32, wheel: Option<f32>) -> PointerSample {
let mut sample = PointerSample::new(pressure);
sample.eraser = eraser;
sample.tilt = tilt;
sample.rotation = rotation;
sample.wheel = wheel;
sample
}
#[test]
fn the_mask_pairs_valuator_numbers_with_values() {
let v: Vec<_> = valuators(&[0b10_0101, 1], &[1.0, 2.0, 3.0, 4.0]).collect();
@@ -445,58 +460,57 @@ mod tests {
fn the_eraser_device_sets_the_eraser_end() {
let mut pens = Pens::default();
pens.set_devices([pen(9), Device::new(10, "Wacom Intuos Pro M Pen eraser", Some("ERASER"), pen_valuators()), mouse(12)]);
let feed = StylusFeed::default();
let pose = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None };
pens.raw_event(&feed, 9, &[0b100], &[32767.5]);
assert_eq!(pens.handle(9, []), Update::Set(Some(PenSample { pressure: 0.5, eraser: false, pose })));
assert_eq!(feed.eraser(), Some(false));
let pen = PenSource::default();
let end = || pen.current().map(|s| (s.eraser, s.pressure));
pens.raw_event(&pen, 9, &[0b100], &[32767.5]);
assert_eq!(pens.handle(9, []), Update::Set(Some(reading(0.5, false, [0.0, 0.0], 0.0, None))));
assert_eq!(end(), Some((false, 0.5)));
// Turned over, the pen hovers with its eraser end: the eraser device's first event, with
// no pressure yet.
pens.raw_event(&feed, 10, &[0b1], &[100.0]);
assert_eq!(pens.handle(10, []), Update::Set(Some(PenSample { pressure: 0.0, eraser: true, pose })));
assert_eq!((feed.eraser(), feed.held()), (Some(true), Some(0.0)));
pens.raw_event(&feed, 10, &[0b100], &[65535.0]);
assert_eq!((feed.eraser(), feed.held()), (Some(true), Some(1.0)));
pens.raw_event(&pen, 10, &[0b1], &[100.0]);
assert_eq!(pens.handle(10, []), Update::Set(Some(reading(0.0, true, [0.0, 0.0], 0.0, None))));
assert_eq!(end(), Some((true, 0.0)));
pens.raw_event(&pen, 10, &[0b100], &[65535.0]);
assert_eq!(end(), Some((true, 1.0)));
// Back to the tip, with the tip's own last pressure.
pens.raw_event(&feed, 9, &[0b1], &[200.0]);
assert_eq!((feed.eraser(), feed.held()), (Some(false), Some(0.5)));
pens.raw_event(&pen, 9, &[0b1], &[200.0]);
assert_eq!(end(), Some((false, 0.5)));
// A mouse: no pen end.
pens.raw_event(&feed, 12, &[0b1], &[3.0]);
assert_eq!(feed.eraser(), None);
pens.raw_event(&pen, 12, &[0b1], &[3.0]);
assert_eq!(end(), None);
}
/// #764: a pen's tilt goes into the feed in degrees and its barrel rotation as a turn, the
/// middle of the valuator's range at 0°; a pen without those valuators reads neither.
/// #764: a pen's tilt goes into the source in radians and its barrel rotation as a turn, the
/// middle of the valuator's range at 0; a pen without those valuators reads neither.
#[test]
fn a_pens_tilt_and_rotation_go_into_the_feed() {
let mut pens = Pens::default();
let pressure_only = Device::new(10, "", Some("STYLUS"), pen_valuators().into_iter().take(3));
let one_tilt = Device::new(11, "", Some("STYLUS"), pen_valuators().into_iter().take(4));
pens.set_devices([pen(9), pressure_only, one_tilt, mouse(12)]);
let feed = StylusFeed::default();
let pen_source = PenSource::default();
// Pressure, tilt x, tilt y and rotation: valuators 2 to 5.
pens.raw_event(&feed, 9, &[0b11_1100], &[32767.5, -30.0, 45.0, 0.0]);
let pose = feed.pose().unwrap();
assert_eq!((feed.held(), pose.tilt), (Some(0.5), Some([-30.0, 45.0])));
assert!(pose.rotation.is_some_and(|r| r < 0.2), "{pose:?}");
pens.raw_event(&pen_source, 9, &[0b11_1100], &[32767.5, -30.0, 45.0, 0.0]);
let sample = pen_source.current().unwrap();
assert_eq!((sample.pressure, sample.tilt), (0.5, [(-30.0f32).to_radians(), 45.0f32.to_radians()]));
assert!(sample.rotation < 0.2f32.to_radians(), "{sample:?}");
// A quarter of the range back is a quarter turn back; the tilt stays as it was.
pens.raw_event(&feed, 9, &[0b10_0000], &[-450.0]);
let pose = feed.pose().unwrap();
assert_eq!(pose.tilt, Some([-30.0, 45.0]));
assert!(pose.rotation.is_some_and(|r| (r - 270.0).abs() < 0.2), "{pose:?}");
pens.raw_event(&pen_source, 9, &[0b10_0000], &[-450.0]);
let sample = pen_source.current().unwrap();
assert_eq!(sample.tilt, [(-30.0f32).to_radians(), 45.0f32.to_radians()]);
assert!((sample.rotation - (-90.0f32).to_radians()).abs() < 0.2f32.to_radians(), "{sample:?}");
// A pen with no tilt or rotation valuators, or with one tilt valuator only, reads none.
pens.raw_event(&feed, 10, &[0b100], &[65535.0]);
assert_eq!((feed.held(), feed.pose()), (Some(1.0), None));
pens.raw_event(&feed, 11, &[0b1100], &[65535.0, 20.0]);
assert_eq!(feed.pose(), None);
pens.raw_event(&pen_source, 10, &[0b100], &[65535.0]);
assert_eq!(pen_source.current(), Some(reading(1.0, false, [0.0, 0.0], 0.0, None)));
pens.raw_event(&pen_source, 11, &[0b1100], &[65535.0, 20.0]);
assert_eq!(pen_source.current().map(|s| s.tilt), Some([0.0, 0.0]));
// The mouse: none.
pens.raw_event(&feed, 12, &[0b1], &[3.0]);
assert_eq!(feed.pose(), None);
pens.raw_event(&pen_source, 12, &[0b1], &[3.0]);
assert_eq!(pen_source.current(), None);
// A pen whose tilt and rotation no event has carried yet is upright and unturned.
let mut fresh = Pens::default();
fresh.set_devices([pen(9)]);
let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None };
assert_eq!(fresh.handle(9, [(2, 0.0)]), Update::Set(Some(PenSample { pressure: 0.0, eraser: false, pose: upright })));
assert_eq!(fresh.handle(9, [(2, 0.0)]), Update::Set(Some(reading(0.0, false, [0.0, 0.0], 0.0, None))));
}
/// An airbrush pen's "Abs Wheel" valuator goes into the feed as 0..1 of its range, once an
@@ -510,19 +524,20 @@ mod tests {
let pad = Device::new(13, "Wacom Intuos Pro M Pad pad", Some("PAD"), [(6, "Abs Wheel".to_string(), 0.0, 71.0)]);
let mut pens = Pens::default();
pens.set_devices([airbrush, pad, pen(10)]);
let feed = StylusFeed::default();
pens.raw_event(&feed, 9, &[0b100], &[32767.5]);
assert_eq!(feed.pose().and_then(|q| q.wheel), None, "no event has carried the wheel yet");
pens.raw_event(&feed, 9, &[0b100_0000], &[255.75]);
assert_eq!(feed.pose().and_then(|q| q.wheel), Some(0.25));
pens.raw_event(&feed, 9, &[0b100_0000], &[5000.0]);
assert_eq!(feed.pose().and_then(|q| q.wheel), Some(1.0), "clamped to the range");
pens.raw_event(&feed, 9, &[0b100], &[100.0]);
assert_eq!(feed.pose().and_then(|q| q.wheel), Some(1.0), "kept while other valuators move");
pens.raw_event(&feed, 13, &[0b100_0000], &[30.0]);
assert_eq!((feed.held(), feed.pose()), (None, None), "the pad is not a pen");
pens.raw_event(&feed, 10, &[0b100_0000], &[512.0]);
assert_eq!(feed.pose().and_then(|q| q.wheel), None, "a pen without the valuator");
let pen_source = PenSource::default();
let wheel = || pen_source.current().and_then(|s| s.wheel);
pens.raw_event(&pen_source, 9, &[0b100], &[32767.5]);
assert_eq!(wheel(), None, "no event has carried the wheel yet");
pens.raw_event(&pen_source, 9, &[0b100_0000], &[255.75]);
assert_eq!(wheel(), Some(0.25));
pens.raw_event(&pen_source, 9, &[0b100_0000], &[5000.0]);
assert_eq!(wheel(), Some(1.0), "clamped to the range");
pens.raw_event(&pen_source, 9, &[0b100], &[100.0]);
assert_eq!(wheel(), Some(1.0), "kept while other valuators move");
pens.raw_event(&pen_source, 13, &[0b100_0000], &[30.0]);
assert_eq!(pen_source.current(), None, "the pad is not a pen");
pens.raw_event(&pen_source, 10, &[0b100_0000], &[512.0]);
assert_eq!(wheel(), None, "a pen without the valuator");
}
/// A device listed again unchanged keeps its last tilt and rotation; another device listed
@@ -533,12 +548,11 @@ mod tests {
pens.set_devices([pen(9)]);
pens.handle(9, [(3, -30.0), (4, 45.0), (5, -450.0)]);
pens.set_devices([pen(9)]);
let Update::Set(Some(PenSample { pose, .. })) = pens.handle(9, [(2, 0.0)]) else { panic!("no pen") };
assert_eq!(pose.tilt, Some([-30.0, 45.0]));
let Update::Set(Some(sample)) = pens.handle(9, [(2, 0.0)]) else { panic!("no pen") };
assert_eq!(sample.tilt, [(-30.0f32).to_radians(), 45.0f32.to_radians()]);
let other = Device::new(9, "HUION Kamvas Pen Pen (0x1)", Some("STYLUS"), pen_valuators());
pens.set_devices([other]);
let upright = PenPose { tilt: Some([0.0, 0.0]), rotation: Some(0.0), wheel: None };
assert_eq!(pens.handle(9, [(2, 0.0)]), Update::Set(Some(PenSample { pressure: 0.0, eraser: false, pose: upright })));
assert_eq!(pens.handle(9, [(2, 0.0)]), Update::Set(Some(reading(0.0, false, [0.0, 0.0], 0.0, None))));
}
/// Tilt valuators whose range does not fit in ±90 are scaled to ±60°.
@@ -552,34 +566,35 @@ mod tests {
);
let mut pens = Pens::default();
pens.set_devices([d]);
let Update::Set(Some(PenSample { pose, .. })) = pens.handle(1, [(3, 127.0), (4, -1000.0)]) else { panic!("no pen") };
assert_eq!(pose.tilt, Some([60.0, -60.0]));
let Update::Set(Some(sample)) = pens.handle(1, [(3, 127.0), (4, -1000.0)]) else { panic!("no pen") };
assert_eq!(sample.tilt, [60.0f32.to_radians(), (-60.0f32).to_radians()]);
}
#[test]
fn a_pens_valuator_becomes_its_pressure_and_another_pointer_clears_it() {
let mut pens = Pens::default();
pens.set_devices([pen(9), mouse(12)]);
let feed = StylusFeed::default();
pens.raw_event(&feed, 9, &[0b101], &[100.0, 32767.5]);
assert_eq!(feed.held(), Some(0.5));
let pen_source = PenSource::default();
let pressure = || pen_source.current().map(|s| s.pressure);
pens.raw_event(&pen_source, 9, &[0b101], &[100.0, 32767.5]);
assert_eq!(pressure(), Some(0.5));
// Raw events carry only the valuators that changed: a move without pressure keeps it.
pens.raw_event(&feed, 9, &[0b1], &[200.0]);
assert_eq!(feed.held(), Some(0.5));
pens.raw_event(&feed, 9, &[0b100], &[65535.0]);
assert_eq!(feed.held(), Some(1.0));
pens.raw_event(&pen_source, 9, &[0b1], &[200.0]);
assert_eq!(pressure(), Some(0.5));
pens.raw_event(&pen_source, 9, &[0b100], &[65535.0]);
assert_eq!(pressure(), Some(1.0));
// The mouse moves: no pen pressure until the pen moves again.
pens.raw_event(&feed, 12, &[0b1], &[3.0]);
assert_eq!(feed.held(), None);
pens.raw_event(&feed, 9, &[0b1], &[300.0]);
assert_eq!(feed.held(), Some(1.0), "the pen's last pressure");
pens.raw_event(&pen_source, 12, &[0b1], &[3.0]);
assert_eq!(pressure(), None);
pens.raw_event(&pen_source, 9, &[0b1], &[300.0]);
assert_eq!(pressure(), Some(1.0), "the pen's last pressure");
// A master device or one not listed yet changes nothing.
pens.raw_event(&feed, 2, &[0b100], &[0.0]);
assert_eq!(feed.held(), Some(1.0));
// A pen whose first event carries no pressure is hovering: it presses with 0.
pens.raw_event(&pen_source, 2, &[0b100], &[0.0]);
assert_eq!(pressure(), Some(1.0));
// A pen whose first event carries no pressure is hovering: it reads 0.
pens.set_devices([pen(9), pen(10)]);
pens.raw_event(&feed, 10, &[0b1], &[5.0]);
assert_eq!(feed.press(), Some(0.0));
pens.raw_event(&pen_source, 10, &[0b1], &[5.0]);
assert_eq!(pressure(), Some(0.0));
}
#[test]
@@ -590,13 +605,11 @@ mod tests {
let labels = ["Abs Pressure", "Abs Tilt X", "Abs Tilt Y", "Abs Rotary Z"];
pens.set_devices([Device::new(1, "", None, (2..).zip(labels).map(|(n, l)| (n, l.to_string(), min, max)))]);
for v in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX, f64::MIN, -0.0, 1e300, 0.5] {
let Update::Set(Some(PenSample { pressure: p, pose, .. })) = pens.handle(1, (2..6).map(|n| (n, v))) else {
panic!("{min}..{max}: {v} gave no pressure")
};
assert!((0.0..=1.0).contains(&p), "{min}..{max}: {v} gave {p}");
let tilt = pose.tilt.unwrap_or_default();
assert!(tilt.iter().all(|t| (-90.0..=90.0).contains(t)), "{min}..{max}: {v} gave {pose:?}");
assert!(pose.rotation.is_some_and(|r| (-180.0..=180.0).contains(&r)), "{min}..{max}: {v} gave {pose:?}");
let Update::Set(Some(s)) = pens.handle(1, (2..6).map(|n| (n, v))) else { panic!("{min}..{max}: {v} gave no pressure") };
assert!((0.0..=1.0).contains(&s.pressure), "{min}..{max}: {v} gave {s:?}");
let quarter = std::f32::consts::FRAC_PI_2 + 1e-6;
assert!(s.tilt.iter().all(|t| t.abs() <= quarter), "{min}..{max}: {v} gave {s:?}");
assert!(s.rotation.abs() <= std::f32::consts::PI + 1e-6, "{min}..{max}: {v} gave {s:?}");
}
}
let mut pens = Pens::default();
@@ -604,10 +617,10 @@ mod tests {
assert!(pens.devices.len() <= MAX_DEVICES, "the device list is bounded");
// Values for valuators the pen doesn't have are ignored.
pens.set_devices([pen(3)]);
let Update::Set(Some(PenSample { pressure: p, .. })) = pens.handle(3, valuators(&[u32::MAX; 2048], &[0.5; 4096]).collect::<Vec<_>>()) else {
let Update::Set(Some(s)) = pens.handle(3, valuators(&[u32::MAX; 2048], &[0.5; 4096]).collect::<Vec<_>>()) else {
panic!("the pen gave no pressure")
};
assert!(p < 0.001, "{p}");
assert!(s.pressure < 0.001, "{}", s.pressure);
}
#[test]
+69 -322
View File
@@ -1,21 +1,21 @@
//! Windows pen tablets: with Windows Ink, winit reports a pen in contact as a touch and drops its
//! barrel button, and egui-winit presses the primary button for the touch it makes the pointer,
//! so a pen pressed with its barrel button held clicks and drags with the left button. The
//! `WM_POINTERDOWN` message winit is about to handle still has the barrel button's state in its
//! second-button flag ("analogous to a mouse right button down",
//! <https://learn.microsoft.com/en-us/windows/win32/inputmsg/wm-pointerdown>): [`msg_hook`] notes
//! it, and [`raw_input_hook`] makes the primary button of that contact the secondary one.
//!
//! winit also drops which end of the pen is down. For each pointer message of a pen, [`msg_hook`]
//! reads the pen's `POINTER_PEN_INFO` and writes its pressure and end into the canvas's pen feed
//! ([`start`]): `PEN_FLAG_INVERTED` ("The pen is inverted") or `PEN_FLAG_ERASER` ("The eraser
//! button is pressed") is the eraser end
//! barrel button and which end of the pen is down. For each pointer message of a pen,
//! [`msg_hook`] reads the pen's `POINTER_PEN_INFO` before winit handles the message and writes its
//! pressure, end, tilt and rotation into the framework's [`PenSource`] ([`start`]):
//! `PEN_FLAG_INVERTED` ("The pen is inverted") or `PEN_FLAG_ERASER` ("The eraser button is
//! pressed") is the eraser end
//! (<https://learn.microsoft.com/en-us/windows/win32/inputmsg/pen-flags-constants>). Pointer
//! messages also come while the pen hovers, so turning the pen over selects the Eraser tool before
//! it touches. A message of another pointer, a pen leaving detection range or the window, or a
//! mouse message that Windows did not make from a pen or a touch
//! (<https://learn.microsoft.com/en-us/windows/win32/tablet/system-events-and-mouse-messages>)
//! clears the feed.
//! clears the source.
//!
//! The barrel button is the second-button flag of the pointer message ("analogous to a mouse right
//! button down",
//! <https://learn.microsoft.com/en-us/windows/win32/inputmsg/wm-pointerdown>): it goes to the
//! source, whose pointer feed turns the primary button of a contact that went down with it held
//! into the secondary button.
//!
//! The same `POINTER_PEN_INFO` gives the pen's tilt and barrel rotation (#372: a 6D Art Pen turns a
//! Calligraphic brush's nib with its barrel), each only where its `PEN_MASK_*` bit says the pen
@@ -23,14 +23,14 @@
//! `tiltX` and `tiltY` in degrees −90..90, positive to the right and toward the user, and
//! `rotation` in degrees 0..359 clockwise
//! (<https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-pointer_pen_info>).
//! Toward the user is down the screen, so they are [`PenPose`]'s axes and direction as they come.
//! Toward the user is down the screen, so they are the sample's axes and direction as they come,
//! converted to radians. `POINTER_PEN_INFO` has no field for an airbrush pen's finger wheel.
#![cfg_attr(not(windows), allow(dead_code))]
use std::cell::RefCell;
use std::sync::OnceLock;
use egui::{Event, Modifiers, PointerButton, Pos2, TouchId, TouchPhase};
use vectorcraft_ui_egui::stylus::{PenPose, PenSample, StylusFeed};
use craft::behavior::PointerSample;
use craft::ui::runtime::pen::PenSource;
/// `POINTER_MESSAGE_FLAG_SECONDBUTTON` (`winuser.h`): in the high word of a pointer message's
/// `wParam`, a pen in contact with its barrel button pressed.
@@ -38,8 +38,6 @@ const POINTER_MESSAGE_FLAG_SECONDBUTTON: usize = 0x0020;
/// `POINTER_MESSAGE_FLAG_INRANGE` (`winuser.h`): not set on the message of a pointer that has left
/// detection range.
const POINTER_MESSAGE_FLAG_INRANGE: usize = 0x0002;
/// At most this many pointer contacts wait for their touch event.
const MAX_PENDING: usize = 16;
/// `PEN_FLAG_INVERTED` and `PEN_FLAG_ERASER` (`winuser.h`), in `POINTER_PEN_INFO::penFlags`.
const PEN_FLAG_INVERTED: u32 = 0x0002;
const PEN_FLAG_ERASER: u32 = 0x0004;
@@ -64,23 +62,20 @@ const WM_POINTERUP: u32 = 0x0247;
const WM_POINTERENTER: u32 = 0x0249;
const WM_POINTERLEAVE: u32 = 0x024A;
thread_local! {
static STROKES: RefCell<BarrelStrokes> = RefCell::new(BarrelStrokes::default());
}
/// A pen's tilt along x and y and its barrel rotation, in radians.
type Pose = ([f32; 2], f32);
/// The pen feed [`msg_hook`] writes, once [`start`] has made it.
static FEED: OnceLock<StylusFeed> = OnceLock::new();
/// The pen source [`msg_hook`] writes, once [`start`] has made it.
static FEED: OnceLock<PenSource> = OnceLock::new();
/// The canvas's pen feed, which [`msg_hook`] writes on the UI thread before winit handles each
/// message, so a press never waits for it.
pub fn start() -> StylusFeed {
FEED.get_or_init(StylusFeed::on_ui_thread).clone()
/// The canvas's pen source, which [`msg_hook`] writes before winit handles each message.
pub fn start() -> PenSource {
FEED.get_or_init(PenSource::default).clone()
}
/// winit's message hook (`EventLoopBuilderExtWindows::with_msg_hook`), which winit calls for each
/// message it takes from the thread's queue, before dispatching it: notes each pointer contact's id
/// and whether the barrel button was held, and writes the pen's pressure and end into the feed.
/// It never consumes the message.
/// message it takes from the thread's queue, before dispatching it: writes the pen's pressure, end
/// and barrel button into the source. It never consumes the message.
#[cfg(windows)]
#[allow(unsafe_code)]
pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
@@ -91,14 +86,7 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
let Some(msg) = (unsafe { msg.cast::<MSG>().as_ref() }) else {
return false;
};
if msg.message == WM_POINTERDOWN {
STROKES.with(|s| {
if let Ok(mut s) = s.try_borrow_mut() {
s.pointer_down(msg.wParam.0);
}
});
}
let Some(feed) = FEED.get() else {
let Some(pen) = FEED.get() else {
return false;
};
let read_pen = || {
@@ -113,7 +101,9 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
// SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message.
let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32);
if let Some(sample) = feed_update(msg.message, msg.wParam.0, read_pen, from_mouse) {
feed.set_sample(sample);
// The barrel goes first: the contact's press reads it with the sample.
pen.set_barrel(sample.is_some() && (msg.wParam.0 >> 16) & POINTER_MESSAGE_FLAG_SECONDBUTTON != 0);
pen.set(sample);
}
false
}
@@ -122,24 +112,26 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool {
/// reports: the pressure as winit gives it to a touch, 0 while it hovers, a full press for a pen
/// in contact that reports none; the eraser end while it is inverted or its eraser button is
/// pressed; and how it is held, `pose` ([`pen_pose`]).
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, pose: PenPose) -> PenSample {
fn pen_sample(pressure: u32, pen_mask: u32, pen_flags: u32, in_contact: bool, (tilt, rotation): Pose) -> PointerSample {
let pressure = match pressure {
1..=1024 if pen_mask & PEN_MASK_PRESSURE != 0 => pressure as f32 / 1024.0,
_ if in_contact => 1.0,
_ => 0.0,
};
PenSample { pressure, eraser: pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0, pose }
let mut sample = PointerSample::new(pressure);
sample.tilt = tilt;
sample.rotation = rotation;
sample.eraser = pen_flags & (PEN_FLAG_INVERTED | PEN_FLAG_ERASER) != 0;
sample
}
/// How a pen whose `POINTER_PEN_INFO` holds `pen_mask`, `tilt_x`, `tilt_y` and `rotation` is
/// held: the tilt when the pen reports it along either axis (0 along an axis it doesn't), the
/// rotation when it reports one, each kept within [`PenPose`]'s ranges. `POINTER_PEN_INFO` has no
/// field for an airbrush pen's finger wheel, so the pose has none.
fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> PenPose {
let along = |mask: u32, t: i32| if pen_mask & mask != 0 { t as f32 } else { 0.0 };
let tilt = (pen_mask & (PEN_MASK_TILT_X | PEN_MASK_TILT_Y) != 0).then(|| [along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)]);
let rotation = (pen_mask & PEN_MASK_ROTATION != 0).then_some(rotation as f32);
PenPose { tilt, rotation, wheel: None }.sanitized()
/// held, in radians: each tilt along an axis the pen reports (0 along one it doesn't) within ±90°,
/// and the rotation when it reports one (0 otherwise) within a turn.
fn pen_pose(pen_mask: u32, tilt_x: i32, tilt_y: i32, rotation: u32) -> Pose {
let along = |mask: u32, t: i32| if pen_mask & mask != 0 { (t as f32).clamp(-90.0, 90.0).to_radians() } else { 0.0 };
let turn = if pen_mask & PEN_MASK_ROTATION != 0 { ((rotation % 360) as f32).to_radians() } else { 0.0 };
([along(PEN_MASK_TILT_X, tilt_x), along(PEN_MASK_TILT_Y, tilt_y)], turn)
}
/// Whether a mouse message with this extra information (`GetMessageExtraInfo`) comes from a mouse,
@@ -148,16 +140,16 @@ fn is_mouse(extra_info: u32) -> bool {
extra_info & SIGNATURE_MASK != MI_WP_SIGNATURE
}
/// What the feed is set to for a message with this `wParam`: `Some(Some(sample))` for a pointer
/// What the source is set to for a message with this `wParam`: `Some(Some(sample))` for a pointer
/// message of a pen in range (`read_pen`), `Some(None)` for a pointer message of another pointer,
/// a pointer leaving detection range or the window, or a mouse message from a mouse
/// (`from_mouse`), and `None` to leave it as it is.
fn feed_update(
message: u32,
wparam: usize,
read_pen: impl FnOnce() -> Option<PenSample>,
read_pen: impl FnOnce() -> Option<PointerSample>,
from_mouse: impl FnOnce() -> bool,
) -> Option<Option<PenSample>> {
) -> Option<Option<PointerSample>> {
match message {
WM_POINTERENTER | WM_POINTERUPDATE | WM_POINTERDOWN | WM_POINTERUP if (wparam >> 16) & POINTER_MESSAGE_FLAG_INRANGE == 0 => Some(None),
WM_POINTERENTER | WM_POINTERUPDATE | WM_POINTERDOWN | WM_POINTERUP => Some(read_pen()),
@@ -167,255 +159,23 @@ fn feed_update(
}
}
/// Before egui reads a frame's input: the primary button of a contact that started with the
/// barrel button held becomes the secondary button.
pub fn raw_input_hook(raw: &mut egui::RawInput) {
STROKES.with(|s| {
if let Ok(mut s) = s.try_borrow_mut() {
s.rewrite(&mut raw.events);
}
});
}
/// The pen contacts that press the secondary button.
#[derive(Default)]
struct BarrelStrokes {
/// Each `WM_POINTERDOWN`'s pointer id and whether the barrel button was held, oldest first,
/// until the touch of that contact starts.
pending: Vec<(u64, bool)>,
/// The contact whose touch started with the barrel button held, until it ends, the same pointer
/// starts another contact, or another contact starts with the barrel button held.
right: Option<Right>,
}
/// A contact that started with the barrel button held.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Right {
id: TouchId,
/// Its secondary button is down: the press went to egui and the release has not.
down: bool,
}
impl BarrelStrokes {
/// A `WM_POINTERDOWN` with this `wParam`, whose low word is the pointer id and whose high word
/// holds the pointer flags.
fn pointer_down(&mut self, wparam: usize) {
if self.pending.len() >= MAX_PENDING {
self.pending.remove(0);
}
self.pending.push(((wparam & 0xffff) as u64, (wparam >> 16) & POINTER_MESSAGE_FLAG_SECONDBUTTON != 0));
}
/// Makes the primary button of the right contact the secondary one. egui-winit sends a touch's
/// pointer button with the touch event it comes from: the press after the touch's start and
/// the pointer's move to it, the release right after its end. A canceled contact, or one
/// whose end never came (Windows does not promise one), gets a secondary release of its own.
fn rewrite(&mut self, events: &mut Vec<Event>) {
let release = |pos: Pos2| Event::PointerButton { pos, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE };
let mut out = Vec::with_capacity(events.len() + 1);
// The button event that comes next for the right contact: `Some(true)` for its press,
// `Some(false)` for its release.
let mut next = None;
for mut event in events.drain(..) {
let mut after = None;
match &mut event {
Event::Touch { id, phase, pos, .. } => {
let (id, phase, pos) = (*id, *phase, *pos);
if phase == TouchPhase::Start {
// Each start decides afresh, from the oldest contact of its pointer still waiting.
let barrel = match self.pending.iter().position(|&(p, _)| p == id.0) {
Some(i) => self.pending.remove(i).1,
None => false,
};
if let Some(r) = self.right
&& (barrel || r.id == id)
{
if r.down {
out.push(release(pos));
}
self.right = None;
}
if barrel {
self.right = Some(Right { id, down: false });
}
}
next = None;
if let Some(r) = self.right.filter(|r| r.id == id) {
match phase {
TouchPhase::Start => next = Some(true),
TouchPhase::Move => {}
TouchPhase::End => {
self.right = None;
next = Some(false);
}
TouchPhase::Cancel => {
self.right = None;
if r.down {
after = Some(release(pos));
}
}
}
}
}
Event::PointerMoved(_) if next == Some(true) => {}
Event::PointerButton { button, pressed, .. } if next == Some(*pressed) && *button == PointerButton::Primary => {
*button = PointerButton::Secondary;
if let Some(r) = self.right.as_mut() {
r.down = *pressed;
}
next = None;
}
_ => next = None,
}
out.push(event);
out.extend(after);
}
*events = out;
}
}
#[cfg(test)]
mod tests {
use super::*;
use egui::{TouchDeviceId, pos2};
/// `POINTER_MESSAGE_FLAG_INRANGE`, `_INCONTACT` and `_FIRSTBUTTON` (`winuser.h`): a pen tip
/// touching down.
const TIP: usize = 0x0002 | 0x0004 | 0x0010;
/// `POINTER_MESSAGE_FLAG_INRANGE` and `_INCONTACT` with the barrel button.
const BARREL: usize = 0x0002 | 0x0004 | POINTER_MESSAGE_FLAG_SECONDBUTTON;
fn down(strokes: &mut BarrelStrokes, id: usize, flags: usize) {
strokes.pointer_down((flags << 16) | id);
}
/// The events egui reads after the hook.
fn rewrite(strokes: &mut BarrelStrokes, events: &[Event]) -> Vec<Event> {
let mut events = events.to_vec();
strokes.rewrite(&mut events);
events
}
fn touch(id: u64, phase: TouchPhase) -> Event {
Event::Touch { device_id: TouchDeviceId(1), id: TouchId(id), phase, pos: pos2(10.0, 20.0), force: Some(0.5) }
}
fn button(button: PointerButton, pressed: bool) -> Event {
Event::PointerButton { pos: pos2(10.0, 20.0), button, pressed, modifiers: Modifiers::NONE }
}
/// What egui-winit sends for the touch that drives the pointer.
fn start(id: u64) -> Vec<Event> {
vec![touch(id, TouchPhase::Start), Event::PointerMoved(pos2(10.0, 20.0)), button(PointerButton::Primary, true)]
}
fn end(id: u64) -> Vec<Event> {
vec![touch(id, TouchPhase::End), button(PointerButton::Primary, false), Event::PointerGone]
}
fn buttons(events: &[Event]) -> Vec<(PointerButton, bool)> {
events.iter().filter_map(|e| if let Event::PointerButton { button, pressed, .. } = e { Some((*button, *pressed)) } else { None }).collect()
}
const SECONDARY_DOWN: (PointerButton, bool) = (PointerButton::Secondary, true);
const SECONDARY_UP: (PointerButton, bool) = (PointerButton::Secondary, false);
const PRIMARY_DOWN: (PointerButton, bool) = (PointerButton::Primary, true);
const PRIMARY_UP: (PointerButton, bool) = (PointerButton::Primary, false);
#[test]
fn a_pen_contact_with_the_barrel_button_presses_the_secondary_button() {
let mut strokes = BarrelStrokes::default();
down(&mut strokes, 7, BARREL);
assert_eq!(buttons(&rewrite(&mut strokes, &start(7))), [SECONDARY_DOWN]);
let moved = [touch(7, TouchPhase::Move), Event::PointerMoved(pos2(15.0, 25.0))];
assert_eq!(rewrite(&mut strokes, &moved), moved);
assert_eq!(buttons(&rewrite(&mut strokes, &end(7))), [SECONDARY_UP]);
assert_eq!(strokes.right, None, "the next contact starts afresh");
assert!(strokes.pending.is_empty());
}
#[test]
fn a_pen_contact_with_the_tip_alone_keeps_the_primary_button() {
let mut strokes = BarrelStrokes::default();
down(&mut strokes, 7, TIP);
let events = [start(7), end(7)].concat();
assert_eq!(rewrite(&mut strokes, &events), events);
}
#[test]
fn contacts_of_a_pen_within_one_frame_keep_their_order() {
// A tap with the barrel button held, then one with the tip alone, before the next frame.
let mut strokes = BarrelStrokes::default();
down(&mut strokes, 7, BARREL);
down(&mut strokes, 7, TIP);
let events = rewrite(&mut strokes, &[start(7), end(7), start(7), end(7)].concat());
assert_eq!(buttons(&events), [SECONDARY_DOWN, SECONDARY_UP, PRIMARY_DOWN, PRIMARY_UP]);
}
#[test]
fn a_mouse_button_right_after_a_barrel_contact_keeps_its_button() {
let mut strokes = BarrelStrokes::default();
down(&mut strokes, 7, BARREL);
let events = [start(7), vec![button(PointerButton::Primary, true)], end(7), vec![button(PointerButton::Primary, false)]].concat();
assert_eq!(buttons(&rewrite(&mut strokes, &events)), [SECONDARY_DOWN, PRIMARY_DOWN, SECONDARY_UP, PRIMARY_UP]);
}
#[test]
fn other_touches_and_the_mouse_keep_the_primary_button_during_a_barrel_contact() {
let mut strokes = BarrelStrokes::default();
down(&mut strokes, 7, BARREL);
down(&mut strokes, 9, TIP);
let events = [start(7), start(9), vec![button(PointerButton::Primary, true)], end(9)].concat();
assert_eq!(buttons(&rewrite(&mut strokes, &events)), [SECONDARY_DOWN, PRIMARY_DOWN, PRIMARY_DOWN, PRIMARY_UP]);
assert_eq!(strokes.right, Some(Right { id: TouchId(7), down: true }), "the barrel contact goes on");
}
#[test]
fn a_contact_after_a_lost_end_releases_the_secondary_button_first() {
let mut strokes = BarrelStrokes::default();
down(&mut strokes, 7, BARREL);
rewrite(&mut strokes, &start(7));
// No end arrives for that contact; the pen touches down again with the tip alone.
down(&mut strokes, 7, TIP);
let events = rewrite(&mut strokes, &[start(7), end(7)].concat());
assert_eq!(buttons(&events), [SECONDARY_UP, PRIMARY_DOWN, PRIMARY_UP]);
assert_eq!(strokes.right, None);
// Another pen's barrel contact takes over from one whose end was lost.
down(&mut strokes, 7, BARREL);
rewrite(&mut strokes, &start(7));
down(&mut strokes, 8, BARREL);
let events = rewrite(&mut strokes, &[start(8), end(8)].concat());
assert_eq!(buttons(&events), [SECONDARY_UP, SECONDARY_DOWN, SECONDARY_UP]);
}
#[test]
fn a_canceled_barrel_contact_releases_the_secondary_button() {
let mut strokes = BarrelStrokes::default();
down(&mut strokes, 7, BARREL);
let events = rewrite(&mut strokes, &[start(7), vec![touch(7, TouchPhase::Cancel), Event::PointerGone]].concat());
assert_eq!(buttons(&events), [SECONDARY_DOWN, SECONDARY_UP]);
assert_eq!(strokes.right, None);
}
#[test]
fn a_barrel_contact_that_never_pressed_releases_nothing() {
// A finger drives the pointer, so egui-winit sends no button for the pen.
let mut strokes = BarrelStrokes::default();
down(&mut strokes, 7, BARREL);
let events = [vec![touch(7, TouchPhase::Start)], vec![touch(7, TouchPhase::Cancel)]].concat();
assert_eq!(rewrite(&mut strokes, &events), events);
down(&mut strokes, 7, BARREL);
down(&mut strokes, 7, TIP);
let events = [vec![touch(7, TouchPhase::Start)], start(7)].concat();
assert_eq!(buttons(&rewrite(&mut strokes, &events)), [PRIMARY_DOWN]);
}
/// `PEN_FLAG_BARREL` (`winuser.h`).
const PEN_FLAG_BARREL: u32 = 0x0001;
const UPRIGHT: Pose = ([0.0, 0.0], 0.0);
fn eraser_sample(pressure: f32) -> PointerSample {
let mut sample = PointerSample::new(pressure);
sample.eraser = true;
sample
}
#[test]
fn an_inverted_pen_or_its_eraser_button_is_the_eraser_end() {
let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, PenPose::default()).eraser;
let eraser = |flags| pen_sample(512, PEN_MASK_PRESSURE, flags, true, UPRIGHT).eraser;
assert!(!eraser(0), "the tip");
assert!(!eraser(PEN_FLAG_BARREL), "the barrel button");
assert!(eraser(PEN_FLAG_INVERTED), "turned over");
@@ -427,29 +187,26 @@ mod tests {
#[test]
fn a_pens_tilt_and_rotation_come_where_it_reports_them() {
let all = PEN_MASK_TILT_X | PEN_MASK_TILT_Y | PEN_MASK_ROTATION;
assert_eq!(pen_pose(all, 30, -45, 90), PenPose { tilt: Some([30.0, -45.0]), rotation: Some(90.0), wheel: None });
assert_eq!(pen_pose(PEN_MASK_PRESSURE, 30, -45, 90), PenPose::default(), "a pen that reports neither");
assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90), PenPose { tilt: Some([30.0, 0.0]), ..PenPose::default() }, "one axis");
assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), PenPose { rotation: Some(359.0), ..PenPose::default() }, "a 6D Art Pen's barrel");
let wild = pen_pose(all, 400, i32::MIN, 720);
assert_eq!(wild, PenPose { tilt: Some([90.0, -90.0]), rotation: Some(0.0), wheel: None }, "kept within the ranges");
let deg = f32::to_radians;
assert_eq!(pen_pose(all, 30, -45, 90), ([deg(30.0), deg(-45.0)], deg(90.0)));
assert_eq!(pen_pose(PEN_MASK_PRESSURE, 30, -45, 90), UPRIGHT, "a pen that reports neither");
assert_eq!(pen_pose(PEN_MASK_TILT_X, 30, -45, 90), ([deg(30.0), 0.0], 0.0), "one axis");
assert_eq!(pen_pose(PEN_MASK_ROTATION, 0, 0, 359), ([0.0, 0.0], deg(359.0)), "a 6D Art Pen's barrel");
assert_eq!(pen_pose(all, 400, i32::MIN, 720), ([deg(90.0), deg(-90.0)], 0.0), "kept within the ranges");
let pose = pen_pose(all, 10, 20, 180);
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose).pose, pose);
let sample = pen_sample(512, PEN_MASK_PRESSURE | all, 0, true, pose);
assert_eq!((sample.tilt, sample.rotation), pose);
}
#[test]
fn a_pens_pressure_is_the_one_winit_gives_its_touch() {
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 0.5);
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 1.0);
assert_eq!(
pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, PenPose::default()),
PenSample { pressure: 0.0, eraser: true, pose: PenPose::default() },
"hovering"
);
assert_eq!(pen_sample(0, 0, 0, true, PenPose::default()).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
assert_eq!(pen_sample(300, 0, 0, true, PenPose::default()).pressure, 1.0, "a pressure without the pressure mask is not one");
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, PenPose::default()).pressure, 1.0, "as winit, which gives no force for 0");
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, PenPose::default()).pressure, 0.0);
assert_eq!(pen_sample(512, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 0.5);
assert_eq!(pen_sample(1024, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 1.0);
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, PEN_FLAG_INVERTED, false, UPRIGHT), eraser_sample(0.0), "hovering");
assert_eq!(pen_sample(0, 0, 0, true, UPRIGHT).pressure, 1.0, "a pen in contact that reports no pressure presses fully");
assert_eq!(pen_sample(300, 0, 0, true, UPRIGHT).pressure, 1.0, "a pressure without the pressure mask is not one");
assert_eq!(pen_sample(0, PEN_MASK_PRESSURE, 0, true, UPRIGHT).pressure, 1.0, "as winit, which gives no force for 0");
assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, UPRIGHT).pressure, 0.0);
}
#[test]
@@ -462,11 +219,11 @@ mod tests {
#[test]
fn pen_messages_set_the_feed_and_other_pointers_clear_it() {
let pen = PenSample { pressure: 0.0, eraser: true, pose: PenPose::default() };
let pen = eraser_sample(0.0);
// `POINTER_MESSAGE_FLAG_INRANGE` in the high word of `wParam`, pointer 7 in the low word.
let in_range = (POINTER_MESSAGE_FLAG_INRANGE << 16) | 7;
let no_mouse = || -> bool { panic!("a pointer message is not a mouse message") };
let no_pen = || -> Option<PenSample> { panic!("no pen to read") };
let no_pen = || -> Option<PointerSample> { panic!("no pen to read") };
for m in [WM_POINTERENTER, WM_POINTERUPDATE, WM_POINTERDOWN, WM_POINTERUP] {
assert_eq!(feed_update(m, in_range, || Some(pen), no_mouse), Some(Some(pen)), "{m:#x}");
assert_eq!(feed_update(m, in_range, || None, no_mouse), Some(None), "a touch: {m:#x}");
@@ -479,14 +236,4 @@ mod tests {
// WM_KEYDOWN.
assert_eq!(feed_update(0x0100, 0, no_pen, || -> bool { panic!("not a mouse message") }), None);
}
#[test]
fn contacts_whose_touch_never_arrives_are_bounded() {
let mut strokes = BarrelStrokes::default();
for id in 0..40 {
down(&mut strokes, id, BARREL);
}
assert_eq!(strokes.pending.len(), MAX_PENDING);
assert_eq!(strokes.pending.last(), Some(&(39, true)));
}
}
+50 -428
View File
@@ -1,241 +1,27 @@
//! Pen pressure, tilt and barrel rotation that the host reads from the system itself (#764).
//! Which end of the pen is down (#764).
//!
//! winit 0.30 hands a pen's pressure to egui only on Windows, as the force of a touch event; the
//! web build makes the same touch events from the browser's Pointer Events. No platform gets the
//! pen's tilt or rotation through winit. On Linux under X11 (XWayland included), winit reports a
//! pen as a mouse, so the desktop app reads the pressure, tilt and rotation from XInput2 on a
//! connection of its own and writes them into a [`StylusFeed`] ([`crate::Services::stylus`]). On
//! macOS, where winit reports none of them either, the app reads each event's pressure, tilt and
//! rotation from AppKit before the window handles it, and also keeps them for that event's pointer
//! move ([`StylusFeed::set_move`]), so the moves of a fast stroke each get their own. On Windows,
//! where winit drops which end of the pen is down, the app reads the pressure and the end from
//! each pointer message of a pen before winit handles it. The canvas uses the pressure when a
//! frame's events carry no touch force, and the tilt and rotation for each press, drag and release.
//! An airbrush pen's finger wheel comes with the tilt and rotation ([`PenPose::wheel`]) where the
//! host reads it: from XInput2 on X11 and from AppKit on macOS. The app does not read it on
//! Windows, whose pointer messages have no field for it, or in the web build.
//! The hosts read a pen's pressure, tilt, rotation and end from the system and write them into the
//! framework's [`PenSource`]: from XInput2 on X11 (XWayland included), from AppKit on macOS, from
//! each pointer message of a pen on Windows, and from Pointer Events in the web build. The tool
//! host reads the pressure, tilt and rotation from the same source.
//!
//! The feed also says which end of the pen moved. Turning the pen to its eraser end selects the
//! The source also says which end of the pen moved. Turning the pen to its eraser end selects the
//! Eraser tool, and turning it back to the tip selects the tool used before
//! ([`sync_eraser_tool`]), as the reference app's help describes under "Erase parts of a path
//! using a stylus pen":
//! <https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/erase-parts-of-a-path.html>
//!
//! The web build writes the pen's end into a feed as well. Pointer Events report the eraser end
//! only as a press of the pen's eraser button (`button` 5), so in a browser the end changes when
//! the pen presses: a press of the eraser end selects the Eraser before that press, and a press of
//! the tip selects the tool used before.
//! The web build reports the eraser end only as a press of the pen's eraser button (`button` 5), so
//! in a browser the end changes when the pen presses: a press of the eraser end selects the Eraser
//! before that press, and a press of the tip selects the tool used before.
use std::collections::VecDeque;
use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock};
use std::time::Duration;
pub use vectorcraft_tools::PenPose;
use craft_ui::runtime::pen::PenSource;
use crate::VectorcraftApp;
/// The tool the pen's eraser end selects.
const ERASER: &str = "eraser";
/// How long a press waits for the touch of a pen that hovers ([`StylusFeed::press`]).
const PRESS_WAIT: Duration = Duration::from_millis(5);
/// The pressures of pointer moves kept for the UI ([`StylusFeed::set_move`]); a frame replays 64
/// moves at most.
const MAX_MOVES: usize = 256;
/// What a pen reports as it moves.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct PenSample {
/// 0..1; 0 while the pen hovers.
pub pressure: f32,
/// The pen is turned to its eraser end.
pub eraser: bool,
/// The tilt, rotation and finger wheel the pen read, if any.
pub pose: PenPose,
}
/// What the feed holds.
#[derive(Clone, Debug, Default)]
struct Pen {
/// The pressure of the pen when a pen was the last pointer to move.
latest: Option<f32>,
/// The pen that moved last is turned to its eraser end.
eraser: bool,
/// The highest pressure set since the UI last read the feed, counted from the latest sample
/// whose pressure rose above 0.
peak: Option<f32>,
/// The last pressure above 0 set since a pen was the last pointer to move, with the same end
/// (0 when that end has not touched).
touched: f32,
/// The pressure, tilt and rotation of each pointer move set since the UI last took them,
/// oldest first.
moves: VecDeque<(f32, PenPose)>,
/// The pen's latest tilt and rotation (none when a mouse moved last).
pose: PenPose,
}
impl Pen {
/// A pen hovers, and no touch has been set since the UI last read the feed.
fn hovering(&self) -> bool {
self.latest == Some(0.0) && self.peak.is_none()
}
}
#[derive(Default)]
struct Shared {
pen: Mutex<Pen>,
/// Wake the canvas for a pen that turns without a new window pointer event.
repaint: OnceLock<egui::Context>,
/// Signaled on every [`StylusFeed::set_sample`] ([`StylusFeed::set`] included).
set: Condvar,
/// Written on the UI thread itself ([`StylusFeed::on_ui_thread`]): a press never waits.
ui_thread: bool,
}
/// The pen pressure, pen end, tilt and rotation the host last read, written from any thread and
/// read on the UI thread. Cheap to clone; the clones share the value.
#[derive(Clone, Default)]
pub struct StylusFeed(Arc<Shared>);
impl StylusFeed {
/// A feed the host writes on the UI thread, before the UI handles the event it read (macOS):
/// a press has its touch already, and waiting for one would only stall the thread.
pub fn on_ui_thread() -> Self {
Self(Arc::new(Shared { ui_thread: true, ..Shared::default() }))
}
fn lock(&self) -> MutexGuard<'_, Pen> {
self.0.pen.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub(crate) fn bind_repaint(&self, ctx: &egui::Context) {
self.0.repaint.get_or_init(|| ctx.clone());
}
/// A pen turned to its tip moved with `pressure`, or `None`: another pointer moved
/// ([`Self::set_sample`]).
pub fn set(&self, pressure: Option<f32>) {
self.set_sample(pressure.map(|pressure| PenSample { pressure, ..PenSample::default() }));
}
/// A pen moved with `sample`'s pressure (0..1; 0 while it hovers), end, tilt and rotation, or
/// `None`: another pointer, such as a mouse, moved. A pressure outside 0..1 is clamped, and one
/// that is not a number is a mouse's, 1. The tilt and rotation are kept within their ranges by
/// [`PenPose::sanitized`]. A sample of the other end starts afresh: the touches of the end
/// before it don't count for its presses.
pub fn set_sample(&self, sample: Option<PenSample>) {
let pressure = sample.map(|s| if s.pressure.is_finite() { s.pressure.clamp(0.0, 1.0) } else { 1.0 });
let eraser = sample.is_some_and(|s| s.eraser);
let mut pen = self.lock();
let before_pose = pen.pose;
if eraser != pen.eraser {
*pen = Pen::default();
}
pen.eraser = eraser;
pen.pose = sample.map_or(PenPose::default(), |s| s.pose.sanitized());
match pressure {
Some(p) if p > 0.0 => {
let touching = pen.latest.is_some_and(|l| l > 0.0);
pen.peak = Some(if touching { pen.peak.map_or(p, |q| q.max(p)) } else { p });
pen.touched = p;
}
Some(_) => {}
None => {
pen.peak = None;
pen.touched = 0.0;
pen.moves.clear();
}
}
pen.latest = pressure;
let pose_changed = pen.pose != before_pose;
drop(pen);
self.0.set.notify_all();
if pose_changed && let Some(ctx) = self.0.repaint.get() {
ctx.request_repaint();
}
}
/// Like [`Self::set_sample`], for a pen sample that comes with one pointer move of the window,
/// read before the window handles the move (macOS): its pressure, tilt and rotation are also
/// kept for that move ([`Self::take_moves`]).
pub fn set_move(&self, sample: PenSample) {
self.set_sample(Some(sample));
let mut pen = self.lock();
if pen.moves.len() >= MAX_MOVES {
pen.moves.pop_front();
}
let pressure = pen.latest.unwrap_or(1.0);
let pose = pen.pose;
pen.moves.push_back((pressure, pose));
}
/// The pressures, tilts and rotations of the pointer moves set with [`Self::set_move`] since
/// the last call, oldest first (256 at most): the last one is the latest move's.
pub fn take_moves(&self) -> Vec<(f32, PenPose)> {
self.lock().moves.drain(..).collect()
}
/// The pressure of a press the UI holds (a drag and its release) when a pen was the last
/// pointer to move, otherwise `None`: the latest pressure, or, when the pen has lifted (0), the
/// last pressure it touched with. The lift can reach the feed before the UI handles the last
/// moves and the release of the press, which then keep the pen's pressure, not the lift's 0.
/// The pressures set so far count as read for [`Self::press`].
pub fn held(&self) -> Option<f32> {
let mut pen = self.lock();
pen.peak = None;
let touched = pen.touched;
pen.latest.map(|l| if l > 0.0 { l } else { touched })
}
/// The pressure of a press when a pen was the last pointer to move, otherwise `None`: the
/// highest pressure set since the last read, counted from the latest touch, or else the latest
/// pressure. A quick tap can touch and lift before the frame that handles its press, which
/// then gets the tap's pressure, not the lift's 0. The host's reader can also set the touch
/// just after the UI handles the press: when the pen still hovers, the press waits up to 5 ms
/// for it, and gets 0 if none comes.
pub fn press(&self) -> Option<f32> {
self.press_within(PRESS_WAIT)
}
/// The tilt (in screen axes) and rotation of the pen when a pen was the last pointer to move
/// and it read either, otherwise `None`.
pub fn pose(&self) -> Option<PenPose> {
let pen = self.lock();
pen.latest.map(|_| pen.pose).filter(|q| *q != PenPose::default())
}
fn press_within(&self, wait: Duration) -> Option<f32> {
let mut pen = self.lock();
if pen.hovering() && !self.0.ui_thread {
pen = self.wait_for_touch(pen, wait);
}
let peak = pen.peak.take();
pen.latest.map(|l| peak.unwrap_or(l))
}
/// Whether the pen is turned to its eraser end when a pen was the last pointer to move,
/// otherwise `None`.
pub fn eraser(&self) -> Option<bool> {
let pen = self.lock();
pen.latest.map(|_| pen.eraser)
}
#[cfg(not(target_arch = "wasm32"))]
fn wait_for_touch<'a>(&'a self, pen: MutexGuard<'a, Pen>, wait: Duration) -> MutexGuard<'a, Pen> {
match self.0.set.wait_timeout_while(pen, wait, |p| p.hovering()) {
Ok((pen, _)) => pen,
Err(e) => e.into_inner().0,
}
}
/// The browser's main thread can't wait, and the web build writes its feed on that thread.
#[cfg(target_arch = "wasm32")]
fn wait_for_touch<'a>(&'a self, pen: MutexGuard<'a, Pen>, _wait: Duration) -> MutexGuard<'a, Pen> {
pen
}
}
/// The end of the pen the canvas saw last, and the tool the eraser end stands in for
/// ([`sync_eraser_tool`]).
#[derive(Clone, Debug, Default)]
@@ -255,8 +41,8 @@ impl PenEnd {
/// The end the pen turned to since the last call (`Some(true)`: the eraser end), or `None`
/// when it has not turned, or when another pointer moved last. Each turn is reported once.
fn take_flip(&mut self, feed: Option<&StylusFeed>) -> Option<bool> {
let eraser = feed?.eraser()?;
fn take_flip(&mut self, pen: Option<&PenSource>) -> Option<bool> {
let eraser = pen?.current()?.eraser;
let flipped = self.end.map_or(eraser, |e| e != eraser);
self.end = Some(eraser);
flipped.then_some(eraser)
@@ -271,7 +57,7 @@ impl PenEnd {
/// a turn during a press takes effect after the release, and a turn over another window takes
/// effect when the pointer comes in.
pub(crate) fn sync_eraser_tool(app: &mut VectorcraftApp) -> bool {
let Some(eraser) = app.pen_end.take_flip(app.services.stylus.as_ref()) else { return false };
let Some(eraser) = app.pen_end.take_flip(app.services.pen.as_ref()) else { return false };
let tool = app.session.tool_id();
if eraser {
if tool == ERASER {
@@ -296,213 +82,49 @@ pub(crate) fn sync_eraser_tool(app: &mut VectorcraftApp) -> bool {
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
// PLAN: needs the `craft` facade dependency in crates/ui-egui/Cargo.toml (not in this set's files).
use craft::behavior::PointerSample;
use vectorcraft_engine::Session;
#[test]
fn changing_a_still_pens_pose_wakes_the_canvas() {
let feed = StylusFeed::default();
let ctx = egui::Context::default();
let repaints = Arc::new(AtomicUsize::new(0));
let count = repaints.clone();
ctx.set_repaint_observer(move |_| {
count.fetch_add(1, Ordering::Relaxed);
});
feed.bind_repaint(&ctx);
let pose = PenPose { rotation: Some(0.0), ..Default::default() };
let sample = PenSample { pressure: 0.0, pose, ..Default::default() };
let writer = feed.clone();
std::thread::spawn(move || writer.set_sample(Some(sample))).join().unwrap();
assert_eq!(repaints.load(Ordering::Relaxed), 1);
feed.set_sample(Some(sample));
assert_eq!(repaints.load(Ordering::Relaxed), 1, "an unchanged pose needs no new frame");
feed.set_sample(Some(PenSample { pose: PenPose { rotation: Some(90.0), ..pose }, ..sample }));
assert_eq!(repaints.load(Ordering::Relaxed), 2);
feed.set_sample(None);
assert_eq!(repaints.load(Ordering::Relaxed), 3, "mouse input clears the tip");
fn reading(eraser: bool) -> Option<PointerSample> {
let mut sample = PointerSample::new(0.0);
sample.eraser = eraser;
Some(sample)
}
#[test]
fn the_feed_keeps_the_last_pressure_within_0_to_1() {
let feed = StylusFeed::default();
assert_eq!(feed.held(), None, "no pen until one moves");
let shared = feed.clone();
shared.set(Some(0.25));
assert_eq!(feed.held(), Some(0.25), "the clones share the value");
feed.set(Some(1.5));
assert_eq!(feed.held(), Some(1.0));
feed.set(Some(f32::NAN));
assert_eq!(feed.held(), Some(1.0), "a pressure that is not a number is a mouse's");
feed.set(None);
feed.set(Some(-0.5));
assert_eq!(feed.press_within(Duration::ZERO), Some(0.0));
feed.set(None);
assert_eq!((feed.held(), feed.press()), (None, None), "a mouse moved");
}
fn turning_the_pen_swaps_to_the_eraser_and_back_after_the_press() {
let pen = PenSource::default();
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.services.pen = Some(pen.clone());
app.session.execute("file.new", &serde_json::json!({"width": 800, "height": 600})).unwrap();
app.select_tool("paintbrush");
/// The tilt and rotation a pen read, kept within their ranges, until a mouse moves.
#[test]
fn the_feed_keeps_the_pens_tilt_and_rotation_within_their_ranges() {
let feed = StylusFeed::default();
assert_eq!(feed.pose(), None);
let pen = |pose| Some(PenSample { pressure: 0.4, pose, ..PenSample::default() });
let leaning = PenPose { tilt: Some([-120.0, 30.0]), rotation: Some(-90.0), wheel: None };
feed.set_sample(pen(leaning));
assert_eq!(feed.pose(), Some(PenPose { tilt: Some([-90.0, 30.0]), rotation: Some(270.0), wheel: None }));
assert_eq!(feed.held(), Some(0.4), "the pressure as before");
// Not a number: left out. A tiny negative rotation is 0, not 360.
feed.set_sample(pen(PenPose { tilt: Some([f32::NAN, 0.0]), rotation: Some(-1e-9), wheel: None }));
assert_eq!(feed.pose(), Some(PenPose { rotation: Some(0.0), ..PenPose::default() }));
feed.set_sample(pen(PenPose { rotation: Some(f32::INFINITY), wheel: Some(f32::NAN), ..PenPose::default() }));
assert_eq!(feed.pose(), None, "a pen that reads none of them");
assert!(PenPose { rotation: Some(725.0), ..Default::default() }.sanitized().rotation == Some(5.0));
// An airbrush pen's finger wheel, clamped to 0..1.
feed.set_sample(pen(PenPose { wheel: Some(1.25), ..PenPose::default() }));
assert_eq!(feed.pose(), Some(PenPose { wheel: Some(1.0), ..PenPose::default() }));
// The eraser end reads them too.
feed.set_sample(Some(PenSample { pressure: 0.4, eraser: true, pose: leaning }));
assert_eq!((feed.eraser(), feed.pose()), (Some(true), Some(PenPose { tilt: Some([-90.0, 30.0]), rotation: Some(270.0), wheel: None })));
// A pen that reads no tilt (`set`), or a mouse: none.
feed.set_sample(pen(leaning));
feed.set(Some(0.5));
assert_eq!(feed.pose(), None);
feed.set_sample(pen(leaning));
feed.set_sample(None);
assert_eq!((feed.pose(), feed.held()), (None, None));
}
pen.set(reading(false));
assert!(!sync_eraser_tool(&mut app), "the tip hovers");
pen.set(reading(true));
assert!(sync_eraser_tool(&mut app));
assert_eq!(app.session.tool_id(), ERASER);
assert!(!sync_eraser_tool(&mut app), "a turn acts once");
pen.set(reading(false));
assert!(sync_eraser_tool(&mut app));
assert_eq!(app.session.tool_id(), "paintbrush", "the tip brings back the tool before");
#[test]
fn the_feed_keeps_the_eraser_end() {
let feed = StylusFeed::default();
assert_eq!(feed.eraser(), None, "no pen until one moves");
feed.set_sample(Some(PenSample { pressure: 1.5, eraser: true, ..PenSample::default() }));
assert_eq!((feed.eraser(), feed.held()), (Some(true), Some(1.0)), "clamped, and the eraser end kept");
feed.set_sample(Some(PenSample { pressure: f32::NAN, eraser: true, ..PenSample::default() }));
assert_eq!((feed.eraser(), feed.held()), (Some(true), Some(1.0)));
feed.set(Some(0.25));
assert_eq!((feed.eraser(), feed.held()), (Some(false), Some(0.25)), "the tip");
feed.set_sample(Some(PenSample { pressure: 0.0, eraser: true, ..PenSample::default() }));
assert_eq!(feed.eraser(), Some(true), "the eraser end hovering");
feed.set_sample(None);
assert_eq!(feed.eraser(), None, "a mouse moved");
}
// An Eraser chosen before the eraser end came stays when the tip comes back.
app.select_tool(ERASER);
pen.set(reading(true));
assert!(!sync_eraser_tool(&mut app));
pen.set(reading(false));
assert!(!sync_eraser_tool(&mut app));
assert_eq!(app.session.tool_id(), ERASER);
#[test]
fn the_feed_keeps_the_pressure_of_each_move() {
let feed = StylusFeed::default();
let leaning = PenPose { tilt: Some([20.0, -10.0]), rotation: Some(400.0), wheel: Some(0.75) };
for (p, pose) in [(0.2, PenPose::default()), (1.5, leaning), (0.4, PenPose::default())] {
feed.set_move(PenSample { pressure: p, pose, ..PenSample::default() });
}
feed.set(Some(0.9));
let turned = PenPose { rotation: Some(40.0), ..leaning };
let unread = PenPose::default();
assert_eq!(
feed.take_moves(),
[(0.2, unread), (1.0, turned), (0.4, unread)],
"clamped, each move with its own pose; a sample without a move keeps none"
);
assert_eq!((feed.take_moves(), feed.held()), (vec![], Some(0.9)), "taken once");
for _ in 0..MAX_MOVES + 10 {
feed.set_move(PenSample { pressure: 0.5, ..PenSample::default() });
}
assert_eq!(feed.take_moves().len(), MAX_MOVES, "bounded");
feed.set_move(PenSample { pressure: 0.5, ..PenSample::default() });
feed.set(None);
assert!(feed.take_moves().is_empty(), "a mouse moved");
}
#[test]
fn a_held_press_keeps_the_last_touch_when_the_lift_comes_first() {
let feed = StylusFeed::default();
feed.set(Some(0.0));
assert_eq!(feed.held(), Some(0.0), "a pen that has not touched");
// The pen moves and lifts before the UI handles the last move and the release.
for p in [0.5, 0.6, 0.0] {
feed.set(Some(p));
}
assert_eq!(feed.held(), Some(0.6));
feed.set(Some(0.3));
assert_eq!(feed.held(), Some(0.3), "a touch again: its own pressure");
feed.set(None);
assert_eq!(feed.held(), None, "a mouse moved");
feed.set(Some(0.0));
assert_eq!(feed.held(), Some(0.0), "the pen's touch before the mouse doesn't count");
}
#[test]
fn a_turned_pen_presses_without_the_touches_of_the_other_end() {
let feed = StylusFeed::default();
// The tip touches and lifts where the UI holds no press, so the UI does not read the feed.
for p in [0.0, 0.8, 0.0] {
feed.set(Some(p));
}
feed.set_sample(Some(PenSample { pressure: 0.0, eraser: true, ..PenSample::default() }));
assert_eq!(feed.held(), Some(0.0), "the eraser end has not touched");
assert_eq!(feed.press_within(Duration::ZERO), Some(0.0), "nor pressed");
feed.set_sample(Some(PenSample { pressure: 0.4, eraser: true, ..PenSample::default() }));
feed.set_sample(Some(PenSample { pressure: 0.0, eraser: true, ..PenSample::default() }));
feed.set(Some(0.0));
assert_eq!((feed.held(), feed.press_within(Duration::ZERO)), (Some(0.0), Some(0.0)), "back to the tip");
}
#[test]
fn a_press_takes_the_highest_pressure_since_the_last_read() {
let feed = StylusFeed::default();
feed.set(Some(0.0));
assert_eq!(feed.press(), Some(0.0), "a hovering pen");
// A tap: it touches, presses harder, and lifts before the frame that handles the press.
for p in [0.4, 0.7, 0.3, 0.0] {
feed.set(Some(p));
}
assert_eq!(feed.press(), Some(0.7));
assert_eq!(feed.press(), Some(0.0), "the press read the tap: the latest pressure");
// A new touch counts from its own pressure, not the touch before it.
for p in [0.9, 0.0, 0.2, 0.5, 0.3] {
feed.set(Some(p));
}
assert_eq!(feed.press(), Some(0.5));
// Pressures the UI has read do not count for the next press.
feed.set(Some(0.8));
assert_eq!(feed.held(), Some(0.8));
feed.set(Some(0.4));
assert_eq!(feed.press(), Some(0.4));
feed.set(None);
assert_eq!(feed.press(), None, "a mouse presses with no pen pressure");
}
#[test]
fn a_press_waits_for_the_touch_of_a_hovering_pen() {
let feed = StylusFeed::default();
feed.set(Some(0.0));
let reader = feed.clone();
let late = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(20));
reader.set(Some(0.6));
});
assert_eq!(feed.press_within(Duration::from_secs(10)), Some(0.6), "the touch set while the press waited");
late.join().unwrap();
// No touch comes: the hover's 0 once the wait ends.
feed.set(Some(0.0));
let start = std::time::Instant::now();
assert_eq!(feed.press_within(Duration::from_millis(30)), Some(0.0));
assert!(start.elapsed() >= Duration::from_millis(30));
// A pen that touched, or a mouse, does not wait.
feed.set(Some(0.3));
let start = std::time::Instant::now();
assert_eq!(feed.press_within(Duration::from_secs(10)), Some(0.3));
feed.set(None);
assert_eq!(feed.press_within(Duration::from_secs(10)), None);
assert!(start.elapsed() < Duration::from_secs(5));
}
/// A feed written on the UI thread (macOS) has nothing to wait for: a hovering pen's press
/// gets its 0 at once rather than stalling the thread.
#[test]
fn a_feed_written_on_the_ui_thread_never_waits() {
let feed = StylusFeed::on_ui_thread();
feed.set(Some(0.0));
let start = std::time::Instant::now();
assert_eq!(feed.press_within(Duration::from_secs(10)), Some(0.0));
assert!(start.elapsed() < Duration::from_secs(5));
// A tool chosen while the eraser end stands in cancels the return.
app.select_tool("paintbrush");
pen.set(reading(true));
sync_eraser_tool(&mut app);
app.select_tool("rectangle");
pen.set(reading(false));
assert!(!sync_eraser_tool(&mut app));
assert_eq!(app.session.tool_id(), "rectangle");
}
}