use rand::Rng;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PointerDevice {
#[default]
Mouse,
Touch,
Stylus,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PointerProperties {
pub pointer_type: &'static str,
pub hover_pressure: f64,
pub active_pressure_range: (f64, f64),
pub has_tilt: bool,
pub has_twist: bool,
pub twist_range_deg: (u32, u32),
}
impl PointerDevice {
#[must_use]
pub fn properties(&self) -> PointerProperties {
match self {
PointerDevice::Mouse => PointerProperties {
pointer_type: "mouse",
hover_pressure: 0.0,
active_pressure_range: (0.5, 0.5),
has_tilt: false,
has_twist: false,
twist_range_deg: (0, 0),
},
PointerDevice::Touch => PointerProperties {
pointer_type: "touch",
hover_pressure: 0.0,
active_pressure_range: (0.2, 1.0),
has_tilt: false,
has_twist: false,
twist_range_deg: (0, 0),
},
PointerDevice::Stylus => PointerProperties {
pointer_type: "pen",
hover_pressure: 0.0,
active_pressure_range: (0.1, 1.0),
has_tilt: true,
has_twist: true,
twist_range_deg: (0, 359),
},
}
}
#[must_use]
pub fn sample_active_pressure<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 {
let (lo, hi) = self.properties().active_pressure_range;
rng.gen_range(lo..=hi)
}
#[must_use]
pub fn sample_tilt<R: Rng + ?Sized>(&self, rng: &mut R) -> (i32, i32) {
if self == &PointerDevice::Stylus {
(rng.gen_range(-60..=60), rng.gen_range(-60..=60))
} else {
(0, 0)
}
}
#[must_use]
pub fn sample_twist<R: Rng + ?Sized>(&self, rng: &mut R) -> u32 {
if self == &PointerDevice::Stylus {
rng.gen_range(0..=359)
} else {
0
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use rand::rngs::StdRng;
use rand::SeedableRng;
#[test]
fn mouse_has_no_tilt_or_twist() {
let p = PointerDevice::Mouse.properties();
assert!(!p.has_tilt);
assert!(!p.has_twist);
assert_eq!(p.pointer_type, "mouse");
}
#[test]
fn mouse_hover_pressure_is_zero() {
assert_eq!(PointerDevice::Mouse.properties().hover_pressure, 0.0);
}
#[test]
fn touch_has_pressure_but_no_tilt() {
let p = PointerDevice::Touch.properties();
assert!(p.active_pressure_range.0 > 0.0);
assert!(!p.has_tilt);
assert!(!p.has_twist);
}
#[test]
fn stylus_has_tilt_and_twist() {
let p = PointerDevice::Stylus.properties();
assert!(p.has_tilt);
assert!(p.has_twist);
assert_eq!(p.pointer_type, "pen");
}
#[test]
fn stylus_samples_non_zero_tilt() {
let mut rng = StdRng::seed_from_u64(1);
let (tx, ty) = PointerDevice::Stylus.sample_tilt(&mut rng);
assert!(tx != 0 || ty != 0);
}
#[test]
fn mouse_samples_zero_tilt_and_twist() {
let mut rng = StdRng::seed_from_u64(1);
assert_eq!(PointerDevice::Mouse.sample_tilt(&mut rng), (0, 0));
assert_eq!(PointerDevice::Mouse.sample_twist(&mut rng), 0);
}
}