git clone https://garage44.eu/jeroen/pinnacle.git.. /hid/src/pointer.rs
//! A pointer on the screen, moved by a pointing device's reports.
use crate::{Field, Layout};
use alloc::vec::Vec;
/// What a report did to the pointer, in screen pixels.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PointerEvent {
/// The pointer is now at `x`, `y`; `relative` when a mouse (or a
/// touchpad as one) moved it, not a touch or a tablet's pen.
Move { x: i32, y: i32, relative: bool },
/// The first button went down or up (a touch, as the virtio tablet's
/// is), where the pointer is.
Press { down: bool, x: i32, y: i32 },
}
/// The pointer a device moves: where it is, and its buttons held.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Pointer {
pub x: i32,
pub y: i32,
pub buttons: u32,
}
impl Pointer {
/// A pointer in the middle of a `width` by `height` screen.
pub fn new(width: i32, height: i32) -> Pointer {
Pointer {
x: width / 2,
y: height / 2,
buttons: 0,
}
}
/// A report arrived (with its report ID, if the layout has one): the
/// events it makes on a `width` by `height` screen. A report with
/// another ID than the layout's makes none.
pub fn report(
&mut self,
layout: &Layout,
report: &[u8],
(width, height): (i32, i32),
out: &mut Vec<PointerEvent>,
) {
let report = match layout.report_id {
Some(id) if report.first() == Some(&id) => &report[1..],
Some(_) => return,
None => report,
};
let (Some(fx), Some(fy)) = (layout.x, layout.y) else {
return;
};
let (x, y) = (fx.read(report), fy.read(report));
let (old_x, old_y) = (self.x, self.y);
if fx.relative {
self.x = (self.x + x).clamp(0, width - 1);
self.y = (self.y + y).clamp(0, height - 1);
} else {
let scale = |v: i32, f: Field, size: i32| {
let span = i64::from(f.max - f.min).max(1) + 1;
(i64::from(v - f.min) * i64::from(size) / span) as i32
};
self.x = scale(x, fx, width);
self.y = scale(y, fy, height);
}
if (self.x, self.y) != (old_x, old_y) {
out.push(PointerEvent::Move {
x: self.x,
y: self.y,
relative: fx.relative,
});
}
let buttons = layout
.buttons
.iter()
.enumerate()
.fold(0u32, |b, (i, f)| b | u32::from(f.read(report) != 0) << i);
if (buttons ^ self.buttons) & 1 != 0 {
out.push(PointerEvent::Press {
down: buttons & 1 != 0,
x: self.x,
y: self.y,
});
}
self.buttons = buttons;
}
}