fix(input): an I2C-HID precision touchpad is switched to touchpad mode and its contacts drive the shared touchpad translator with its physical size, two-finger scroll and buttons, where it stayed in firmware mouse mode with its coarse relative reports

This commit is contained in:
Tyler Smith committed 2026-11-16 19:31:31 -05:00
1 parent 5f0c904229
commit 2105d4b6ca
4 files changed
+571 -9

No files matched your search

+1
View File
@@ -11,6 +11,7 @@ pub mod hid_i2c;
pub mod ish;
pub mod observation;
pub mod ps2;
pub mod ptp;
pub mod rmi;
pub mod sfh;
pub mod touchpad;
+52 -9
View File
@@ -14,10 +14,10 @@
//! with the same delay standing in for the reset interrupt.
//! Raw HID reports and the exact report descriptor pass to a shared HID consumer;
//! no keyboard, touchpad or touchscreen descriptor is substituted here.
use super::Input;
use super::{Input, ptp};
use crate::bus::i2c::{self, Address, Bus, Operation, Timer};
use crate::bus::pci::power::{self, Timer as Minimum};
use crate::usb::hid::{ParseError, Translator};
use crate::usb::hid::{ParseError, Translated, Translator};
use alloc::{rc::Rc, string::String, vec::Vec};
use core::mem::ManuallyDrop;
mod refusal;
@@ -321,6 +321,10 @@ impl<B: Bus, I: Interrupt, T: Timer> Device<B, I, T> {
pub fn descriptor(&self) -> Option<&Descriptor> {
self.descriptor.as_ref()
}
/// The device's clock now, in microseconds.
pub fn now_us(&self) -> u64 {
self.timer.now_us()
}
pub fn report_descriptor(&self) -> &[u8] {
&self.report_descriptor
}
@@ -780,6 +784,8 @@ const POLL_REPORTS: usize = 16;
pub struct HidInput<B, I, T> {
device: ManuallyDrop<Device<B, I, T>>,
translator: Translator,
/// A precision touchpad switched to report its fingers.
ptp: Option<ptp::Ptp>,
pub name: String,
}
@@ -791,17 +797,42 @@ impl<B: Bus, I: Interrupt, T: Timer> HidInput<B, I, T> {
reason = "a device whose descriptor does not parse goes back to its owner"
)]
pub fn new(device: Device<B, I, T>, name: String) -> Result<Self, Refusal<B, I, T>> {
let device = ManuallyDrop::new(device);
let mut device = ManuallyDrop::new(device);
match Translator::describe(device.report_descriptor()) {
Ok(translator) => Ok(Self {
device,
translator,
name,
}),
Ok(translator) => {
// A precision touchpad goes to touchpad mode, as Linux
// hid-multitouch's `mt_set_modes` sets it; a failed switch
// leaves it in its firmware's mouse mode, read as a mouse,
// and the failure is the device's, reported by its poll.
let ptp = translator
.descriptor()
.and_then(ptp::Profile::select)
.filter(|profile| {
profile.mode_reports().iter().all(|(id, payload)| {
device.set_report(ReportType::Feature, *id, payload).is_ok()
})
})
.map(ptp::Ptp::new);
let mut name = name;
if ptp.is_some() {
name.push_str(" precision touchpad");
}
Ok(Self {
device,
translator,
ptp,
name,
})
}
Err(error) => Err(Refusal::descriptor(device, error)),
}
}
/// Whether the device is a precision touchpad reporting its fingers.
pub fn is_precision_touchpad(&self) -> bool {
self.ptp.is_some()
}
pub fn device(&self) -> &Device<B, I, T> {
&self.device
}
@@ -816,7 +847,19 @@ impl<B: Bus, I: Interrupt, T: Timer> HidInput<B, I, T> {
Some(
InputReport::Data(report) | InputReport::CorrectedLength { data: report, .. },
) => {
self.translator.translate(&report, &mut events, inputs);
let at = events.len();
let translated = self.translator.translate(&report, &mut events, inputs);
if let (Some(ptp), Translated::Data(frame), Some(descriptor)) =
(&mut self.ptp, &translated, self.translator.descriptor())
{
ptp.report(
descriptor,
frame,
&events[at..],
self.device.now_us(),
inputs,
);
}
}
Some(InputReport::Empty | InputReport::SpuriousInterrupt) => {}
}
+318
View File
@@ -0,0 +1,318 @@
// SPDX-License-Identifier: GPL-2.0-only
// Linux hid-multitouch.c reference: Copyright (c) 2010-2012 Stephane
// Chatty, Benjamin Tissoires and Ecole Nationale de l'Aviation Civile.
// See NOTICE.
//! Precision touchpads behind HID: a touchpad application (Digitizers 05h)
//! that lists its fingers' contacts, with an Input Mode feature in a device
//! configuration application. Such a pad starts in its firmware's mouse
//! mode; set to touchpad mode as Linux `mt_set_modes` sets it, it reports
//! each finger, and [`Translator`] turns finger travel into motion and two
//! fingers into scrolling at the pad's physical size, as the other
//! touchpads here.
//!
//! A frame is one report, or a first report whose contact count says how
//! many contacts follow and continuation reports with a count of 0, as
//! `mt_touch_report` assembles hybrid frames. The pad lists every contact
//! of a frame, so a contact left out of a frame is lifted.
use super::{
Input,
touchpad::{Axis, Geometry, Touch, Translator},
};
use crate::usb::hid::{
Descriptor, Frame, ReportType,
descriptor::{ReportField, Value},
events::{Contact, Event},
};
use alloc::vec::Vec;
const TOUCH_PAD: u32 = 0x000d_0005;
const CONFIGURATION: u32 = 0x000d_000e;
const FINGER: u32 = 0x000d_0022;
const INPUT_MODE: u32 = 0x000d_0052;
const SURFACE_SWITCH: u32 = 0x000d_0057;
const BUTTON_SWITCH: u32 = 0x000d_0058;
const X: u32 = 0x0001_0030;
const Y: u32 = 0x0001_0031;
const BUTTON_1: u32 = 0x0009_0001;
/// hid-multitouch's `MT_INPUTMODE_TOUCHPAD`.
const MODE_TOUCHPAD: i64 = 3;
/// Contacts one frame holds at most, as hid-multitouch's slot limit.
const MAX_CONTACTS: usize = 250;
/// The application collection `collection` belongs to.
fn application(descriptor: &Descriptor, mut collection: Option<usize>) -> Option<usize> {
while let Some(index) = collection {
let c = descriptor.collections.get(index)?;
if c.kind == 1 {
return Some(index);
}
collection = c.parent;
}
None
}
/// Whether `collection` lies in a Finger logical collection.
fn in_finger(descriptor: &Descriptor, mut collection: Option<usize>) -> bool {
while let Some(index) = collection {
let Some(c) = descriptor.collections.get(index) else {
return false;
};
if c.usage == FINGER {
return true;
}
if c.kind == 1 {
return false;
}
collection = c.parent;
}
false
}
/// The millimetres a field's physical range spans, from its unit: SI
/// linear (centimetres) or English linear (inches), length to the first
/// power, scaled by its unit exponent.
fn millimetres(field: &ReportField) -> Option<u16> {
let extent = i128::from(field.physical_maximum) - i128::from(field.physical_minimum);
if extent <= 0 {
return None;
}
// Micrometres per unit of the field's system.
let per_unit: i128 = match field.unit & 0xff {
0x11 => 10_000,
0x13 => 25_400,
_ => return None,
};
let exponent = i32::from(field.unit_exponent);
let mut um = extent * per_unit;
if exponent >= 0 {
um = um.checked_mul(10i128.checked_pow(exponent as u32)?)?;
} else {
um /= 10i128.checked_pow(exponent.unsigned_abs())?;
}
u16::try_from((um + 500) / 1000).ok().filter(|mm| *mm != 0)
}
/// One axis's scale from its field: its logical range over its physical
/// size, when both are stated.
fn axis(field: &ReportField) -> (u16, Option<Axis>) {
let range = u16::try_from(field.maximum.saturating_sub(field.minimum).max(0)).unwrap_or(0);
(
range,
millimetres(field).and_then(|mm| Axis::extent(range, mm)),
)
}
/// One feature report that selects touchpad mode: its ID, its bytes after
/// the ID, and its fields' (bit offset, size, value) to set; every other
/// bit is 0.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Mode {
id: u8,
bytes: usize,
values: Vec<(usize, usize, i64)>,
}
/// What a descriptor describes of a precision touchpad.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Profile {
application: usize,
geometry: Geometry,
modes: Vec<Mode>,
}
impl Profile {
/// The touchpad the descriptor describes, if it is a precision
/// touchpad: a touchpad application with fingers' X and Y, and an Input
/// Mode feature to select it with.
pub fn select(descriptor: &Descriptor) -> Option<Self> {
let is = |collection: Option<usize>, usage: u32| {
application(descriptor, collection)
.is_some_and(|app| descriptor.collections[app].usage == usage)
};
let field = |usage: u32| {
descriptor
.reports
.iter()
.filter(|report| report.kind == ReportType::Input)
.flat_map(|report| report.fields.iter())
.find(|field| {
field.usages.contains(&usage)
&& is(field.collection, TOUCH_PAD)
&& in_finger(descriptor, field.collection)
})
};
let (x, y) = (field(X)?, field(Y)?);
let application = application(descriptor, x.collection)?;
let (x_range, x_axis) = axis(x);
let (y_range, y_axis) = axis(y);
let mut modes = Vec::new();
for report in descriptor
.reports
.iter()
.filter(|report| report.kind == ReportType::Feature)
{
let mut values = Vec::new();
for field in &report.fields {
if !is(field.collection, CONFIGURATION) && !is(field.collection, TOUCH_PAD) {
continue;
}
for (element, usage) in field.usages.iter().enumerate().take(field.count) {
let value = match *usage {
INPUT_MODE => MODE_TOUCHPAD,
// Linux sets both switches on for a touchpad.
SURFACE_SWITCH | BUTTON_SWITCH => 1,
_ => continue,
};
if (field.minimum..=field.maximum).contains(&value) {
values.push((field.offset + element * field.size, field.size, value));
}
}
}
if !values.is_empty() {
modes.push(Mode {
id: report.id,
bytes: report.bits.div_ceil(8),
values,
});
}
}
// The mode switch is what makes contacts flow.
if !modes.iter().any(|Mode { id, .. }| {
descriptor.reports.iter().any(|report| {
report.kind == ReportType::Feature
&& report.id == *id
&& report
.fields
.iter()
.any(|field| field.usages.contains(&INPUT_MODE))
})
}) {
return None;
}
Some(Self {
application,
geometry: Geometry::new((x_range, y_range), x_axis, y_axis),
modes,
})
}
/// The feature reports that select touchpad mode, as (report ID,
/// payload without the ID).
pub fn mode_reports(&self) -> Vec<(u8, Vec<u8>)> {
self.modes
.iter()
.map(|Mode { id, bytes, values }| {
let mut payload = alloc::vec![0u8; *bytes];
for &(offset, size, value) in values {
for bit in 0..size.min(64) {
if value >> bit & 1 != 0
&& let Some(byte) = payload.get_mut((offset + bit) / 8)
{
*byte |= 1 << ((offset + bit) % 8);
}
}
}
(*id, payload)
})
.collect()
}
pub fn geometry(&self) -> Geometry {
self.geometry
}
}
/// A precision touchpad in touchpad mode.
pub struct Ptp {
profile: Profile,
translator: Translator,
/// The contacts the frame being assembled expects, and those it has.
expected: usize,
received: Vec<Contact>,
}
impl Ptp {
pub fn new(profile: Profile) -> Self {
Self {
translator: Translator::new(profile.geometry),
profile,
expected: 0,
received: Vec::new(),
}
}
/// One input report: `frame` as decoded, and the descriptor events the
/// translator decoded from it. Reports of other applications are left
/// to the shared translator.
pub fn report(
&mut self,
descriptor: &Descriptor,
frame: &Frame,
events: &[Event],
now_us: u64,
inputs: &mut Vec<Input>,
) {
let Some(packet) = events.iter().find_map(|event| match event {
Event::Touch(packet) if packet.application == self.profile.application => Some(packet),
_ => None,
}) else {
return;
};
let mut buttons = 0u8;
for sample in &frame.samples {
let Some(usage) = sample.usage else {
continue;
};
if !(BUTTON_1..BUTTON_1 + 3).contains(&usage)
|| application(descriptor, sample.collection) != Some(self.profile.application)
{
continue;
}
if matches!(sample.value, Value::Scalar(value) if value != 0) && !sample.null {
buttons |= 1 << (usage - BUTTON_1);
}
}
let count = packet
.contact_count
.map_or(0, |count| usize::try_from(count).unwrap_or(0))
.min(MAX_CONTACTS);
if count != 0 {
// A nonzero count always starts a frame; one still pending was
// interrupted and is dropped.
self.expected = count;
self.received.clear();
}
for contact in &packet.contacts {
if self.received.len() >= self.expected {
break;
}
self.received.push(contact.clone());
}
if self.received.len() < self.expected {
return;
}
// A complete frame, or a count of 0 with no frame pending: a
// report of buttons alone, with no finger on the pad.
let mut fingers: Vec<_> = self
.received
.drain(..)
.filter(|contact| contact.tip == Some(true) && contact.confidence != Some(false))
.filter_map(|contact| Some((contact.id, contact.x?, contact.y?)))
.collect();
self.expected = 0;
fingers.sort_by_key(|(id, _, _)| *id);
let clamp = |value: i64| value.clamp(i32::MIN.into(), i32::MAX.into()) as i32;
let touch = Touch::of(fingers.into_iter().map(|(_, x, y)| (clamp(x), clamp(y))));
self.translator.frame(touch, buttons, now_us, inputs);
}
/// Release the buttons and forget the fingers, as a stopped pad's.
pub fn release(&mut self, inputs: &mut Vec<Input>) {
self.expected = 0;
self.received.clear();
self.translator.release(inputs);
}
}
#[cfg(test)]
mod tests;
+200
View File
@@ -0,0 +1,200 @@
use super::*;
use crate::usb::hid::{Translated, Translator};
use alloc::vec;
/// A precision touchpad of two finger collections, 1000 x 600 units over
/// 100 x 60 mm, with a contact count, a scan time and one button, its
/// contact maximum in feature report 2, Input Mode in feature report 3 and
/// the surface and button switches in feature report 4.
fn finger() -> Vec<u8> {
vec![
0x09, 0x22, 0xa1, 0x02, // Finger
0x15, 0x00, 0x25, 0x01, 0x09, 0x47, 0x09, 0x42, 0x95, 0x02, 0x75, 0x01, 0x81,
0x02, // Confidence, Tip Switch
0x95, 0x06, 0x81, 0x03, // padding
0x25, 0x05, 0x09, 0x51, 0x75, 0x08, 0x95, 0x01, 0x81, 0x02, // Contact ID
0x05, 0x01, 0x15, 0x00, 0x26, 0xe8, 0x03, 0x35, 0x00, 0x46, 0xe8, 0x03, 0x65, 0x11, 0x55,
0x0e, 0x75, 0x10, 0x95, 0x01, 0x09, 0x30, 0x81, 0x02, // X
0x26, 0x58, 0x02, 0x46, 0x58, 0x02, 0x09, 0x31, 0x81, 0x02, // Y
0x65, 0x00, 0x55, 0x00, 0x35, 0x00, 0x45, 0x00, 0x05, 0x0d, 0xc0,
]
}
fn descriptor() -> Vec<u8> {
let mut d = vec![0x05, 0x0d, 0x09, 0x05, 0xa1, 0x01, 0x85, 0x01];
d.extend(finger());
d.extend(finger());
d.extend([
0x15, 0x00, 0x27, 0xff, 0xff, 0x00, 0x00, 0x75, 0x10, 0x95, 0x01, 0x09, 0x56, 0x81,
0x02, // Scan Time
0x25, 0x7f, 0x75, 0x08, 0x09, 0x54, 0x81, 0x02, // Contact Count
0x05, 0x09, 0x09, 0x01, 0x25, 0x01, 0x75, 0x01, 0x95, 0x01, 0x81, 0x02, // Button 1
0x95, 0x07, 0x81, 0x03, // padding
0x05, 0x0d, 0x85, 0x02, 0x09, 0x55, 0x25, 0x05, 0x75, 0x08, 0x95, 0x01, 0xb1,
0x02, // Contact Count Maximum
0xc0, // end Touch Pad
0x05, 0x0d, 0x09, 0x0e, 0xa1, 0x01, 0x85, 0x03, // Device Configuration
0x09, 0x22, 0xa1, 0x02, 0x09, 0x52, 0x15, 0x00, 0x25, 0x0a, 0x75, 0x08, 0x95, 0x01, 0xb1,
0x02, 0xc0, // Input Mode
0x09, 0x22, 0xa1, 0x00, 0x85, 0x04, 0x09, 0x57, 0x09, 0x58, 0x75, 0x01, 0x95, 0x02, 0x25,
0x01, 0xb1, 0x02, 0x95, 0x06, 0xb1, 0x03, 0xc0, // switches
0xc0,
]);
d
}
/// One finger slot: (confidence, tip, id, x, y).
type Slot = (bool, bool, u8, u16, u16);
fn report(slots: [Slot; 2], scan: u16, count: u8, button: bool) -> Vec<u8> {
let mut r = vec![0x01];
for (confidence, tip, id, x, y) in slots {
r.push(u8::from(confidence) | u8::from(tip) << 1);
r.push(id);
r.extend(x.to_le_bytes());
r.extend(y.to_le_bytes());
}
r.extend(scan.to_le_bytes());
r.push(count);
r.push(u8::from(button));
r
}
const EMPTY: Slot = (false, false, 0, 0, 0);
struct Pad {
translator: Translator,
ptp: Ptp,
}
impl Pad {
fn new() -> Self {
let translator = Translator::describe(&descriptor()).unwrap();
let profile = Profile::select(translator.descriptor().unwrap()).unwrap();
Self {
translator,
ptp: Ptp::new(profile),
}
}
fn feed(&mut self, bytes: &[u8], now_us: u64) -> Vec<Input> {
let mut events = Vec::new();
let mut inputs = Vec::new();
let Translated::Data(frame) = self.translator.translate(bytes, &mut events, &mut inputs)
else {
panic!("report rejected");
};
assert!(inputs.is_empty(), "the shared translator reads no pointer");
self.ptp.report(
self.translator.descriptor().unwrap(),
&frame,
&events,
now_us,
&mut inputs,
);
inputs
}
}
#[test]
fn a_precision_touchpad_is_selected_with_its_size_and_mode_reports() {
let translator = Translator::describe(&descriptor()).unwrap();
let profile = Profile::select(translator.descriptor().unwrap()).unwrap();
assert_eq!(
profile.geometry(),
Geometry::size((1000, 600), (100, 60)),
"10 units per mm on both axes"
);
assert_eq!(
profile.mode_reports(),
vec![(3, vec![3]), (4, vec![0b11])],
"Input Mode 3, then the surface and button switches on"
);
}
#[test]
fn a_descriptor_without_an_input_mode_is_no_precision_touchpad() {
let mut d = descriptor();
// Input Mode becomes a vendor usage.
let at = d.windows(2).position(|w| w == [0x09, 0x52]).unwrap();
d[at + 1] = 0x99;
let translator = Translator::describe(&d).unwrap();
assert_eq!(Profile::select(translator.descriptor().unwrap()), None);
}
#[test]
fn one_finger_moves_two_fingers_scroll_and_a_lift_ends_the_touch() {
let mut pad = Pad::new();
// A finger lands, then moves 25 mm right: 250 units, 393.7 counts at
// 400 counts per inch.
let first = report([(true, true, 1, 100, 300), EMPTY], 10, 1, false);
assert!(pad.feed(&first, 0).is_empty());
let moved = report([(true, true, 1, 350, 300), EMPTY], 20, 1, false);
let inputs = pad.feed(&moved, 300_000);
assert_eq!(inputs, vec![Input::Motion { dx: 393, dy: 0 }]);
// A second finger lands: no jump; both move 10 mm up: 4 detents away.
let two = report(
[(true, true, 1, 350, 300), (true, true, 2, 450, 300)],
30,
2,
false,
);
assert!(pad.feed(&two, 310_000).is_empty());
let up = report(
[(true, true, 1, 350, 200), (true, true, 2, 450, 200)],
40,
2,
false,
);
assert_eq!(pad.feed(&up, 320_000), vec![Input::MouseWheel(4)]);
// Both lift, reported once with their tips up.
let lift = report(
[(true, false, 1, 350, 200), (true, false, 2, 450, 200)],
50,
2,
false,
);
assert!(pad.feed(&lift, 330_000).is_empty());
}
#[test]
fn a_short_still_touch_taps_and_a_palm_is_not_a_finger() {
let mut pad = Pad::new();
let down = report([(true, true, 1, 500, 300), EMPTY], 1, 1, false);
assert!(pad.feed(&down, 0).is_empty());
let up = report([(true, false, 1, 500, 300), EMPTY], 2, 1, false);
assert_eq!(
pad.feed(&up, 50_000),
vec![Input::MouseButtons(1), Input::MouseButtons(0)]
);
// A contact the pad marks without confidence moves nothing.
let palm = report([(false, true, 3, 100, 100), EMPTY], 3, 1, false);
assert!(pad.feed(&palm, 100_000).is_empty());
let palm = report([(false, true, 3, 900, 500), EMPTY], 4, 1, false);
assert!(pad.feed(&palm, 110_000).is_empty());
}
#[test]
fn hybrid_frames_wait_for_their_continuation_and_the_button_is_read() {
let mut pad = Pad::new();
let first = report(
[(true, true, 1, 100, 100), (true, true, 2, 200, 100)],
7,
2,
false,
);
assert!(pad.feed(&first, 0).is_empty());
// Three fingers over two reports: the frame completes on the second.
let start = report(
[(true, true, 1, 100, 100), (true, true, 2, 200, 100)],
8,
3,
true,
);
assert!(pad.feed(&start, 10_000).is_empty(), "frame incomplete");
let rest = report([(true, true, 3, 300, 100), EMPTY], 8, 0, true);
assert_eq!(pad.feed(&rest, 10_000), vec![Input::MouseButtons(1)]);
// A report of the button alone, with no finger on the pad.
let released = report([EMPTY, EMPTY], 9, 0, false);
assert_eq!(pad.feed(&released, 20_000), vec![Input::MouseButtons(0)]);
}