git clone https://garage44.eu/jeroen/pinnacle.gitcartopolis-agent · 2026-11-30T14:15:02Z
feat(hid): report descriptors and HID over I²C in a crate of their own The HID report-descriptor parsing (Field, Layout, parse) and the pointer a report moves leave kernel/src/drivers/usb/hid.rs for a new no_std crate, `pinnacle-hid` (hid/), so that USB and a touchpad on I²C share them. USB keeps its behaviour: `parse` still takes the first report with an X and a Y, a relative device moves a pointer kept on the screen, an absolute one points where it points, the first button is a touch; the kernel turns the crate's PointerEvent into InputEvent in drivers::input. The crate also has HID over I²C (Microsoft's specification 1.0) as a state machine (`i2c::Bringup`) over an `I2cBus` trait: the 30-byte HID descriptor from the register _DSM names, SET_POWER ON, RESET and its zero-length answer (looked for for about a second, then gone on from, as Linux does), the report descriptor, and the input register read as a 2-byte length (0: nothing) and a report. `parse_relative` prefers a relative report, so a touchpad's mouse collection is followed rather than its precision-touchpad one. Added to the workspace and to the gate's test and clippy lists. Tested: cargo test --release -p pinnacle-hid (16 tests: a boot mouse, a tablet, a fake ELAN-like touchpad with a mouse collection, report 1, and a PTP digitizer collection, report 3, ignored; the bring-up order, an unanswered reset, NAKs, a bad descriptor), clippy clean; cargo xtask pc and cargo xtask laptop pass (USB keyboard, tablet and stick as before).
Cargo.lock | 5 +
Cargo.toml | 2 +-
hid/Cargo.toml | 10 +
hid/src/i2c.rs | 345 +++++++++++++++++++++++++++++++
hid/src/lib.rs | 217 ++++++++++++++++++++
hid/src/pointer.rs | 87 ++++++++
hid/src/tests.rs | 465 ++++++++++++++++++++++++++++++++++++++++++
kernel/Cargo.toml | 1 +
kernel/src/drivers/input.rs | 20 ++
kernel/src/drivers/usb/hid.rs | 212 +------------------
xtask/src/main.rs | 4 +
11 files changed, 1164 insertions(+), 204 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
index 7abe575..01d11cd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -75,6 +75,7 @@ dependencies = [
"pinnacle-crypto",
"pinnacle-disk",
"pinnacle-fs",
+ "pinnacle-hid",
"pinnacle-net",
"pinnacle-pkg",
"pinnacle-ttf",
@@ -124,6 +125,10 @@ dependencies = [
"pinnacle-vector",
]
+[[package]]
+name = "pinnacle-hid"
+version = "0.1.0"
+
[[package]]
name = "pinnacle-json"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 9fdf0ed..2c3acb5 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,5 +1,5 @@
[workspace]
-members = ["abi", "aml", "bt", "contacts", "crypto", "disk", "gfx", "json", "kernel", "layout", "locale", "media", "modem", "net", "p2p", "pfs", "pkg", "programs", "records", "rt", "speech", "sync", "text", "tls", "ttf", "tz", "ui", "vector", "venus", "view", "wifi", "workbench", "xtask"]
+members = ["abi", "aml", "bt", "contacts", "crypto", "disk", "gfx", "hid", "json", "kernel", "layout", "locale", "media", "modem", "net", "p2p", "pfs", "pkg", "programs", "records", "rt", "speech", "sync", "text", "tls", "ttf", "tz", "ui", "vector", "venus", "view", "wifi", "workbench", "xtask"]
exclude = ["boot", "vulkan"]
resolver = "3"
diff --git a/hid/Cargo.toml b/hid/Cargo.toml
new file mode 100644
index 0000000..bf6bcf7
--- /dev/null
+++ b/hid/Cargo.toml
@@ -0,0 +1,10 @@
+[package]
+name = "pinnacle-hid"
+description = "HID report descriptors and pointers, and HID over I²C, with no outside crate: what USB and a laptop's touchpad share"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+publish.workspace = true
+
+[lib]
+doctest = false
diff --git a/hid/src/i2c.rs b/hid/src/i2c.rs
new file mode 100644
index 0000000..ee5d33e
--- /dev/null
+++ b/hid/src/i2c.rs
@@ -0,0 +1,345 @@
+//! HID over I²C (Microsoft's HID over I2C Protocol Specification 1.0):
+//! a laptop's touchpad, and some keyboards, on an I²C bus rather than
+//! USB. The firmware's ACPI says where (the device's `I2cSerialBus`
+//! resource: its controller and address) and which register its HID
+//! descriptor is at (its `_DSM`, [`DSM_UUID`] function 1); everything
+//! else the device says itself, in that descriptor.
+//!
+//! Bringing one up ([`Bringup`], a state machine, so that whoever runs
+//! it may sleep between steps): read the 30-byte HID descriptor, turn
+//! the device on (SET_POWER ON), RESET it and wait for its answer (an
+//! input report of length 0), read its report descriptor. From then on
+//! ([`Device`]) each read of the input register is a 2-byte length
+//! (with itself) and a report; a length of 0 is nothing to say.
+//!
+//! The input register is read as Linux's `i2c-hid` reads it: a plain
+//! read at the device's address, no register written first. A device
+//! raises its interrupt line while it has a report; with no line
+//! followed, the reads come by polling, and a device with nothing to say
+//! answers a length of 0.
+
+use crate::{Layout, Pointer, PointerEvent};
+use alloc::vec;
+use alloc::vec::Vec;
+use core::fmt;
+
+/// An I²C bus as a HID device needs it, at 7-bit (or 10-bit) address
+/// `addr`.
+pub trait I2cBus {
+ /// Writes `write`, then with a repeated start reads `read.len()`
+ /// bytes: one transfer. Empty `write`: a plain read; empty `read`: a
+ /// plain write. False when the device did not answer (no
+ /// acknowledgement) or the bus failed.
+ fn write_read(&mut self, addr: u16, write: &[u8], read: &mut [u8]) -> bool;
+
+ /// Writes `bytes`, and stops.
+ fn write(&mut self, addr: u16, bytes: &[u8]) -> bool {
+ self.write_read(addr, bytes, &mut [])
+ }
+}
+
+/// The `_DSM` that answers the HID descriptor's register (function 1,
+/// revision 1), `3CDFF6F7-4267-4555-AD05-B30A3D8938DE`, as the 16-byte
+/// buffer AML's `ToUUID` makes of it (the first three groups little
+/// endian).
+pub const DSM_UUID: [u8; 16] = [
+ 0xf7, 0xf6, 0xdf, 0x3c, 0x67, 0x42, 0x55, 0x45, 0xad, 0x05, 0xb3, 0x0a, 0x3d, 0x89, 0x38, 0xde,
+];
+
+/// How long the HID descriptor is (wHIDDescLength), in version 1.0.
+pub const DESCRIPTOR_LEN: usize = 30;
+
+/// Command opcodes (section 7.2), written to the command register.
+const RESET: u8 = 0x01;
+const SET_POWER: u8 = 0x08;
+/// SET_POWER's states.
+const POWER_ON: u8 = 0;
+
+/// Steps: how often the reset's answer is looked for, and how long
+/// apart (ms): a second in all. The specification gives a device five
+/// seconds; Linux, too, goes on without the answer.
+const RESET_TRIES: u32 = 100;
+const RESET_EVERY_MS: u32 = 10;
+/// How often the HID descriptor is asked for: a device just powered
+/// may not acknowledge the first.
+const DESCRIPTOR_TRIES: u32 = 3;
+/// The longest report descriptor and input report taken.
+const MAX_REPORT_DESCRIPTOR: usize = 8192;
+const MAX_INPUT: usize = 4096;
+
+/// The HID descriptor (section 5.1): where the device's registers are,
+/// what it is.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct HidDescriptor {
+ /// bcdVersion: 0x0100.
+ pub version: u16,
+ pub report_descriptor_length: u16,
+ pub report_descriptor_register: u16,
+ pub input_register: u16,
+ /// The longest input report, with its two length bytes.
+ pub max_input_length: u16,
+ pub output_register: u16,
+ pub max_output_length: u16,
+ pub command_register: u16,
+ pub data_register: u16,
+ pub vendor: u16,
+ pub product: u16,
+ pub version_id: u16,
+}
+
+impl HidDescriptor {
+ /// Reads the 30 bytes; None unless they say they are 30 long and of
+ /// version 1.0.
+ pub fn parse(b: &[u8]) -> Option<HidDescriptor> {
+ let w = |i: usize| -> Option<u16> { Some(u16::from_le_bytes([*b.get(2 * i)?, *b.get(2 * i + 1)?])) };
+ if usize::from(w(0)?) != DESCRIPTOR_LEN || w(1)? != 0x0100 {
+ return None;
+ }
+ Some(HidDescriptor {
+ version: w(1)?,
+ report_descriptor_length: w(2)?,
+ report_descriptor_register: w(3)?,
+ input_register: w(4)?,
+ max_input_length: w(5)?,
+ output_register: w(6)?,
+ max_output_length: w(7)?,
+ command_register: w(8)?,
+ data_register: w(9)?,
+ vendor: w(10)?,
+ product: w(11)?,
+ version_id: w(12)?,
+ })
+ }
+}
+
+/// Why a device was not brought up, or stopped answering.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Error {
+ /// The HID descriptor's register did not answer.
+ NoDescriptor,
+ /// It answered, not with a version 1.0 HID descriptor.
+ BadDescriptor,
+ /// SET_POWER ON, or RESET, was not acknowledged.
+ PowerOn,
+ Reset,
+ /// The report descriptor could not be read.
+ NoReportDescriptor,
+ /// The report descriptor has no report with an X and a Y.
+ NoPointer,
+ /// A read of the input register failed.
+ Input,
+}
+
+impl fmt::Display for Error {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ f.write_str(match self {
+ Error::NoDescriptor => "no HID descriptor",
+ Error::BadDescriptor => "not a HID 1.0 descriptor",
+ Error::PowerOn => "SET_POWER not acknowledged",
+ Error::Reset => "RESET not acknowledged",
+ Error::NoReportDescriptor => "no report descriptor",
+ Error::NoPointer => "no pointer in its reports",
+ Error::Input => "the input register did not answer",
+ })
+ }
+}
+
+/// Where a [`Bringup`] is.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum State {
+ Descriptor,
+ PowerOn,
+ Reset,
+ ResetAnswer,
+ ReportDescriptor,
+}
+
+/// What the caller does after a [`Bringup::step`].
+#[derive(Debug, PartialEq, Eq)]
+pub enum Step {
+ /// Step again after `ms` milliseconds (0: at once).
+ Again(u32),
+ Ready(Device),
+ Failed(Error),
+}
+
+/// A device being brought up, a step at a time.
+#[derive(Clone, Debug)]
+pub struct Bringup {
+ address: u16,
+ register: u16,
+ state: State,
+ tries: u32,
+ descriptor: HidDescriptor,
+ reset_answered: bool,
+}
+
+impl Bringup {
+ /// The device at `address` whose HID descriptor is at `register`
+ /// (from `_DSM`).
+ pub fn new(address: u16, register: u16) -> Bringup {
+ Bringup {
+ address,
+ register,
+ state: State::Descriptor,
+ tries: 0,
+ descriptor: HidDescriptor::default(),
+ reset_answered: false,
+ }
+ }
+
+ fn command(&self, bus: &mut dyn I2cBus, opcode: u8, low: u8) -> bool {
+ let r = self.descriptor.command_register.to_le_bytes();
+ bus.write(self.address, &[r[0], r[1], low, opcode])
+ }
+
+ /// The next step.
+ pub fn step(&mut self, bus: &mut dyn I2cBus) -> Step {
+ match self.state {
+ State::Descriptor => {
+ let mut b = [0u8; DESCRIPTOR_LEN];
+ if !bus.write_read(self.address, &self.register.to_le_bytes(), &mut b) {
+ self.tries += 1;
+ return if self.tries < DESCRIPTOR_TRIES {
+ Step::Again(10)
+ } else {
+ Step::Failed(Error::NoDescriptor)
+ };
+ }
+ let Some(d) = HidDescriptor::parse(&b) else {
+ return Step::Failed(Error::BadDescriptor);
+ };
+ self.descriptor = d;
+ self.state = State::PowerOn;
+ Step::Again(0)
+ }
+ State::PowerOn => {
+ if !self.command(bus, SET_POWER, POWER_ON) {
+ return Step::Failed(Error::PowerOn);
+ }
+ self.state = State::Reset;
+ // Some devices want a moment to wake (Linux gives 60 ms
+ // to those it knows of).
+ Step::Again(RESET_EVERY_MS)
+ }
+ State::Reset => {
+ if !self.command(bus, RESET, 0) {
+ return Step::Failed(Error::Reset);
+ }
+ self.state = State::ResetAnswer;
+ self.tries = 0;
+ Step::Again(RESET_EVERY_MS)
+ }
+ State::ResetAnswer => {
+ let mut b = vec![0u8; input_length(&self.descriptor)];
+ if bus.write_read(self.address, &[], &mut b) && b[0] == 0 && b[1] == 0 {
+ self.reset_answered = true;
+ self.state = State::ReportDescriptor;
+ return Step::Again(0);
+ }
+ self.tries += 1;
+ if self.tries >= RESET_TRIES {
+ self.state = State::ReportDescriptor;
+ return Step::Again(0);
+ }
+ Step::Again(RESET_EVERY_MS)
+ }
+ State::ReportDescriptor => {
+ let length = usize::from(self.descriptor.report_descriptor_length);
+ if length == 0 || length > MAX_REPORT_DESCRIPTOR {
+ return Step::Failed(Error::NoReportDescriptor);
+ }
+ let mut report_descriptor = vec![0u8; length];
+ let register = self.descriptor.report_descriptor_register.to_le_bytes();
+ if !bus.write_read(self.address, ®ister, &mut report_descriptor) {
+ return Step::Failed(Error::NoReportDescriptor);
+ }
+ let Some(layout) = crate::parse_relative(&report_descriptor) else {
+ return Step::Failed(Error::NoPointer);
+ };
+ Step::Ready(Device {
+ address: self.address,
+ descriptor: self.descriptor,
+ input: vec![0; input_length(&self.descriptor)],
+ report_descriptor,
+ layout,
+ reset_answered: self.reset_answered,
+ })
+ }
+ }
+ }
+}
+
+/// How many bytes an input read takes: the device's longest report,
+/// with its length.
+fn input_length(d: &HidDescriptor) -> usize {
+ usize::from(d.max_input_length).clamp(2, MAX_INPUT)
+}
+
+/// Brings up the device at `address`, its HID descriptor at `register`,
+/// calling `wait` with the milliseconds to wait between steps.
+pub fn bring_up(
+ bus: &mut dyn I2cBus,
+ address: u16,
+ register: u16,
+ mut wait: impl FnMut(u32),
+) -> Result<Device, Error> {
+ let mut b = Bringup::new(address, register);
+ loop {
+ match b.step(bus) {
+ Step::Again(0) => {}
+ Step::Again(ms) => wait(ms),
+ Step::Ready(d) => return Ok(d),
+ Step::Failed(e) => return Err(e),
+ }
+ }
+}
+
+/// A device brought up: its descriptors, and its pointer's layout.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Device {
+ pub address: u16,
+ pub descriptor: HidDescriptor,
+ pub report_descriptor: Vec<u8>,
+ /// The report the pointer is read from: the mouse's, where the
+ /// device has one beside a precision touchpad's.
+ pub layout: Layout,
+ /// Whether the RESET was answered with its empty report.
+ pub reset_answered: bool,
+ input: Vec<u8>,
+}
+
+impl Device {
+ /// Reads the input register: the report it holds (its ID first,
+ /// where the device numbers its reports), or None when it has
+ /// nothing to say (a length of 0, or no more than the length itself)
+ /// or says it has more than it can.
+ pub fn read_input(&mut self, bus: &mut dyn I2cBus) -> Result<Option<&[u8]>, Error> {
+ Ok(self.read(bus)?.map(|n| &self.input[2..n]))
+ }
+
+ /// The input report's end in `input`, if there is one.
+ fn read(&mut self, bus: &mut dyn I2cBus) -> Result<Option<usize>, Error> {
+ if !bus.write_read(self.address, &[], &mut self.input) {
+ return Err(Error::Input);
+ }
+ let length = usize::from(u16::from_le_bytes([self.input[0], self.input[1]]));
+ Ok((length > 2 && length <= self.input.len()).then_some(length))
+ }
+
+ /// Reads the input register once, and moves `pointer` by what it
+ /// says on a `screen` of that size. True when a report came.
+ pub fn poll(
+ &mut self,
+ bus: &mut dyn I2cBus,
+ pointer: &mut Pointer,
+ screen: (i32, i32),
+ out: &mut Vec<PointerEvent>,
+ ) -> Result<bool, Error> {
+ let Some(end) = self.read(bus)? else {
+ return Ok(false);
+ };
+ pointer.report(&self.layout, &self.input[2..end], screen, out);
+ Ok(true)
+ }
+}
diff --git a/hid/src/lib.rs b/hid/src/lib.rs
new file mode 100644
index 0000000..c80c2a0
--- /dev/null
+++ b/hid/src/lib.rs
@@ -0,0 +1,217 @@
+//! Human Interface Devices (Device Class Definition for HID 1.11), with
+//! no outside crate: what a USB mouse and a laptop's touchpad on I²C
+//! share. A pointing device's report descriptor is read for where its
+//! X, Y, wheel and buttons are ([`parse`]), and each report it sends
+//! becomes pointer events ([`Pointer`]): an absolute device (a tablet, a
+//! touch screen) points where it points, a relative one (a mouse, a
+//! touchpad in its mouse mode) moves a pointer kept on the screen.
+//!
+//! [`i2c`] is HID over I²C (Microsoft's HID over I2C protocol
+//! specification 1.0): how a touchpad behind a laptop's I²C controller
+//! is woken, reset, described and read, over any bus that does
+//! [`i2c::I2cBus`]. Nothing here touches hardware: the kernel's USB and
+//! I²C drivers bring the bytes.
+
+#![no_std]
+
+extern crate alloc;
+
+pub mod i2c;
+mod pointer;
+
+pub use pointer::{Pointer, PointerEvent};
+
+use alloc::vec::Vec;
+
+/// A field of a report: where it is, how wide, its range.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Field {
+ pub offset: u32,
+ pub size: u32,
+ pub min: i32,
+ pub max: i32,
+ pub relative: bool,
+}
+
+impl Field {
+ /// Its value in `report` (the report's ID, if it has one, taken off).
+ pub fn read(&self, report: &[u8]) -> i32 {
+ let mut value: u32 = 0;
+ for i in 0..self.size.min(32) {
+ let bit = self.offset + i;
+ let byte = report.get((bit / 8) as usize).copied().unwrap_or(0);
+ value |= u32::from(byte >> (bit % 8) & 1) << i;
+ }
+ // Signed when its range is.
+ if self.min < 0 && self.size < 32 && value & (1 << (self.size - 1)) != 0 {
+ (value | !0 << self.size) as i32
+ } else {
+ value as i32
+ }
+ }
+}
+
+/// Where a pointing device's report keeps what it says.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Layout {
+ pub report_id: Option<u8>,
+ pub x: Option<Field>,
+ pub y: Option<Field>,
+ pub wheel: Option<Field>,
+ /// Buttons 1, 2, 3…, each a bit.
+ pub buttons: Vec<Field>,
+}
+
+impl Layout {
+ /// Whether its X and Y are movements (a mouse), not places.
+ pub fn relative(&self) -> bool {
+ self.x.is_some_and(|x| x.relative)
+ }
+}
+
+/// Reads a report descriptor (HID 1.11, section 6.2.2) for the first
+/// report with an X and a Y in it: its pointer's layout.
+pub fn parse(descriptor: &[u8]) -> Option<Layout> {
+ layouts(descriptor)?
+ .into_iter()
+ .find(|l| l.x.is_some() && l.y.is_some())
+}
+
+/// As [`parse`], preferring a report whose X and Y are relative: a
+/// touchpad has a mouse's report beside its precision touchpad's
+/// (absolute, a finger's place), and sends the mouse's until it is told
+/// otherwise.
+pub fn parse_relative(descriptor: &[u8]) -> Option<Layout> {
+ let pointers: Vec<Layout> = layouts(descriptor)?
+ .into_iter()
+ .filter(|l| l.x.is_some() && l.y.is_some())
+ .collect();
+ let relative = pointers.iter().position(Layout::relative);
+ pointers.into_iter().nth(relative.unwrap_or(0))
+}
+
+/// Every input report a descriptor declares, by report ID, with the
+/// pointer's fields found in each. None when the descriptor ends inside
+/// an item.
+pub fn layouts(descriptor: &[u8]) -> Option<Vec<Layout>> {
+ #[derive(Clone, Copy, Default)]
+ struct Global {
+ page: u32,
+ min: i32,
+ max: i32,
+ size: u32,
+ count: u32,
+ id: u8,
+ }
+ let mut g = Global::default();
+ let mut stack: Vec<Global> = Vec::new();
+ let mut usages: Vec<u32> = Vec::new();
+ let mut range: Option<(u32, u32)> = None;
+ // Bits read so far, per report ID.
+ let mut offsets: Vec<(u8, u32)> = Vec::new();
+ let mut layouts: Vec<Layout> = Vec::new();
+ let mut at = 0;
+ while at < descriptor.len() {
+ let prefix = descriptor[at];
+ if prefix == 0xfe {
+ // A long item: its length is in the next byte.
+ at += 3 + usize::from(*descriptor.get(at + 1)?);
+ continue;
+ }
+ let size = [0, 1, 2, 4][usize::from(prefix & 3)];
+ let data = descriptor.get(at + 1..at + 1 + size)?;
+ let unsigned = data.iter().rev().fold(0u32, |v, &b| v << 8 | u32::from(b));
+ let signed = match size {
+ 1 => i32::from(data[0] as i8),
+ 2 => i32::from(i16::from_le_bytes([data[0], data[1]])),
+ 4 => unsigned as i32,
+ _ => 0,
+ };
+ let (kind, tag) = ((prefix >> 2) & 3, prefix >> 4);
+ match (kind, tag) {
+ // Main: Input.
+ (0, 8) => {
+ let constant = unsigned & 1 != 0;
+ let variable = unsigned & 2 != 0;
+ let relative = unsigned & 4 != 0;
+ let offset = match offsets.iter_mut().find(|(id, _)| *id == g.id) {
+ Some((_, o)) => o,
+ None => {
+ offsets.push((g.id, 0));
+ &mut offsets.last_mut().unwrap().1
+ }
+ };
+ let layout = match layouts
+ .iter_mut()
+ .position(|l| l.report_id == Some(g.id).filter(|&i| i != 0))
+ {
+ Some(i) => &mut layouts[i],
+ None => {
+ layouts.push(Layout {
+ report_id: Some(g.id).filter(|&i| i != 0),
+ ..Layout::default()
+ });
+ layouts.last_mut().unwrap()
+ }
+ };
+ for i in 0..g.count {
+ let usage = if let Some((lo, hi)) = range {
+ (lo + i).min(hi)
+ } else {
+ usages.get(i as usize).or(usages.last()).copied().unwrap_or(0)
+ };
+ // A usage with its page in its top half, or the page in force.
+ let usage = if usage > 0xffff {
+ usage
+ } else {
+ g.page << 16 | usage
+ };
+ let field = Field {
+ offset: *offset + i * g.size,
+ size: g.size,
+ min: g.min,
+ max: g.max,
+ relative,
+ };
+ if !constant && variable {
+ match usage {
+ 0x0001_0030 => layout.x = Some(field),
+ 0x0001_0031 => layout.y = Some(field),
+ 0x0001_0038 => layout.wheel = Some(field),
+ u if u >> 16 == 0x09 && (1..=8).contains(&(u & 0xffff)) => {
+ layout.buttons.push(field);
+ }
+ _ => {}
+ }
+ }
+ }
+ *offset += g.size * g.count;
+ usages.clear();
+ range = None;
+ }
+ // Main: Output, Feature, Collection, End Collection.
+ (0, _) => {
+ usages.clear();
+ range = None;
+ }
+ (1, 0) => g.page = unsigned,
+ (1, 1) => g.min = signed,
+ // A logical maximum is unsigned when the minimum is not negative.
+ (1, 2) => g.max = if g.min >= 0 { unsigned as i32 } else { signed },
+ (1, 7) => g.size = unsigned,
+ (1, 8) => g.id = unsigned as u8,
+ (1, 9) => g.count = unsigned,
+ (1, 10) => stack.push(g),
+ (1, 11) => g = stack.pop().unwrap_or(g),
+ (2, 0) => usages.push(if size == 4 { unsigned } else { unsigned & 0xffff }),
+ (2, 1) => range = Some((unsigned, range.map_or(unsigned, |r| r.1))),
+ (2, 2) => range = Some((range.map_or(0, |r| r.0), unsigned)),
+ _ => {}
+ }
+ at += 1 + size;
+ }
+ Some(layouts)
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/hid/src/pointer.rs b/hid/src/pointer.rs
new file mode 100644
index 0000000..900a474
--- /dev/null
+++ b/hid/src/pointer.rs
@@ -0,0 +1,87 @@
+//! 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;
+ }
+}
diff --git a/hid/src/tests.rs b/hid/src/tests.rs
new file mode 100644
index 0000000..bd60824
--- /dev/null
+++ b/hid/src/tests.rs
@@ -0,0 +1,465 @@
+use crate::i2c::{self, Bringup, Error, HidDescriptor, I2cBus, Step};
+use crate::{Field, Pointer, PointerEvent, layouts, parse, parse_relative};
+use alloc::collections::VecDeque;
+use alloc::vec;
+use alloc::vec::Vec;
+
+/// A USB boot mouse's descriptor: no report ID, three buttons, relative
+/// X, Y and wheel.
+const MOUSE: &[u8] = &[
+ 0x05, 0x01, 0x09, 0x02, 0xa1, 0x01, 0x09, 0x01, 0xa1, 0x00, //
+ 0x05, 0x09, 0x19, 0x01, 0x29, 0x03, 0x15, 0x00, 0x25, 0x01, 0x95, 0x03, 0x75, 0x01, 0x81, 0x02, //
+ 0x95, 0x01, 0x75, 0x05, 0x81, 0x03, //
+ 0x05, 0x01, 0x09, 0x30, 0x09, 0x31, 0x09, 0x38, 0x15, 0x81, 0x25, 0x7f, 0x75, 0x08, 0x95, 0x03, 0x81,
+ 0x06, //
+ 0xc0, 0xc0,
+];
+
+/// QEMU's USB tablet: one button, absolute 15-bit X and Y.
+const TABLET: &[u8] = &[
+ 0x05, 0x01, 0x09, 0x02, 0xa1, 0x01, 0x09, 0x01, 0xa1, 0x00, //
+ 0x05, 0x09, 0x19, 0x01, 0x29, 0x03, 0x15, 0x00, 0x25, 0x01, 0x95, 0x03, 0x75, 0x01, 0x81, 0x02, //
+ 0x95, 0x01, 0x75, 0x05, 0x81, 0x01, //
+ 0x05, 0x01, 0x09, 0x30, 0x09, 0x31, 0x15, 0x00, 0x26, 0xff, 0x7f, 0x35, 0x00, 0x46, 0xff, 0x7f, 0x75,
+ 0x10, 0x95, 0x02, 0x81, 0x02, //
+ 0xc0, 0xc0,
+];
+
+/// The mouse collection an ELAN or Synaptics touchpad sends until told
+/// otherwise: report 1, two buttons, relative 8-bit X and Y.
+const TOUCHPAD_MOUSE: &[u8] = &[
+ 0x05, 0x01, 0x09, 0x02, 0xa1, 0x01, 0x85, 0x01, 0x09, 0x01, 0xa1, 0x00, //
+ 0x05, 0x09, 0x19, 0x01, 0x29, 0x02, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x02, 0x81, 0x02, //
+ 0x95, 0x06, 0x81, 0x03, //
+ 0x05, 0x01, 0x09, 0x30, 0x09, 0x31, 0x15, 0x81, 0x25, 0x7f, 0x75, 0x08, 0x95, 0x02, 0x81, 0x06, //
+ 0xc0, 0xc0,
+];
+
+/// Its precision touchpad (Windows' PTP) collection: report 3, a
+/// finger's confidence, tip, contact ID, absolute X and Y with physical
+/// units; the scan time, contact count and the pad's button; then the
+/// feature reports Windows asks (contact count maximum, the pad's kind;
+/// report 4, the input mode).
+const TOUCHPAD_PTP: &[u8] = &[
+ 0x05, 0x0d, 0x09, 0x05, 0xa1, 0x01, 0x85, 0x03, //
+ 0x05, 0x0d, 0x09, 0x22, 0xa1, 0x02, //
+ 0x15, 0x00, 0x25, 0x01, 0x09, 0x47, 0x09, 0x42, 0x95, 0x02, 0x75, 0x01, 0x81, 0x02, //
+ 0x95, 0x01, 0x75, 0x03, 0x25, 0x05, 0x09, 0x51, 0x81, 0x02, //
+ 0x75, 0x01, 0x95, 0x03, 0x81, 0x03, //
+ 0x05, 0x01, 0x15, 0x00, 0x26, 0xaf, 0x04, 0x75, 0x10, 0x55, 0x0e, 0x65, 0x11, 0x09, 0x30, 0x35, 0x00,
+ 0x46, 0xe8, 0x03, 0x95, 0x01, 0x81, 0x02, //
+ 0x26, 0x7b, 0x02, 0x46, 0x12, 0x02, 0x09, 0x31, 0x81, 0x02, //
+ 0xc0, //
+ 0x05, 0x0d, 0x55, 0x0c, 0x66, 0x01, 0x10, 0x47, 0xff, 0xff, 0x00, 0x00, 0x27, 0xff, 0xff, 0x00, 0x00,
+ 0x75, 0x10, 0x95, 0x01, 0x09, 0x56, 0x81, 0x02, //
+ 0x09, 0x54, 0x25, 0x7f, 0x95, 0x01, 0x75, 0x08, 0x81, 0x02, //
+ 0x05, 0x09, 0x09, 0x01, 0x25, 0x01, 0x75, 0x01, 0x95, 0x01, 0x81, 0x02, //
+ 0x95, 0x07, 0x81, 0x03, //
+ 0x05, 0x0d, 0x85, 0x02, 0x09, 0x55, 0x09, 0x59, 0x75, 0x04, 0x95, 0x02, 0x25, 0x0f, 0xb1, 0x02, //
+ 0xc0, //
+ 0x05, 0x0d, 0x09, 0x0e, 0xa1, 0x01, 0x85, 0x04, 0x09, 0x22, 0xa1, 0x02, //
+ 0x09, 0x52, 0x15, 0x00, 0x25, 0x0a, 0x75, 0x08, 0x95, 0x01, 0xb1, 0x02, //
+ 0xc0, 0xc0,
+];
+
+fn touchpad_descriptor() -> Vec<u8> {
+ [TOUCHPAD_MOUSE, TOUCHPAD_PTP].concat()
+}
+
+#[test]
+fn a_boot_mouse_has_relative_x_y_and_wheel() {
+ let l = parse(MOUSE).unwrap();
+ assert_eq!(l.report_id, None);
+ assert_eq!(
+ l.x,
+ Some(Field {
+ offset: 8,
+ size: 8,
+ min: -127,
+ max: 127,
+ relative: true
+ })
+ );
+ assert_eq!(l.y.unwrap().offset, 16);
+ assert_eq!(l.wheel.unwrap().offset, 24);
+ assert_eq!(l.buttons.len(), 3);
+ assert_eq!(l.buttons[2].offset, 2);
+}
+
+#[test]
+fn a_field_reads_signed_when_its_range_is() {
+ let f = Field {
+ offset: 8,
+ size: 8,
+ min: -127,
+ max: 127,
+ relative: true,
+ };
+ assert_eq!(f.read(&[0, 0xfd]), -3);
+ assert_eq!(f.read(&[0, 5]), 5);
+ let u = Field {
+ offset: 4,
+ size: 12,
+ min: 0,
+ max: 4095,
+ relative: false,
+ };
+ assert_eq!(u.read(&[0xf0, 0xff]), 4095);
+}
+
+#[test]
+fn a_tablet_points_where_it_points() {
+ let l = parse(TABLET).unwrap();
+ assert!(!l.relative());
+ let mut p = Pointer {
+ x: 0,
+ y: 0,
+ buttons: 0,
+ };
+ let mut out = Vec::new();
+ // The middle, button down.
+ p.report(&l, &[1, 0x00, 0x40, 0x00, 0x40], (1000, 800), &mut out);
+ assert_eq!(
+ out,
+ [
+ PointerEvent::Move {
+ x: 500,
+ y: 400,
+ relative: false
+ },
+ PointerEvent::Press {
+ down: true,
+ x: 500,
+ y: 400
+ }
+ ]
+ );
+}
+
+#[test]
+fn a_mouse_moves_the_pointer_and_stays_on_the_screen() {
+ let l = parse(MOUSE).unwrap();
+ let mut p = Pointer::new(100, 50);
+ let mut out = Vec::new();
+ p.report(&l, &[0, 10, 0xfb, 0], (100, 50), &mut out);
+ assert_eq!(
+ out,
+ [PointerEvent::Move {
+ x: 60,
+ y: 20,
+ relative: true
+ }]
+ );
+ out.clear();
+ p.report(&l, &[0, 127, 127, 0], (100, 50), &mut out);
+ assert_eq!((p.x, p.y), (99, 49));
+ // Nothing moved, nothing pressed: no event.
+ out.clear();
+ p.report(&l, &[0, 0, 0, 0], (100, 50), &mut out);
+ assert!(out.is_empty());
+}
+
+#[test]
+fn a_truncated_descriptor_is_none() {
+ assert_eq!(parse(&MOUSE[..MOUSE.len() - 3]), None);
+ assert_eq!(parse(&[0x26, 0xff]), None);
+}
+
+#[test]
+fn a_touchpad_is_read_as_its_mouse() {
+ let d = touchpad_descriptor();
+ let l = parse(&d).unwrap();
+ assert_eq!(l.report_id, Some(1));
+ assert!(l.relative());
+ assert_eq!(l.x.unwrap().offset, 8);
+ assert_eq!(l.y.unwrap().offset, 16);
+ assert_eq!(l.buttons.len(), 2);
+ // Its precision touchpad's report is there too, absolute: a finger's
+ // X after a byte of flags, Y after it.
+ let all = layouts(&d).unwrap();
+ let ptp = all.iter().find(|l| l.report_id == Some(3)).unwrap();
+ assert_eq!(
+ ptp.x,
+ Some(Field {
+ offset: 8,
+ size: 16,
+ min: 0,
+ max: 1199,
+ relative: false
+ })
+ );
+ assert_eq!(ptp.y.unwrap().max, 635);
+ assert_eq!(ptp.buttons.len(), 1);
+}
+
+#[test]
+fn the_mouse_is_chosen_even_after_the_touchpad() {
+ let d = [TOUCHPAD_PTP, TOUCHPAD_MOUSE].concat();
+ // `parse`, as USB has it, takes the first.
+ assert_eq!(parse(&d).unwrap().report_id, Some(3));
+ let l = parse_relative(&d).unwrap();
+ assert_eq!(l.report_id, Some(1));
+ // With no relative report, the absolute one.
+ assert_eq!(parse_relative(TABLET), parse(TABLET));
+}
+
+#[test]
+fn the_dsm_uuid_is_tou_uids_bytes() {
+ let text = "3CDFF6F7-4267-4555-AD05-B30A3D8938DE";
+ let hex: Vec<u8> = text
+ .split('-')
+ .flat_map(|g| {
+ (0..g.len() / 2)
+ .map(|i| u8::from_str_radix(&g[2 * i..2 * i + 2], 16).unwrap())
+ .collect::<Vec<_>>()
+ })
+ .collect();
+ let mut want = hex.clone();
+ want[0..4].reverse();
+ want[4..6].reverse();
+ want[6..8].reverse();
+ assert_eq!(i2c::DSM_UUID[..], want[..]);
+}
+
+/// A touchpad on the bus: at 0x15, its HID descriptor at register 1, as
+/// ELAN's are; registers 2 (report descriptor), 3 (input), 5 (command).
+struct Fake {
+ address: u16,
+ descriptor: [u8; 30],
+ report_descriptor: Vec<u8>,
+ on: bool,
+ /// Answers owed: the reset's empty report.
+ reset_pending: bool,
+ /// The input register not acknowledged: the reset's answer never
+ /// read.
+ input_naks: bool,
+ /// Reports waiting, the device's interrupt line low.
+ reports: VecDeque<Vec<u8>>,
+ /// What the host did, in order.
+ log: Vec<&'static str>,
+ /// Transfers to fail from the start.
+ nak_first: u32,
+}
+
+impl Fake {
+ fn new() -> Fake {
+ let words: [u16; 13] = [30, 0x0100, 0, 2, 3, 32, 4, 0, 5, 6, 0x04f3, 0x3140, 0x0001];
+ let mut descriptor = [0u8; 30];
+ for (i, w) in words.iter().enumerate() {
+ descriptor[2 * i..2 * i + 2].copy_from_slice(&w.to_le_bytes());
+ }
+ let report_descriptor = touchpad_descriptor();
+ descriptor[4..6].copy_from_slice(&(report_descriptor.len() as u16).to_le_bytes());
+ Fake {
+ address: 0x15,
+ descriptor,
+ report_descriptor,
+ on: false,
+ reset_pending: false,
+ input_naks: false,
+ reports: VecDeque::new(),
+ log: Vec::new(),
+ nak_first: 0,
+ }
+ }
+}
+
+impl I2cBus for Fake {
+ fn write_read(&mut self, addr: u16, write: &[u8], read: &mut [u8]) -> bool {
+ if addr != self.address {
+ return false;
+ }
+ if self.nak_first > 0 {
+ self.nak_first -= 1;
+ return false;
+ }
+ match (write, read.len()) {
+ // A plain read: the input register.
+ ([], n) if n > 0 => {
+ read.fill(0);
+ if !self.on || self.input_naks {
+ return false;
+ }
+ // A report from before the reset comes first.
+ if let Some(r) = self.reports.pop_front() {
+ let len = (r.len() + 2) as u16;
+ read[..2].copy_from_slice(&len.to_le_bytes());
+ read[2..2 + r.len()].copy_from_slice(&r);
+ return true;
+ }
+ if core::mem::take(&mut self.reset_pending) {
+ self.log.push("reset answer");
+ }
+ true
+ }
+ ([1, 0], _) => {
+ self.log.push("hid descriptor");
+ let n = read.len().min(30);
+ read[..n].copy_from_slice(&self.descriptor[..n]);
+ true
+ }
+ ([2, 0], n) if self.on => {
+ self.log.push("report descriptor");
+ read.copy_from_slice(&self.report_descriptor[..n]);
+ true
+ }
+ ([5, 0, 0, 0x08], 0) => {
+ self.log.push("power on");
+ self.on = true;
+ true
+ }
+ ([5, 0, 0, 0x01], 0) if self.on => {
+ self.log.push("reset");
+ self.reset_pending = true;
+ true
+ }
+ _ => false,
+ }
+ }
+}
+
+#[test]
+fn the_hid_descriptor_says_where_everything_is() {
+ let d = HidDescriptor::parse(&Fake::new().descriptor).unwrap();
+ assert_eq!((d.vendor, d.product), (0x04f3, 0x3140));
+ assert_eq!((d.input_register, d.command_register), (3, 5));
+ assert_eq!(d.report_descriptor_length as usize, touchpad_descriptor().len());
+ let mut bad = Fake::new().descriptor;
+ bad[2] = 0x02;
+ assert_eq!(HidDescriptor::parse(&bad), None);
+ assert_eq!(HidDescriptor::parse(&bad[..10]), None);
+}
+
+#[test]
+fn a_touchpad_is_woken_reset_and_described_in_that_order() {
+ let mut bus = Fake::new();
+ let mut waited = 0;
+ let d = i2c::bring_up(&mut bus, 0x15, 1, |ms| waited += ms).unwrap();
+ assert_eq!(
+ bus.log,
+ [
+ "hid descriptor",
+ "power on",
+ "reset",
+ "reset answer",
+ "report descriptor"
+ ]
+ );
+ assert!(d.reset_answered);
+ assert_eq!((d.descriptor.vendor, d.descriptor.product), (0x04f3, 0x3140));
+ assert_eq!(d.layout.report_id, Some(1));
+ assert!(d.layout.relative());
+ assert!(waited > 0);
+}
+
+#[test]
+fn a_moved_finger_moves_the_pointer_and_a_click_presses() {
+ let mut bus = Fake::new();
+ let mut d = i2c::bring_up(&mut bus, 0x15, 1, |_| {}).unwrap();
+ let mut p = Pointer::new(1920, 1080);
+ let mut out = Vec::new();
+ // Nothing to say: a length of 0.
+ assert_eq!(d.poll(&mut bus, &mut p, (1920, 1080), &mut out), Ok(false));
+ assert!(out.is_empty());
+ // Report 1: left button, 5 right, 3 up.
+ bus.reports.push_back(vec![1, 0b01, 5, 0xfd]);
+ // A precision touchpad's report: not followed.
+ bus.reports
+ .push_back(vec![3, 0x03, 0x10, 0x00, 0x20, 0x00, 0, 0, 1, 0]);
+ // The button let go.
+ bus.reports.push_back(vec![1, 0, 0, 0]);
+ for _ in 0..3 {
+ assert_eq!(d.poll(&mut bus, &mut p, (1920, 1080), &mut out), Ok(true));
+ }
+ assert_eq!(
+ out,
+ [
+ PointerEvent::Move {
+ x: 965,
+ y: 537,
+ relative: true
+ },
+ PointerEvent::Press {
+ down: true,
+ x: 965,
+ y: 537
+ },
+ PointerEvent::Press {
+ down: false,
+ x: 965,
+ y: 537
+ },
+ ]
+ );
+}
+
+#[test]
+fn read_input_gives_the_report_with_its_id() {
+ let mut bus = Fake::new();
+ let mut d = i2c::bring_up(&mut bus, 0x15, 1, |_| {}).unwrap();
+ bus.reports.push_back(vec![1, 2, 3, 4]);
+ assert_eq!(d.read_input(&mut bus), Ok(Some(&[1u8, 2, 3, 4][..])));
+ assert_eq!(d.read_input(&mut bus), Ok(None));
+ bus.address = 0x2c;
+ assert_eq!(d.read_input(&mut bus), Err(Error::Input));
+}
+
+#[test]
+fn an_unanswered_reset_is_waited_for_and_then_gone_on_from() {
+ let mut bus = Fake::new();
+ // A report already waiting is not the reset's answer: the next read
+ // is.
+ bus.reports.push_back(vec![1, 0, 1, 1]);
+ let mut waits = 0;
+ let d = i2c::bring_up(&mut bus, 0x15, 1, |_| waits += 1).unwrap();
+ assert!(d.reset_answered);
+ assert_eq!(waits, 3);
+ let mut bus = Fake::new();
+ bus.input_naks = true;
+ let mut waits = 0;
+ let d = i2c::bring_up(&mut bus, 0x15, 1, |_| waits += 1).unwrap();
+ assert!(!d.reset_answered);
+ // About a second of 10 ms waits, and no more.
+ assert!((100..=103).contains(&waits), "{waits}");
+}
+
+#[test]
+fn a_device_that_does_not_answer_fails_after_a_few_tries() {
+ let mut bus = Fake::new();
+ assert_eq!(i2c::bring_up(&mut bus, 0x2c, 1, |_| {}), Err(Error::NoDescriptor));
+ // The first two asks not acknowledged: the third is.
+ let mut bus = Fake::new();
+ bus.nak_first = 2;
+ assert!(i2c::bring_up(&mut bus, 0x15, 1, |_| {}).is_ok());
+ let mut bus = Fake::new();
+ bus.descriptor[2] = 0x02;
+ assert_eq!(
+ i2c::bring_up(&mut bus, 0x15, 1, |_| {}),
+ Err(Error::BadDescriptor)
+ );
+}
+
+#[test]
+fn the_state_machine_steps_one_transfer_at_a_time() {
+ let mut bus = Fake::new();
+ let mut b = Bringup::new(0x15, 1);
+ assert_eq!(b.step(&mut bus), Step::Again(0));
+ assert_eq!(bus.log, ["hid descriptor"]);
+ assert!(matches!(b.step(&mut bus), Step::Again(ms) if ms > 0));
+ assert_eq!(bus.log.last(), Some(&"power on"));
+ assert!(matches!(b.step(&mut bus), Step::Again(ms) if ms > 0));
+ assert_eq!(bus.log.last(), Some(&"reset"));
+ assert_eq!(b.step(&mut bus), Step::Again(0));
+ assert!(matches!(b.step(&mut bus), Step::Ready(_)));
+}
+
+#[test]
+fn a_descriptor_with_no_pointer_is_refused() {
+ let mut bus = Fake::new();
+ // Only the precision touchpad's configuration collection: no X, Y.
+ let config = &TOUCHPAD_PTP[TOUCHPAD_PTP.len() - 26..];
+ assert_eq!(config[0..4], [0x05, 0x0d, 0x09, 0x0e]);
+ bus.report_descriptor = config.to_vec();
+ bus.descriptor[4..6].copy_from_slice(&(config.len() as u16).to_le_bytes());
+ assert_eq!(i2c::bring_up(&mut bus, 0x15, 1, |_| {}), Err(Error::NoPointer));
+}
diff --git a/kernel/Cargo.toml b/kernel/Cargo.toml
index 6f88653..8883693 100644
--- a/kernel/Cargo.toml
+++ b/kernel/Cargo.toml
@@ -24,6 +24,7 @@ pinnacle-abi = { path = "../abi" }
pinnacle-aml = { path = "../aml" }
pinnacle-disk = { path = "../disk" }
pinnacle-fs = { path = "../pfs" }
+pinnacle-hid = { path = "../hid" }
pinnacle-net = { path = "../net" }
pinnacle-pkg = { path = "../pkg" }
diff --git a/kernel/src/drivers/input.rs b/kernel/src/drivers/input.rs
index 478e24c..ccd6070 100644
--- a/kernel/src/drivers/input.rs
+++ b/kernel/src/drivers/input.rs
@@ -116,6 +116,26 @@ pub fn deliver(events: Vec<InputEvent>) {
}
}
+/// What a HID pointer did (USB's, a touchpad's on I²C) as the display
+/// server reads it: a mouse's moves `BY_MOUSE`, its first button a touch.
+pub fn pointer_event(e: pinnacle_hid::PointerEvent) -> InputEvent {
+ let (kind, code, value, x, y) = match e {
+ pinnacle_hid::PointerEvent::Move { x, y, relative } => {
+ let by = if relative { InputEvent::BY_MOUSE } else { 0 };
+ (InputEvent::MOVE, by, 0, x, y)
+ }
+ pinnacle_hid::PointerEvent::Press { down, x, y } => (InputEvent::PRESS, 0, i32::from(down), x, y),
+ };
+ InputEvent {
+ kind,
+ code,
+ value,
+ x,
+ y,
+ synthetic: false,
+ }
+}
+
/// An input device's interrupt. False if `intid` is no input device's.
pub fn interrupt(intid: u32) -> bool {
let mut input = INPUT.lock();
diff --git a/kernel/src/drivers/usb/hid.rs b/kernel/src/drivers/usb/hid.rs
index c87d20d..8ffaac0 100644
--- a/kernel/src/drivers/usb/hid.rs
+++ b/kernel/src/drivers/usb/hid.rs
@@ -6,6 +6,8 @@
//! for where its X, Y, wheel and buttons are: an absolute one (a tablet, a
//! touch screen) moves to where it points, as the virtio tablet does; a
//! relative one (a mouse) moves a pointer the kernel keeps on the screen.
+//! The descriptor and the pointer are `pinnacle_hid`'s, shared with the
+//! touchpad on I²C (`drivers::i2c_hid`).
use super::{Controller, Descriptor, Interface, configure_endpoints, start_reading};
use crate::mm::pages;
@@ -14,170 +16,11 @@ use crate::sync::SpinLock;
use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_abi::InputEvent;
+use pinnacle_hid::{Layout, Pointer, parse};
/// What each device attached is, for the self-check and Settings.
pub static ATTACHED: SpinLock<Vec<String>> = SpinLock::new(Vec::new());
-/// A field of a report: where it is, how wide, its range.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub struct Field {
- pub offset: u32,
- pub size: u32,
- pub min: i32,
- pub max: i32,
- pub relative: bool,
-}
-
-impl Field {
- fn read(&self, report: &[u8]) -> i32 {
- let mut value: u32 = 0;
- for i in 0..self.size.min(32) {
- let bit = self.offset + i;
- let byte = report.get((bit / 8) as usize).copied().unwrap_or(0);
- value |= u32::from(byte >> (bit % 8) & 1) << i;
- }
- // Signed when its range is.
- if self.min < 0 && self.size < 32 && value & (1 << (self.size - 1)) != 0 {
- (value | !0 << self.size) as i32
- } else {
- value as i32
- }
- }
-}
-
-/// Where a pointing device's report keeps what it says.
-#[derive(Clone, Debug, Default, PartialEq, Eq)]
-pub struct Layout {
- pub report_id: Option<u8>,
- pub x: Option<Field>,
- pub y: Option<Field>,
- pub wheel: Option<Field>,
- /// Buttons 1, 2, 3…, each a bit.
- pub buttons: Vec<Field>,
-}
-
-/// Reads a report descriptor (HID 1.11, section 6.2.2) for the first
-/// report with an X and a Y in it: its pointer's layout.
-pub fn parse(descriptor: &[u8]) -> Option<Layout> {
- #[derive(Clone, Copy, Default)]
- struct Global {
- page: u32,
- min: i32,
- max: i32,
- size: u32,
- count: u32,
- id: u8,
- }
- let mut g = Global::default();
- let mut stack: Vec<Global> = Vec::new();
- let mut usages: Vec<u32> = Vec::new();
- let mut range: Option<(u32, u32)> = None;
- // Bits read so far, per report ID.
- let mut offsets: Vec<(u8, u32)> = Vec::new();
- let mut layouts: Vec<Layout> = Vec::new();
- let mut at = 0;
- while at < descriptor.len() {
- let prefix = descriptor[at];
- if prefix == 0xfe {
- // A long item: its length is in the next byte.
- at += 3 + usize::from(*descriptor.get(at + 1)?);
- continue;
- }
- let size = [0, 1, 2, 4][usize::from(prefix & 3)];
- let data = descriptor.get(at + 1..at + 1 + size)?;
- let unsigned = data.iter().rev().fold(0u32, |v, &b| v << 8 | u32::from(b));
- let signed = match size {
- 1 => i32::from(data[0] as i8),
- 2 => i32::from(i16::from_le_bytes([data[0], data[1]])),
- 4 => unsigned as i32,
- _ => 0,
- };
- let (kind, tag) = ((prefix >> 2) & 3, prefix >> 4);
- match (kind, tag) {
- // Main: Input.
- (0, 8) => {
- let constant = unsigned & 1 != 0;
- let variable = unsigned & 2 != 0;
- let relative = unsigned & 4 != 0;
- let offset = match offsets.iter_mut().find(|(id, _)| *id == g.id) {
- Some((_, o)) => o,
- None => {
- offsets.push((g.id, 0));
- &mut offsets.last_mut().unwrap().1
- }
- };
- let layout = match layouts
- .iter_mut()
- .position(|l| l.report_id == Some(g.id).filter(|&i| i != 0))
- {
- Some(i) => &mut layouts[i],
- None => {
- layouts.push(Layout {
- report_id: Some(g.id).filter(|&i| i != 0),
- ..Layout::default()
- });
- layouts.last_mut().unwrap()
- }
- };
- for i in 0..g.count {
- let usage = if let Some((lo, hi)) = range {
- (lo + i).min(hi)
- } else {
- usages.get(i as usize).or(usages.last()).copied().unwrap_or(0)
- };
- // A usage with its page in its top half, or the page in force.
- let usage = if usage > 0xffff {
- usage
- } else {
- g.page << 16 | usage
- };
- let field = Field {
- offset: *offset + i * g.size,
- size: g.size,
- min: g.min,
- max: g.max,
- relative,
- };
- if !constant && variable {
- match usage {
- 0x0001_0030 => layout.x = Some(field),
- 0x0001_0031 => layout.y = Some(field),
- 0x0001_0038 => layout.wheel = Some(field),
- u if u >> 16 == 0x09 && (1..=8).contains(&(u & 0xffff)) => {
- layout.buttons.push(field);
- }
- _ => {}
- }
- }
- }
- *offset += g.size * g.count;
- usages.clear();
- range = None;
- }
- // Main: Output, Feature, Collection, End Collection.
- (0, _) => {
- usages.clear();
- range = None;
- }
- (1, 0) => g.page = unsigned,
- (1, 1) => g.min = signed,
- // A logical maximum is unsigned when the minimum is not negative.
- (1, 2) => g.max = if g.min >= 0 { unsigned as i32 } else { signed },
- (1, 7) => g.size = unsigned,
- (1, 8) => g.id = unsigned as u8,
- (1, 9) => g.count = unsigned,
- (1, 10) => stack.push(g),
- (1, 11) => g = stack.pop().unwrap_or(g),
- (2, 0) => usages.push(if size == 4 { unsigned } else { unsigned & 0xffff }),
- (2, 1) => range = Some((unsigned, range.map_or(unsigned, |r| r.1))),
- (2, 2) => range = Some((range.map_or(0, |r| r.0), unsigned)),
- _ => {}
- }
- at += 1 + size;
- }
- layouts.into_iter().find(|l| l.x.is_some() && l.y.is_some())
-}
-
/// Linux's key code for each keyboard usage (HID Usage Tables, page 7), as
/// its `usbkbd` driver has them: what the display server reads.
const KEYS: [u8; 256] = [
@@ -218,9 +61,7 @@ pub struct Reader {
kind: Kind,
previous: [u8; 8],
/// The pointer a relative device moves, and its buttons held.
- x: i32,
- y: i32,
- buttons: u32,
+ pointer: Pointer,
}
/// The screen's size, which pointer positions are in.
@@ -280,42 +121,9 @@ impl Reader {
}
fn pointer(&mut self, layout: &Layout, report: &[u8], out: &mut Vec<InputEvent>) {
- let report = match layout.report_id {
- Some(id) if report.first() == Some(&id) => &report[1..],
- Some(_) => return,
- None => report,
- };
- let (width, height) = screen();
- 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) {
- let by = if fx.relative { InputEvent::BY_MOUSE } else { 0 };
- out.push(event(InputEvent::MOVE, by, 0, self.x, self.y));
- }
- let buttons = layout
- .buttons
- .iter()
- .enumerate()
- .fold(0u32, |b, (i, f)| b | u32::from(f.read(report) != 0) << i);
- // The first button is a touch, as the virtio tablet's is.
- if (buttons ^ self.buttons) & 1 != 0 {
- out.push(event(InputEvent::PRESS, 0, (buttons & 1) as i32, self.x, self.y));
- }
- self.buttons = buttons;
+ let mut moved = Vec::new();
+ self.pointer.report(layout, report, screen(), &mut moved);
+ out.extend(moved.into_iter().map(crate::drivers::input::pointer_event));
}
}
@@ -370,7 +178,7 @@ pub fn attach(
};
let what = match &kind {
Kind::Keyboard => "keyboard",
- Kind::Pointer(l) if l.x.is_some_and(|x| x.relative) => "mouse",
+ Kind::Pointer(l) if l.relative() => "mouse",
Kind::Pointer(_) => "tablet",
};
let (width, height) = screen();
@@ -383,9 +191,7 @@ pub fn attach(
length: usize::from(endpoint.2).clamp(1, 64),
kind,
previous: [0; 8],
- x: width / 2,
- y: height / 2,
- buttons: 0,
+ pointer: Pointer::new(width, height),
},
);
let line = alloc::format!("{what} ({})", d.product_name);
diff --git a/xtask/src/main.rs b/xtask/src/main.rs
index f5e965f..9ae3e65 100644
--- a/xtask/src/main.rs
+++ b/xtask/src/main.rs
@@ -1760,6 +1760,8 @@ fn gate() -> Result {
"pinnacle-speech",
"-p",
"pinnacle-aml",
+ "-p",
+ "pinnacle-hid",
])?;
cargo(&[
"clippy",
@@ -1806,6 +1808,8 @@ fn gate() -> Result {
"pinnacle-speech",
"-p",
"pinnacle-aml",
+ "-p",
+ "pinnacle-hid",
"--",
"-D",
"warnings",