garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /hid/src/lib.rs

raw

//! 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. A
//! keyboard's boot report becomes key presses ([`Keyboard`]), from USB or
//! from Bluetooth alike.
//!
//! [`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 keyboard;
mod pointer;

pub use keyboard::{Key, Keyboard, key_code, usage};
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;