diff --git a/NOTICE b/NOTICE index 1c31689693..dbaa011880 100644 --- a/NOTICE +++ b/NOTICE @@ -38,11 +38,15 @@ Component License Where Linux kernel v7.2.12 (source in GPL-2.0-only, GPL-2.0-or-later, stela.efi third_party/linux, Rust ports in MIT, GPL-2.0 OR BSD-3-Clause and crates/stela-driver*/, other per-file terms -stela-linux, stela-boot-core) +stela-linux, stela-boot-core, +stela-soc) FreeBSD e1000 driver BSD-3-Clause stela.efi MediaTek mt76 Wi-Fi, btmtk and BSD-3-Clause-Clear, ISC stela.efi wireless regulatory ports Asahi Linux hci_bcm4377 GPL-2.0-only OR MIT (MIT used) stela.efi +VoodooInput (acidanthera), the GPL-2.0-only stela.efi +emulated Magic Trackpad 2's +reports and descriptors Intel drm_eld.h definitions MIT stela.efi Mesa 26.2.5 (NVK, NIR, NAK, MIT; c11 threads BSL-1.0 stela.efi Vulkan runtime) @@ -852,6 +856,10 @@ crates/stela-drivers/src/input/: Native input timer admission crates/stela-drivers/src/input/: Standard HID-over-I2C Linux a804c5742bff224d4cb4d25dd383554d598be32b; GPL-2.0-only drivers/hid/hid-ids.h, drivers/hid/i2c-hid/i2c-hid-core.c +crates/stela-drivers/src/input/: Precision touchpad whole frames, their palms + and scan-time clock + Linux cc9de5d4b5ab6459f5774946aa3195ad51236fa8; GPL-2.0-or-later + drivers/hid/hid-multitouch.c crates/stela-drivers/src/input/: RMI4 transport and F01 control substrate Linux a804c5742bff224d4cb4d25dd383554d598be32b; GPL-2.0-only drivers/input/rmi4/rmi_bus.h, drivers/input/rmi4/rmi_driver.c, @@ -1184,3 +1192,12 @@ crates/stela-linux/src/compat/kernel/: Linux kernel services for the unchanged lib/list_sort.c, lib/seq_buf.c, lib/sort.c, lib/usercopy.c, lib/vsprintf.c, mm/interval_tree.c, mm/memory.c, mm/mmap.c, mm/slab.h, mm/slub.c, mm/util.c, mm/vmalloc.c +crates/stela-soc/src/usb/: Emulated Magic Trackpad 2: its USB function, + descriptors, multitouch feature answers and reports + Linux cc9de5d4b5ab6459f5774946aa3195ad51236fa8; GPL-2.0-or-later + drivers/hid/hid-ids.h, drivers/hid/hid-magicmouse.c + VoodooInput d897813718c2ef9ad143b6a86240fe52dcb1693e; GPL-2.0-only + VoodooInput/VoodooInputIDs.hpp, + VoodooInput/VoodooInputSimulator/VoodooInputActuatorDevice.cpp, + VoodooInput/VoodooInputSimulator/VoodooInputSimulatorDevice.cpp, + VoodooInput/VoodooInputSimulator/VoodooInputSimulatorDevice.hpp diff --git a/crates/stela-boot-core/src/options.rs b/crates/stela-boot-core/src/options.rs index f23cce54d2..b35e048219 100644 --- a/crates/stela-boot-core/src/options.rs +++ b/crates/stela-boot-core/src/options.rs @@ -109,6 +109,41 @@ impl Lid { } } +/// Cables an emulated Magic Trackpad 2 fed by the host's precision +/// touchpads (`--trackpad mt2|builtin`): a hand-written opt-in, in a +/// startup choice of its own, that setup never writes (so the options +/// revision stays 13). +pub const TRACKPAD: &str = "--trackpad"; + +/// The trackpad `--trackpad` cables: a Magic Trackpad 2 (05AC:0265), or +/// the same device under the internal trackpad ID VoodooInput presents on +/// macOS 12 and later (05AC:0281). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GuestTrackpad { + Mt2, + Builtin, +} + +impl GuestTrackpad { + const NAMES: [(&'static str, Self); 2] = [("mt2", Self::Mt2), ("builtin", Self::Builtin)]; + + pub fn parse(value: &str) -> Result { + Self::NAMES + .iter() + .find(|(name, _)| *name == value) + .map(|(_, kind)| *kind) + .ok_or(Error::Trackpad) + } + + pub fn name(self) -> &'static str { + Self::NAMES + .iter() + .find(|(_, kind)| *kind == self) + .map(|(name, _)| *name) + .unwrap_or_default() + } +} + /// A `--audio-check` mode. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum AudioCheck { @@ -329,6 +364,10 @@ pub struct System { /// Cable the native USB keyboard and pointer to the last USB-C /// controller and feed it the host's virtio-input devices (`--input`). pub input: bool, + /// Cable an emulated Magic Trackpad 2 beside the native keyboard and + /// pointer, fed whole frames by the host's precision touchpads, which + /// then no longer move the native mouse ([`TRACKPAD`], with `--input`). + pub trackpad: Option, /// Explicit native executors and guest PEs (`--native-cores N`), one per /// logical processor; SMT siblings count after every physical core. pub native_cores: Option, @@ -484,6 +523,7 @@ impl Default for System { survey: false, idle_skip: false, input: false, + trackpad: None, native_cores: None, guest_pes: None, code_window: None, @@ -653,6 +693,13 @@ impl System { self.lid.unwrap_or_default() } + /// The trackpad this boot cables: `--trackpad`, on the hub `--input` + /// cables, so none without host input. The hub's disk-port count and + /// the cabling both read this, so they agree. + pub fn guest_trackpad(&self) -> Option { + self.trackpad.filter(|_| self.input) + } + /// This boot starts the macOS the Preboot disk holds, which needs a GPU; /// its recoveryOS and a staged update's installer show on the firmware's /// display, as a restore does. @@ -943,6 +990,7 @@ impl fmt::Display for System { line.value(IPV4_GATEWAY, self.ipv4_gateway)?; line.value(DNS, (!self.dns.is_empty()).then(|| Servers(&self.dns)))?; line.flag("--input", self.input)?; + line.value(TRACKPAD, self.trackpad.map(GuestTrackpad::name))?; line.flag("--idle-skip", self.idle_skip)?; line.flag("--survey", self.survey)?; line.flag("--sep-observe", self.sep_observe)?; diff --git a/crates/stela-boot-core/src/options/error.rs b/crates/stela-boot-core/src/options/error.rs index ec6bfb0c76..c4e469cf35 100644 --- a/crates/stela-boot-core/src/options/error.rs +++ b/crates/stela-boot-core/src/options/error.rs @@ -63,6 +63,8 @@ pub enum Error { DuplicateWifiKey, WifiCountry, DuplicateWifiCountry, + Trackpad, + DuplicateTrackpad, Usb4Approve, DuplicateUsb4Approve, Ipv4, @@ -144,6 +146,7 @@ pub enum Constraint { AudioHpetDependency, NativePciIoapicExclusive, LidSleepDependency, + TrackpadDependency, } impl Error { /// The established stela.cfg diagnostic at presentation-only callers. @@ -197,6 +200,8 @@ impl Error { Self::DuplicateWifiKey => "duplicate --wifi-key", Self::WifiCountry => "--wifi-country needs a two-letter country", Self::DuplicateWifiCountry => "duplicate --wifi-country", + Self::Trackpad => "--trackpad takes mt2 or builtin", + Self::DuplicateTrackpad => "duplicate --trackpad", Self::Usb4Approve => "--usb4-approve needs a device UUID", Self::DuplicateUsb4Approve => "duplicate --usb4-approve", Self::Ipv4 => "--ipv4 needs a host ADDRESS/PREFIX, such as 192.168.1.20/24", @@ -286,6 +291,9 @@ impl Constraint { "--native-pci-own-ioapic requires the normal system platform path" } Self::LidSleepDependency => "--lid-sleep requires --lid method", + Self::TrackpadDependency => { + "--trackpad needs --input: the trackpad sits on the native keyboard and pointer's hub" + } } } } diff --git a/crates/stela-boot-core/src/options/parse.rs b/crates/stela-boot-core/src/options/parse.rs index d6353d12cc..633ce116a0 100644 --- a/crates/stela-boot-core/src/options/parse.rs +++ b/crates/stela-boot-core/src/options/parse.rs @@ -187,6 +187,12 @@ impl ParseState<'_> { options.timer_delay = Some(micros); } "--input" => options.input = true, + TRACKPAD => { + let kind = GuestTrackpad::parse(value().ok_or(Error::Trackpad)?)?; + if options.trackpad.replace(kind).is_some() { + return Err(Error::DuplicateTrackpad); + } + } "--usb-storage" => { let serial = value().ok_or(Error::MissingUsbStorage)?; if options.usb_storage.iter().any(|other| other == serial) { diff --git a/crates/stela-boot-core/src/options/tests.rs b/crates/stela-boot-core/src/options/tests.rs index 94eaa71876..18a7976b6c 100644 --- a/crates/stela-boot-core/src/options/tests.rs +++ b/crates/stela-boot-core/src/options/tests.rs @@ -57,6 +57,60 @@ fn native_pci_ioapic_handoff_round_trips_and_refuses_diagnostic_paths() { use alloc::{format, string::ToString, vec}; +#[test] +fn the_trackpad_is_cabled_only_beside_host_input() { + // The disk-port count and the cabling both read this: no port is kept + // for a trackpad there is no host input to cable. + let cabled = System { + input: true, + trackpad: Some(GuestTrackpad::Mt2), + ..System::default() + }; + assert_eq!(cabled.guest_trackpad(), Some(GuestTrackpad::Mt2)); + let no_input = System { + input: false, + ..cabled.clone() + }; + assert_eq!(no_input.guest_trackpad(), None); + let no_flag = System { + trackpad: None, + ..cabled + }; + assert_eq!(no_flag.guest_trackpad(), None); +} + +#[test] +fn options_round_trip_trackpad() { + for (word, kind) in [ + ("mt2", GuestTrackpad::Mt2), + ("builtin", GuestTrackpad::Builtin), + ] { + let text = format!("--system --input --trackpad {word}"); + let options = System::parse(&text).unwrap(); + assert_eq!(options.trackpad, Some(kind)); + assert_eq!(options.to_string(), text); + assert_eq!(System::parse(&options.to_string()), Ok(options)); + } + // Without the flag: no trackpad, and the line has no word for it. + let plain = System::parse("--system --input").unwrap(); + assert_eq!(plain.trackpad, None); + assert_eq!(plain.to_string(), "--system --input"); + for (text, error) in [ + ("--system --input --trackpad nope", Error::Trackpad), + ("--system --input --trackpad", Error::Trackpad), + ( + "--system --input --trackpad mt2 --trackpad builtin", + Error::DuplicateTrackpad, + ), + ( + "--system --trackpad mt2", + Error::Constraint(Constraint::TrackpadDependency), + ), + ] { + assert_eq!(System::parse(text).unwrap_err(), error, "{text}"); + } +} + #[test] fn diagnostic_options_are_typed() { for text in ["--system", "--system --wifi --audio-own-hpet"] { diff --git a/crates/stela-boot-core/src/options/validate.rs b/crates/stela-boot-core/src/options/validate.rs index e5423a03ff..47f12f818d 100644 --- a/crates/stela-boot-core/src/options/validate.rs +++ b/crates/stela-boot-core/src/options/validate.rs @@ -21,6 +21,9 @@ pub(super) fn system(options: &System) -> Result<(), Error> { { return Err(Error::Constraint(Constraint::NativePciIoapicExclusive)); } + if options.trackpad.is_some() && !options.input { + return Err(Error::Constraint(Constraint::TrackpadDependency)); + } Ok(()) } diff --git a/crates/stela-boot/Cargo.toml b/crates/stela-boot/Cargo.toml index f69e2bb719..d516f170ef 100644 --- a/crates/stela-boot/Cargo.toml +++ b/crates/stela-boot/Cargo.toml @@ -53,7 +53,8 @@ stela-formats = { path = "../stela-formats", default-features = false } uefi = { version = "0.41", default-features = false, features = ["alloc"] } stela-boot-core = { path = "../stela-boot-core", features = ["native-acpi"] } stela-drivers = { path = "../stela-drivers", features = ["native-acpi", "nouveau-port"] } -stela-soc = { path = "../stela-soc", default-features = false } +# stela.efi alone carries the GPL-2.0-only Magic Trackpad 2 model. +stela-soc = { path = "../stela-soc", default-features = false, features = ["trackpad"] } stela-mesa = { path = "../stela-mesa", optional = true } stela-runtime = { path = "../stela-runtime", default-features = false } stela-loader = { path = "../stela-loader", default-features = false } diff --git a/crates/stela-boot/src/engine/input.rs b/crates/stela-boot/src/engine/input.rs index 8cf7db85c5..7740f65e2d 100644 --- a/crates/stela-boot/src/engine/input.rs +++ b/crates/stela-boot/src/engine/input.rs @@ -30,11 +30,33 @@ //! guest has one keyboard and one pointer for all host devices, so each //! device's keys and buttons are kept apart and joined: a touchpad's report //! does not let go of a mouse's drag, nor one keyboard's Shift the other's. +//! +//! With `--trackpad`, every precision touchpad gives whole frames for the +//! guest's emulated Magic Trackpad 2 instead of moving its mouse +//! ([`HostInput::trackpad`]); what the guest asks of the trackpad is +//! logged as `TRACKPAD` lines when inputs are delivered. use super::storage::{Inputs, RestoreRoot}; use crate::output; use alloc::vec::Vec; -use stela_drivers::input::{HeldInputs, Input, InputDevice}; +use stela_boot_core::options::GuestTrackpad; +use stela_drivers::input::{HeldInputs, Input, InputDevice, multitouch::Surface}; use stela_soc::machine::AppleDevices; +use stela_soc::usb::trackpad::{self, Identity}; + +/// The surface the guest trackpad maps without a precision touchpad: the +/// Magic Trackpad 2's own, 160.00 by 114.90 mm (hid-magicmouse.c +/// `TRACKPAD2_DIMENSION_X`/`_Y`). +const MT2_SURFACE: Surface = Surface { + width_um: 160_000, + height_um: 114_900, +}; + +// stela.efi carries the Magic Trackpad 2 model `--trackpad` cables: +// stela-soc's `trackpad` feature, set in crates/stela-boot/Cargo.toml. +const _: () = assert!( + stela_soc::usb::TRACKPAD, + "stela.efi needs stela-soc's trackpad feature" +); /// What was reported of one device, each kind once, and when it was read. #[derive(Clone, Default)] @@ -137,6 +159,18 @@ pub struct HostInput { held: HeldInputs, /// The next device's identity. next_id: u64, + /// `--trackpad`: precision touchpads give whole frames. + touch_frames: bool, + /// Whether the guest trackpad maps a host touchpad's surface, not the + /// MT2's own it was cabled with when none was there. + trackpad_surface: bool, + /// A touchpad's surface that arrived after the cabling, for the guest + /// trackpad at the next delivery. + new_surface: Option, + /// The guest trackpad's counters at the last `TRACKPAD frames` line, + /// and the counter then. + trackpad_seen: trackpad::Counters, + trackpad_reported: u64, } impl HostInput { @@ -164,11 +198,67 @@ impl HostInput { wanted_leds: None, reported_times: 0, held: HeldInputs::new(), + touch_frames: false, + trackpad_surface: false, + new_surface: None, + trackpad_seen: trackpad::Counters::default(), + trackpad_reported: 0, + } + } + + /// `--trackpad`: switch every precision touchpad to frames mode, now + /// and as they arrive, and the guest trackpad they feed: the first + /// one's surface, else the Magic Trackpad 2's own until one arrives. + pub fn trackpad(&mut self, kind: GuestTrackpad) -> trackpad::Config { + self.touch_frames = true; + let mut surface = None; + for device in &mut self.inputs.devices { + surface = surface.or(frames(device)); + } + self.trackpad_surface = surface.is_some(); + let identity = match kind { + GuestTrackpad::Mt2 => Identity::MagicTrackpad2, + GuestTrackpad::Builtin => Identity::Builtin, + }; + match surface { + Some(surface) => output::arguments(format_args!( + "TRACKPAD surface {}, as 05ac:{:04x} ({})\n", + Millimetres(surface), + identity.product(), + kind.name() + )), + None => output::arguments(format_args!( + "TRACKPAD no precision touchpad yet: the guest trackpad, as 05ac:{:04x} ({}), \ + spans the MT2's own {} until one arrives\n", + identity.product(), + kind.name(), + Millimetres(MT2_SURFACE) + )), + } + trackpad::Config { + identity, + surface: surface.unwrap_or(MT2_SURFACE), } } /// Read `devices` too from now on: keyboards and pointers that arrived. - pub fn add(&mut self, devices: Vec) { + /// With `--trackpad` a precision touchpad among them gives frames, and + /// the first, when the guest trackpad spans the MT2's own size, gives + /// it its surface at the next delivery. + pub fn add(&mut self, mut devices: Vec) { + if self.touch_frames { + for device in &mut devices { + if let Some(surface) = frames(device) + && !core::mem::replace(&mut self.trackpad_surface, true) + { + output::arguments(format_args!( + "TRACKPAD surface {} from the touchpad that arrived\n", + Millimetres(surface) + )); + self.new_surface = Some(surface); + } + } + } for device in devices { output::arguments(format_args!("INPUT host device {}\n", device.name())); self.inputs.devices.push(device); @@ -194,10 +284,51 @@ impl HostInput { /// Deliver what [`Self::read`] read from the host's devices, and note /// the guest's lock-key LEDs for the next read to send. pub fn deliver_all(&mut self, devices: &mut AppleDevices, inputs: Vec) { + if let Some(surface) = self.new_surface.take() { + devices.set_trackpad_surface(surface); + } for input in inputs { self.deliver(devices, input); } self.wanted_leds = devices.keyboard_leds(); + if self.touch_frames { + self.report_trackpad(devices); + } + } + + /// `TRACKPAD` lines: each of the guest trackpad's trace entries, and + /// once per [`TIMES_SECONDS`] its frames since the last line, with the + /// pad's rate by the frames' own scan times. + fn report_trackpad(&mut self, devices: &mut AppleDevices) { + for event in devices.trackpad_trace() { + output::arguments(format_args!("TRACKPAD {event}\n")); + } + let now = super::host::fresh_counter(); + if now.wrapping_sub(self.trackpad_reported) < super::host::COUNTER_HZ * TIMES_SECONDS { + return; + } + self.trackpad_reported = now; + let Some(counters) = devices.trackpad_counters() else { + return; + }; + let seen = core::mem::replace(&mut self.trackpad_seen, counters); + let received = counters.received.saturating_sub(seen.received); + if received == 0 { + return; + } + let reporting_us = counters.reporting_us.saturating_sub(seen.reporting_us); + let rate = match reporting_us { + 0 => 0, + us => received.saturating_mul(1_000_000) / us, + }; + output::arguments(format_args!( + "TRACKPAD frames received={received} sent={} coalesced={} dropped={} rate={rate} Hz \ + over {} ms of touch\n", + counters.sent.saturating_sub(seen.sent), + counters.coalesced.saturating_sub(seen.coalesced), + counters.dropped.saturating_sub(seen.dropped), + reporting_us / 1000, + )); } /// Read the host's input devices, without the guest's devices, in the @@ -411,6 +542,27 @@ impl HostInput { } } +/// Set `device` to give whole frames if it is a precision touchpad, logging +/// it: its surface, else `None`. +fn frames(device: &mut InputDevice) -> Option { + if !device.set_touch_frames(true) { + return None; + } + output::arguments(format_args!("TRACKPAD frames from {}\n", device.name())); + device.touch_surface() +} + +/// A surface as `W.WW x H.HH mm`. +struct Millimetres(Surface); + +impl core::fmt::Display for Millimetres { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mm = |um: u32| (um / 1000, um % 1000 / 10); + let ((w, w_frac), (h, h_frac)) = (mm(self.0.width_um), mm(self.0.height_um)); + write!(f, "{w}.{w_frac:02} x {h}.{h_frac:02} mm") + } +} + /// Why a device stopped, for its removal's line: the cause the device /// holds, else its last polling failure, else that neither is known. /// Whether `device` is a laptop's own: its i8042 keyboard or touchpad, an diff --git a/crates/stela-boot/src/engine/start.rs b/crates/stela-boot/src/engine/start.rs index f71faac2b8..ebf8a975e2 100644 --- a/crates/stela-boot/src/engine/start.rs +++ b/crates/stela-boot/src/engine/start.rs @@ -994,7 +994,7 @@ fn run_guest(boot: Boot<'_>, mut host: OpenedHost, mut storage: Storage) -> ! { acpi: host_acpi, devices: HostDevices { - host_input, + mut host_input, host_usb, host_bluetooth, host_network, @@ -1142,6 +1142,10 @@ fn run_guest(boot: Boot<'_>, mut host: OpenedHost, mut storage: Storage) -> ! { usb_disks, guest_mac: guest_network.as_ref().map(network::GuestNetwork::mac), guest_bluetooth: host_bluetooth.as_ref().map(bluetooth::HostBluetooth::kind), + // As the disk-port count below reads it: only with host input. + guest_trackpad: options + .guest_trackpad() + .and_then(|kind| Some(host_input.as_mut()?.trackpad(kind))), }, board.as_ref(), &core_locks, @@ -1691,6 +1695,7 @@ struct Placement<'a> { usb_disks: Vec>, guest_mac: Option, guest_bluetooth: Option, + guest_trackpad: Option, } /// The placed devices, the USB port a restore drives, and whether guest @@ -1830,6 +1835,7 @@ fn place_devices( network: placement.guest_mac, bluetooth: placement.guest_bluetooth, system_control: options.lid_sleep, + trackpad: placement.guest_trackpad, }, scanout, firmware: &firmware, @@ -3220,8 +3226,12 @@ fn start_devices( let owned_wifi = wifi_network(handoff, options); let owned_writes = disk_writes(handoff); let external = options.external_disks.then(|| { - stela_soc::machine::UsbCables::disk_ports(options.guest_network, options.input) - .saturating_sub(owned_usb.len()) + stela_soc::machine::UsbCables::disk_ports( + options.guest_network, + options.input, + options.guest_trackpad().is_some(), + ) + .saturating_sub(owned_usb.len()) }); let root = handoff.root; let heap = handoff.heap.physical..handoff.heap.physical + handoff.heap.bytes; diff --git a/crates/stela-cli/Cargo.toml b/crates/stela-cli/Cargo.toml index 644ac06855..00e5be9615 100644 --- a/crates/stela-cli/Cargo.toml +++ b/crates/stela-cli/Cargo.toml @@ -20,6 +20,11 @@ path = "src/main.rs" # built with amdgpu (`cargo xtask boot build --amdgpu` or `--radv`); a # release leaves both out. amdgpu-port = ["stela-loader/amdgpu-port"] +# Set only by `--all-features` gates (`cargo xtask check`), whose feature +# unification gives stela-soc its `trackpad` here; it lifts the build's +# refusal of a stela-soc with the GPL-2.0-only trackpad (src/lib.rs). A +# shipped CLI (`xtask dist`, `-p stela-cli`) never sets it. +workspace-check = [] [dependencies] stela-gpu-maintenance.workspace = true diff --git a/crates/stela-cli/src/lib.rs b/crates/stela-cli/src/lib.rs index f1881f6eb7..8302b3a5df 100644 --- a/crates/stela-cli/src/lib.rs +++ b/crates/stela-cli/src/lib.rs @@ -18,6 +18,18 @@ mod setup; pub use setup::InstallMedium; +// The CLI is GPL-3.0-or-later and links stela-soc, so it must not carry +// stela-soc's GPL-2.0-only Magic Trackpad 2 model, which only stela.efi +// enables (the `trackpad` feature, set in crates/stela-boot/Cargo.toml). +// An `--all-features` gate (`cargo xtask check`) unifies that feature into +// this crate and sets `workspace-check` beside it; a shipped build +// (`xtask dist`, `-p stela-cli`) sets neither. +#[cfg(not(feature = "workspace-check"))] +const _: () = assert!( + !stela_soc::usb::TRACKPAD, + "the stela CLI must not link stela-soc's GPL-2.0-only trackpad" +); + /// The help's examples, with this computer's spelling of a whole disk. fn examples() -> String { let disk = setup::host::DISK_EXAMPLE; diff --git a/crates/stela-drivers/src/input.rs b/crates/stela-drivers/src/input.rs index 7018031ada..387a612097 100644 --- a/crates/stela-drivers/src/input.rs +++ b/crates/stela-drivers/src/input.rs @@ -9,9 +9,11 @@ pub mod elan; mod held; pub mod hid_i2c; pub mod ish; +pub mod multitouch; pub mod observation; pub mod ps2; pub mod ptp; +pub mod ptp_frames; pub mod rmi; pub mod sfh; pub mod touchpad; @@ -66,6 +68,9 @@ pub enum Input { MouseWheel(i8), /// Mouse horizontal wheel (AC Pan) detents, positive right. MouseHWheel(i8), + /// A precision touchpad's whole frame, for a guest multitouch device + /// ([`multitouch`]); only a touchpad in frames mode gives one. + Touch(multitouch::Frame), } #[cfg(test)] diff --git a/crates/stela-drivers/src/input/device.rs b/crates/stela-drivers/src/input/device.rs index 8d1be519fe..6c0497f8d4 100644 --- a/crates/stela-drivers/src/input/device.rs +++ b/crates/stela-drivers/src/input/device.rs @@ -120,6 +120,24 @@ impl InputDevice { } } + /// Set frames mode on an I²C-HID precision touchpad: whole contact + /// frames ([`Input::Touch`]) in place of mouse motion. Whether the + /// device is one; every other device is left as it is. + pub fn set_touch_frames(&mut self, on: bool) -> bool { + match self { + Self::I2cHid(device) => device.set_touch_frames(on), + _ => false, + } + } + + /// The surface an I²C-HID precision touchpad's frames span. + pub fn touch_surface(&self) -> Option { + match self { + Self::I2cHid(device) => device.touch_surface(), + _ => None, + } + } + /// Show `leds` on the device's keyboard LEDs: bit 0 Num Lock, bit 1 /// Caps Lock, bit 2 Scroll Lock, then the other input LED codes. A /// device without LEDs ignores it. diff --git a/crates/stela-drivers/src/input/held.rs b/crates/stela-drivers/src/input/held.rs index 27e9eeea03..8b49dacb14 100644 --- a/crates/stela-drivers/src/input/held.rs +++ b/crates/stela-drivers/src/input/held.rs @@ -17,6 +17,9 @@ struct Held { /// ([`Input::MouseButtons`]), as the device last reported them. buttons: u8, mouse_buttons: u8, + /// While the last touch frame ([`Input::Touch`]) held a contact or a + /// button: its time. + touch: Option, } impl Held { @@ -36,6 +39,7 @@ impl Held { } Input::Buttons(buttons) => self.buttons = buttons, Input::MouseButtons(buttons) => self.mouse_buttons = buttons, + Input::Touch(frame) => self.touch = frame.holds().then_some(frame.time_us), _ => {} } } @@ -59,6 +63,11 @@ impl Held { if self.mouse_buttons != 0 { out.push(Input::MouseButtons(0)); } + // A touchpad's frames are its own surface: nothing to join with + // another device's. + if let Some(time_us) = self.touch { + out.push(Input::Touch(super::multitouch::Frame::lifted(time_us))); + } } } diff --git a/crates/stela-drivers/src/input/hid_i2c.rs b/crates/stela-drivers/src/input/hid_i2c.rs index 18e6d88780..6dda463a1e 100644 --- a/crates/stela-drivers/src/input/hid_i2c.rs +++ b/crates/stela-drivers/src/input/hid_i2c.rs @@ -833,6 +833,17 @@ impl HidInput { self.ptp.is_some() } + /// Set a precision touchpad's frames mode ([`ptp::Ptp::set_frames`]); + /// whether the device is one. + pub fn set_touch_frames(&mut self, on: bool) -> bool { + self.ptp.as_mut().map(|ptp| ptp.set_frames(on)).is_some() + } + + /// The surface a precision touchpad's frames span. + pub fn touch_surface(&self) -> Option { + self.ptp.as_ref().map(ptp::Ptp::surface) + } + pub fn device(&self) -> &Device { &self.device } diff --git a/crates/stela-drivers/src/input/hid_i2c/tests.rs b/crates/stela-drivers/src/input/hid_i2c/tests.rs index 5c9a6820f8..0555486d32 100644 --- a/crates/stela-drivers/src/input/hid_i2c/tests.rs +++ b/crates/stela-drivers/src/input/hid_i2c/tests.rs @@ -3,6 +3,7 @@ use super::*; use alloc::{collections::VecDeque, rc::Rc, vec}; use core::cell::{Cell, RefCell}; +mod frames; mod minimum; mod ownership; mod polled; diff --git a/crates/stela-drivers/src/input/hid_i2c/tests/frames.rs b/crates/stela-drivers/src/input/hid_i2c/tests/frames.rs new file mode 100644 index 0000000000..e021478c91 --- /dev/null +++ b/crates/stela-drivers/src/input/hid_i2c/tests/frames.rs @@ -0,0 +1,63 @@ +//! A precision touchpad's frames mode through the I²C-HID input. +use super::*; +use crate::input::{ + multitouch::Surface, + ptp::tests::{EMPTY, descriptor as touchpad_descriptor, report}, +}; + +#[test] +fn a_precision_touchpad_passes_frames_through_on_request() { + let (mut d, h) = device(0x04f3, 0x32e2); + { + let mut h = h.borrow_mut(); + h.report_desc = touchpad_descriptor(); + // wReportDescLength; the reports fit wMaxInputLength's 32 bytes. + let length = h.report_desc.len() as u16; + h.desc[4..6].copy_from_slice(&length.to_le_bytes()); + } + d.initialize().unwrap(); + let mut input = HidInput::new(d, String::from("pad")).unwrap(); + assert!(input.is_precision_touchpad()); + assert_eq!( + input.touch_surface(), + Some(Surface { + width_um: 100_000, + height_um: 60_000 + }) + ); + let feed = |input: &mut HidInput<_, _, _>, bytes: Vec| { + h.borrow_mut().input.push_back(Hardware::frame(&bytes)); + let mut inputs = Vec::new(); + input.poll(&mut inputs).unwrap(); + inputs + }; + // The mouse path until frames mode is set: a finger moving 10 mm is + // motion. + feed( + &mut input, + report([(true, true, 1, 500, 300), EMPTY], 10, 1, false), + ); + let moved = feed( + &mut input, + report([(true, true, 1, 600, 300), EMPTY], 20, 1, false), + ); + assert!(matches!(moved[..], [Input::Motion { .. }]), "{moved:?}"); + assert!(input.set_touch_frames(true)); + let frames = feed( + &mut input, + report([(true, true, 1, 700, 300), EMPTY], 30, 1, false), + ); + let [Input::Touch(frame)] = frames[..] else { + panic!("{frames:?}"); + }; + assert_eq!(frame.fingers()[0].x_um, 70_000); +} + +#[test] +fn another_device_has_no_frames_mode() { + let (d, _h) = ready(); + let mut input = HidInput::new(d, String::from("vendor")).unwrap(); + assert!(!input.is_precision_touchpad()); + assert!(!input.set_touch_frames(true)); + assert_eq!(input.touch_surface(), None); +} diff --git a/crates/stela-drivers/src/input/multitouch.rs b/crates/stela-drivers/src/input/multitouch.rs new file mode 100644 index 0000000000..6b4a8d3c27 --- /dev/null +++ b/crates/stela-drivers/src/input/multitouch.rs @@ -0,0 +1,82 @@ +//! Whole multi-contact touch frames ([`Frame`]): every contact a +//! precision touchpad lists in one scan, in micrometres from its top-left +//! corner, with its buttons and the scan's time. A consumer that models a +//! multitouch device (the guest's Magic Trackpad 2) needs the contacts +//! themselves; the mouse path ([`super::touchpad`]) flattens them to one +//! point. Positions in micrometres let a consumer place them knowing only +//! the pad's [`Surface`], not its units. +//! +//! A frame lists the contacts of one scan only: a contact left out of the +//! next frame lifted, and one listed with its tip up is lifting. + +/// The contacts one frame holds at most. +pub const MAX_FINGERS: usize = 10; + +/// One contact of a frame. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Finger { + /// The pad's contact identifier: the same contact keeps it from + /// landing to lifting. + pub id: u8, + /// From the pad's top-left corner, y downward. + pub x_um: u32, + pub y_um: u32, + /// Touching the surface (HID Tip Switch). + pub tip: bool, + /// The pad takes the contact for a finger; `false` for a palm or + /// another large contact (HID Confidence). + pub confident: bool, +} + +/// One scan's contacts, buttons and time. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Frame { + /// When the pad scanned it, in microseconds of a clock that only runs + /// forward. + pub time_us: u64, + /// The pad's buttons held, button 1 in bit 0. + pub buttons: u8, + count: u8, + fingers: [Finger; MAX_FINGERS], +} + +impl Frame { + /// A frame of `fingers`' first [`MAX_FINGERS`], in their order. + pub fn new(time_us: u64, buttons: u8, fingers: &[Finger]) -> Self { + let count = fingers.len().min(MAX_FINGERS); + let mut held = [Finger::default(); MAX_FINGERS]; + held[..count].copy_from_slice(&fingers[..count]); + Self { + time_us, + buttons, + count: count as u8, + fingers: held, + } + } + + /// Nothing on the pad and no button held: what a device that stopped + /// leaves. + pub fn lifted(time_us: u64) -> Self { + Self::new(time_us, 0, &[]) + } + + pub fn fingers(&self) -> &[Finger] { + &self.fingers[..usize::from(self.count)] + } + + /// Whether the frame holds anything down: a contact touching, or a + /// button. + pub fn holds(&self) -> bool { + self.buttons != 0 || self.fingers().iter().any(|finger| finger.tip) + } +} + +/// The size of a pad's surface: the extent its contacts' positions span. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Surface { + pub width_um: u32, + pub height_um: u32, +} + +#[cfg(test)] +mod tests; diff --git a/crates/stela-drivers/src/input/multitouch/tests.rs b/crates/stela-drivers/src/input/multitouch/tests.rs new file mode 100644 index 0000000000..13f6815060 --- /dev/null +++ b/crates/stela-drivers/src/input/multitouch/tests.rs @@ -0,0 +1,73 @@ +use super::*; +use crate::input::{HeldInputs, Input}; +use alloc::vec::Vec; + +fn finger(id: u8, tip: bool) -> Finger { + Finger { + id, + x_um: 1000 * u32::from(id), + y_um: 500, + tip, + confident: true, + } +} + +#[test] +fn frame_keeps_ten_fingers_in_order() { + let twelve: Vec = (0..12).map(|id| finger(id, true)).collect(); + let frame = Frame::new(7, 1, &twelve); + assert_eq!(frame.fingers().len(), MAX_FINGERS); + assert_eq!( + frame.fingers().iter().map(|f| f.id).collect::>(), + (0..10).collect::>() + ); + assert_eq!((frame.time_us, frame.buttons), (7, 1)); + let lifted = Frame::lifted(9); + assert!(lifted.fingers().is_empty()); + assert_eq!((lifted.time_us, lifted.buttons), (9, 0)); + assert!(!lifted.holds()); +} + +#[test] +fn held_releases_a_touch() { + // A finger down, then the device stops: one lifted frame at the last + // frame's time. + let mut held = HeldInputs::new(); + let mut inputs = alloc::vec![Input::Touch(Frame::new(1_000, 0, &[finger(0, true)]))]; + held.polled(3, &mut inputs, 0); + let mut out = Vec::new(); + held.stopped(3, &mut out); + assert_eq!(out, [Input::Touch(Frame::lifted(1_000))]); + out.clear(); + held.stopped(3, &mut out); + assert!(out.is_empty(), "once"); + // Button 1 held with no finger listed. + let mut inputs = alloc::vec![Input::Touch(Frame::new(2_000, 1, &[]))]; + held.polled(4, &mut inputs, 0); + held.stopped(4, &mut out); + assert_eq!(out, [Input::Touch(Frame::lifted(2_000))]); + // A touch that lifted holds nothing. + out.clear(); + let mut inputs = alloc::vec![ + Input::Touch(Frame::new(3_000, 0, &[finger(0, true)])), + Input::Touch(Frame::new(3_008, 0, &[finger(0, false)])), + ]; + held.polled(5, &mut inputs, 0); + held.stopped(5, &mut out); + assert!(out.is_empty()); +} + +#[test] +fn a_touch_passes_through_beside_another_device_s_buttons() { + let mut held = HeldInputs::new(); + let mut mouse = alloc::vec![Input::MouseButtons(1)]; + held.polled(0, &mut mouse, 0); + let frame = Frame::new(5, 0, &[finger(1, true)]); + let mut pad = alloc::vec![Input::Touch(frame)]; + held.polled(1, &mut pad, 0); + assert_eq!(pad, [Input::Touch(frame)]); + // The pad stops: its touch lifts, the mouse's button stays. + let mut out = Vec::new(); + held.stopped(1, &mut out); + assert_eq!(out, [Input::Touch(Frame::lifted(5))]); +} diff --git a/crates/stela-drivers/src/input/ptp.rs b/crates/stela-drivers/src/input/ptp.rs index 3cf6fc6297..cb95704d4a 100644 --- a/crates/stela-drivers/src/input/ptp.rs +++ b/crates/stela-drivers/src/input/ptp.rs @@ -13,9 +13,13 @@ //! 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. +//! of a frame, so a contact left out of a frame is lifted. In frames mode +//! ([`Ptp::set_frames`]) each frame goes out whole instead +//! ([`super::ptp_frames`]). use super::{ Input, + multitouch::Surface, + ptp_frames, touchpad::{Axis, Geometry, Touch, Translator}, }; use crate::usb::hid::{ @@ -31,6 +35,7 @@ const FINGER: u32 = 0x000d_0022; const INPUT_MODE: u32 = 0x000d_0052; const SURFACE_SWITCH: u32 = 0x000d_0057; const BUTTON_SWITCH: u32 = 0x000d_0058; +const SCAN_TIME: u32 = 0x000d_0056; const X: u32 = 0x0001_0030; const Y: u32 = 0x0001_0031; const BUTTON_1: u32 = 0x0009_0001; @@ -118,6 +123,8 @@ pub struct Profile { application: usize, geometry: Geometry, modes: Vec, + /// The fields' ranges and size as frames mode reads them. + scale: ptp_frames::Scale, } impl Profile { @@ -142,6 +149,13 @@ impl Profile { }) }; let (x, y) = (field(X)?, field(Y)?); + let scan = descriptor + .reports + .iter() + .filter(|report| report.kind == ReportType::Input) + .flat_map(|report| report.fields.iter()) + .find(|field| field.usages.contains(&SCAN_TIME) && is(field.collection, TOUCH_PAD)); + let scale = ptp_frames::Scale::of(x, y, scan); let application = application(descriptor, x.collection)?; let (x_range, x_axis) = axis(x); let (y_range, y_axis) = axis(y); @@ -193,6 +207,7 @@ impl Profile { application, geometry: Geometry::new((x_range, y_range), x_axis, y_axis), modes, + scale, }) } @@ -220,6 +235,11 @@ impl Profile { pub fn geometry(&self) -> Geometry { self.geometry } + + /// The surface the pad states, to the micrometre. + pub fn surface(&self) -> Option { + self.scale.stated() + } } /// A precision touchpad in touchpad mode. @@ -229,6 +249,8 @@ pub struct Ptp { /// The contacts the frame being assembled expects, and those it has. expected: usize, received: Vec, + /// In frames mode, the pad's scan clock. + frames: Option, } impl Ptp { @@ -238,9 +260,21 @@ impl Ptp { profile, expected: 0, received: Vec::new(), + frames: None, } } + /// Frames mode: each frame goes out whole as [`Input::Touch`], in + /// place of the translator's motion, scrolling and taps, never both. + pub fn set_frames(&mut self, on: bool) { + self.frames = on.then(ptp_frames::Clock::default); + } + + /// The surface the frames' positions span. + pub fn surface(&self) -> Surface { + self.profile.scale.surface() + } + /// 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. @@ -293,6 +327,15 @@ impl Ptp { } // A complete frame, or a count of 0 with no frame pending: a // report of buttons alone, with no finger on the pad. + if let Some(clock) = &mut self.frames { + let scale = &self.profile.scale; + let time_us = clock.time_us(packet.scan_time, scale.scan_max(), now_us); + let frame = ptp_frames::frame(&self.received, buttons, time_us, scale); + inputs.push(Input::Touch(frame)); + self.received.clear(); + self.expected = 0; + return; + } let mut fingers: Vec<_> = self .received .drain(..) @@ -315,4 +358,4 @@ impl Ptp { } #[cfg(test)] -mod tests; +pub(crate) mod tests; diff --git a/crates/stela-drivers/src/input/ptp/tests.rs b/crates/stela-drivers/src/input/ptp/tests.rs index 6444dc91d5..47d313163a 100644 --- a/crates/stela-drivers/src/input/ptp/tests.rs +++ b/crates/stela-drivers/src/input/ptp/tests.rs @@ -20,7 +20,7 @@ fn finger() -> Vec { ] } -fn descriptor() -> Vec { +pub(crate) fn descriptor() -> Vec { let mut d = vec![0x05, 0x0d, 0x09, 0x05, 0xa1, 0x01, 0x85, 0x01]; d.extend(finger()); d.extend(finger()); @@ -44,9 +44,9 @@ fn descriptor() -> Vec { } /// One finger slot: (confidence, tip, id, x, y). -type Slot = (bool, bool, u8, u16, u16); +pub(crate) type Slot = (bool, bool, u8, u16, u16); -fn report(slots: [Slot; 2], scan: u16, count: u8, button: bool) -> Vec { +pub(crate) fn report(slots: [Slot; 2], scan: u16, count: u8, button: bool) -> Vec { let mut r = vec![0x01]; for (confidence, tip, id, x, y) in slots { r.push(u8::from(confidence) | u8::from(tip) << 1); @@ -60,15 +60,15 @@ fn report(slots: [Slot; 2], scan: u16, count: u8, button: bool) -> Vec { r } -const EMPTY: Slot = (false, false, 0, 0, 0); +pub(crate) const EMPTY: Slot = (false, false, 0, 0, 0); -struct Pad { +pub(crate) struct Pad { translator: Translator, - ptp: Ptp, + pub(crate) ptp: Ptp, } impl Pad { - fn new() -> Self { + pub(crate) fn new() -> Self { let translator = Translator::describe(&descriptor()).unwrap(); let profile = Profile::select(translator.descriptor().unwrap()).unwrap(); Self { @@ -77,7 +77,7 @@ impl Pad { } } - fn feed(&mut self, bytes: &[u8], now_us: u64) -> Vec { + pub(crate) fn feed(&mut self, bytes: &[u8], now_us: u64) -> Vec { let mut events = Vec::new(); let mut inputs = Vec::new(); let Translated::Data(frame) = self.translator.translate(bytes, &mut events, &mut inputs) diff --git a/crates/stela-drivers/src/input/ptp_frames.rs b/crates/stela-drivers/src/input/ptp_frames.rs new file mode 100644 index 0000000000..00972892fa --- /dev/null +++ b/crates/stela-drivers/src/input/ptp_frames.rs @@ -0,0 +1,185 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Linux hid-multitouch.c reference: Copyright (c) 2010-2012 Stephane +// Chatty, Benjamin Tissoires and Ecole Nationale de l'Aviation Civile. +// See NOTICE. +//! A precision touchpad's whole frames ([`Input::Touch`]) for a guest that +//! models a multitouch device, in place of the mouse path's motion +//! ([`super::ptp`] in frames mode). +//! +//! Each contact goes into the frame as the pad listed it, a palm +//! (Confidence 0) included: Linux hid-multitouch keeps such a contact as +//! `MT_TOOL_PALM` (`mt_process_slot`), and dropping it would read as a lift, +//! which a multitouch consumer takes for a tap. Positions are micrometres +//! from the pad's top-left corner over its [`Surface`], kept exact to the +//! micrometre (126.90 mm stays 126 900 µm, where the mouse path's +//! [`super::touchpad::Geometry`] rounds to whole millimetres). +//! +//! A frame's time follows the pad's Scan Time (100 µs units, HID Usage +//! Tables 16.3), unwrapped past its logical maximum, as hid-multitouch's +//! `mt_compute_timestamp` does, and resynchronized to the poll clock after a +//! gap longer than its `MAX_TIMESTAMP_INTERVAL` of one second. The host polls +//! in bursts, so poll times would put velocity noise into the frames. +//! A Scan Time counter of 0 to `max` wraps modulo `max + 1`; Linux adds +//! `max` itself, 100 µs short at each wrap. +use super::multitouch::{Finger, Frame, Surface}; +use crate::usb::hid::{descriptor::ReportField, events::Contact}; +use alloc::vec::Vec; + +/// hid-multitouch's `MAX_TIMESTAMP_INTERVAL`, in microseconds. +const MAX_GAP_US: u64 = 1_000_000; +/// Scan Time's unit. +const SCAN_UNIT_US: u64 = 100; +/// A Scan Time field's logical maximum when it states none: a 16-bit +/// counter, as the Windows precision touchpad requirement has it. +const SCAN_MAX: i64 = 0xffff; +/// libinput's assumed size of a pad that states none, as the mouse path +/// assumes it. +const ASSUMED: Surface = Surface { + width_um: 69_000, + height_um: 50_000, +}; + +/// The micrometres 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 micrometres(field: &ReportField) -> Option { + let extent = i128::from(field.physical_maximum) - i128::from(field.physical_minimum); + if extent <= 0 { + return None; + } + 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 { + // Rounded to the nearest micrometre. + let divisor = 10i128.checked_pow(exponent.unsigned_abs())?; + um = (um + divisor / 2) / divisor; + } + u32::try_from(um).ok().filter(|um| *um != 0) +} + +/// The surface the pad's X and Y fields span, when both state their size. +pub fn surface(x: &ReportField, y: &ReportField) -> Option { + Some(Surface { + width_um: micrometres(x)?, + height_um: micrometres(y)?, + }) +} + +/// What frames mode reads of a pad's fields: the logical ranges of X and Y, +/// the surface they span and Scan Time's maximum. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Scale { + x: (i64, i64), + y: (i64, i64), + stated: Option, + scan_max: i64, +} + +impl Scale { + /// The scale of a pad's finger X and Y fields and its Scan Time field. + pub fn of(x: &ReportField, y: &ReportField, scan: Option<&ReportField>) -> Self { + Self { + x: (x.minimum, x.maximum), + y: (y.minimum, y.maximum), + stated: surface(x, y), + scan_max: scan + .map(|field| field.maximum) + .filter(|max| *max > 0) + .unwrap_or(SCAN_MAX), + } + } + + /// The surface the pad states. + pub fn stated(&self) -> Option { + self.stated + } + + /// The surface the frames' positions span: the stated one, else + /// libinput's assumed 69 by 50 mm. + pub fn surface(&self) -> Surface { + self.stated.unwrap_or(ASSUMED) + } + + pub fn scan_max(&self) -> i64 { + self.scan_max + } + + /// `value` of the logical range `range` in micrometres of `extent`, + /// rounded to the nearest, clamped to the range. + fn position(value: i64, range: (i64, i64), extent: u32) -> u32 { + let (min, max) = range; + let span = i128::from(max) - i128::from(min); + if span <= 0 { + return 0; + } + let offset = (i128::from(value.clamp(min, max)) - i128::from(min)) * i128::from(extent); + ((offset + span / 2) / span) as u32 + } +} + +/// The pad's scan clock, read as frame times. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Clock { + /// The last frame's time, its Scan Time and the poll time it was read + /// at. + last: Option<(u64, Option, u64)>, +} + +impl Clock { + /// The time of a frame of Scan Time `scan` (0..=`scan_max`, if the pad + /// reports one) read at poll time `now_us`: the first frame's poll time, + /// then the last frame's plus the scan counter's advance, wrapping past + /// `scan_max`; a gap of more than a second between polls, or a frame + /// without a scan time, resynchronizes to the poll time. Never before + /// the last frame's time. + pub fn time_us(&mut self, scan: Option, scan_max: i64, now_us: u64) -> u64 { + let time = match (self.last, scan) { + (None, _) => now_us, + (Some((time, Some(last_scan), polled)), Some(scan)) + if now_us.saturating_sub(polled) <= MAX_GAP_US => + { + let period = i128::from(scan_max.max(1)) + 1; + let advance = (i128::from(scan) - i128::from(last_scan)).rem_euclid(period); + time.saturating_add(advance as u64 * SCAN_UNIT_US) + } + (Some((time, ..)), _) => now_us.max(time), + }; + self.last = Some((time, scan, now_us)); + time + } +} + +/// The frame of `contacts`, the pad's contacts of one scan in the order it +/// listed them, with `buttons` held at `time_us`. A contact without a +/// position is left out; one without an identifier takes its place in the +/// list as one; one without a confidence is confident. +pub fn frame(contacts: &[Contact], buttons: u8, time_us: u64, scale: &Scale) -> Frame { + let surface = scale.surface(); + let fingers: Vec = contacts + .iter() + .enumerate() + .filter_map(|(index, contact)| { + let (x, y) = (contact.x?, contact.y?); + Some(Finger { + // Contact identifiers fit a byte on every precision + // touchpad; a wider one keeps its low byte. + id: contact.id.map_or(index as u8, |id| id as u8), + x_um: Scale::position(x, scale.x, surface.width_um), + y_um: Scale::position(y, scale.y, surface.height_um), + tip: contact.tip == Some(true), + confident: contact.confidence != Some(false), + }) + }) + .collect(); + Frame::new(time_us, buttons, &fingers) +} + +#[cfg(test)] +mod tests; diff --git a/crates/stela-drivers/src/input/ptp_frames/tests.rs b/crates/stela-drivers/src/input/ptp_frames/tests.rs new file mode 100644 index 0000000000..2fc78bdc7c --- /dev/null +++ b/crates/stela-drivers/src/input/ptp_frames/tests.rs @@ -0,0 +1,216 @@ +use super::*; +use crate::input::{ + Input, + ptp::tests::{EMPTY, Pad, report}, +}; +use crate::usb::hid::descriptor::ReportField; +use alloc::{vec, vec::Vec}; + +fn touches(inputs: &[Input]) -> Vec { + inputs + .iter() + .map(|input| match input { + Input::Touch(frame) => *frame, + other => panic!("frames mode gave {other:?}"), + }) + .collect() +} + +fn frames_pad() -> Pad { + let mut pad = Pad::new(); + pad.ptp.set_frames(true); + pad +} + +/// An axis field of `maximum` units over `physical` in `unit` and +/// `exponent`. +fn axis(maximum: i64, physical: i64, unit: u32, exponent: i8) -> ReportField { + ReportField { + offset: 0, + size: 16, + count: 1, + flags: 2, + minimum: 0, + maximum, + physical_minimum: 0, + physical_maximum: physical, + unit, + unit_exponent: exponent, + collection: None, + usages: vec![0x0001_0030], + } +} + +#[test] +fn surface_is_micrometres() { + let pad = Pad::new(); + assert_eq!( + pad.ptp.surface(), + Surface { + width_um: 100_000, + height_um: 60_000 + } + ); + // The ELAN 04F3:32E2's X: 0..3987 over 12690 at 10^-3 cm, 126.90 mm, + // which whole millimetres would round to 127. + let x = axis(3987, 12690, 0x11, -3); + let y = axis(2579, 8200, 0x11, -3); + assert_eq!( + surface(&x, &y), + Some(Surface { + width_um: 126_900, + height_um: 82_000 + }) + ); + // English linear: 4 inches at 10^0 is 101.6 mm. + let inch = axis(1000, 4, 0x13, 0); + assert_eq!(surface(&inch, &inch).map(|s| s.width_um), Some(101_600)); + // No unit, or no physical range: no stated size, and libinput's assumed + // 69 by 50 mm for the frames. + let bare = axis(1000, 0, 0, 0); + assert_eq!(surface(&bare, &bare), None); + let scale = Scale::of(&bare, &bare, None); + assert_eq!(scale.stated(), None); + assert_eq!( + scale.surface(), + Surface { + width_um: 69_000, + height_um: 50_000 + } + ); + assert_eq!(scale.scan_max(), 0xffff); +} + +#[test] +fn frames_mode_emits_touch_not_motion() { + let mut pad = frames_pad(); + let first = report([(true, true, 1, 500, 300), EMPTY], 10, 1, false); + let moved = report([(true, true, 1, 600, 300), EMPTY], 20, 1, false); + let mut inputs = pad.feed(&first, 1_000_000); + inputs.extend(pad.feed(&moved, 1_001_000)); + let frames = touches(&inputs); + assert_eq!(frames.len(), 2, "one frame per report, nothing else"); + let at = |frame: &Frame| { + let f = frame.fingers()[0]; + (f.id, f.x_um, f.y_um, f.tip, f.confident) + }; + assert_eq!(at(&frames[0]), (1, 50_000, 30_000, true, true)); + assert_eq!(at(&frames[1]), (1, 60_000, 30_000, true, true)); + // The lift reaches the frame with its tip up; a button-only report is + // a frame of no contacts. + let lift = report([(true, false, 1, 600, 300), EMPTY], 30, 1, false); + let lifted = touches(&pad.feed(&lift, 1_002_000)); + assert_eq!(lifted[0].fingers().len(), 1); + assert!(!lifted[0].fingers()[0].tip); + let click = report([EMPTY, EMPTY], 40, 0, true); + let clicked = touches(&pad.feed(&click, 1_003_000)); + assert_eq!(clicked.len(), 1); + assert!(clicked[0].fingers().is_empty()); + assert_eq!(clicked[0].buttons, 1); +} + +#[test] +fn non_confident_contact_is_kept() { + let mut pad = frames_pad(); + // A palm, its whole life without confidence, beside a finger. + let palm = report( + [(false, true, 3, 100, 100), (true, true, 4, 900, 500)], + 5, + 2, + false, + ); + let frames = touches(&pad.feed(&palm, 0)); + let fingers = frames[0].fingers(); + assert_eq!(fingers.len(), 2); + assert_eq!( + (fingers[0].id, fingers[0].tip, fingers[0].confident), + (3, true, false) + ); + assert_eq!( + (fingers[1].id, fingers[1].tip, fingers[1].confident), + (4, true, true) + ); + assert_eq!((fingers[0].x_um, fingers[0].y_um), (10_000, 10_000)); +} + +#[test] +fn scan_time_drives_time() { + // Through the pad: scan 100 then 180 is 8 ms, whatever the polls say. + let mut pad = frames_pad(); + let one = report([(true, true, 1, 500, 300), EMPTY], 100, 1, false); + let two = report([(true, true, 1, 510, 300), EMPTY], 180, 1, false); + let a = touches(&pad.feed(&one, 1_000_000))[0].time_us; + let b = touches(&pad.feed(&two, 1_000_100))[0].time_us; + assert_eq!((a, b), (1_000_000, 1_008_000)); + // The counter wraps at 65535: 65500 to 30 is 66 counts. + let mut clock = Clock::default(); + assert_eq!(clock.time_us(Some(65_500), 0xffff, 5_000_000), 5_000_000); + assert_eq!(clock.time_us(Some(30), 0xffff, 5_000_200), 5_006_600); + // A second scan time within a frame of hybrid reports adds nothing. + assert_eq!(clock.time_us(Some(30), 0xffff, 5_000_300), 5_006_600); + // A poll gap over a second resynchronizes to the poll clock, which is + // past the scan clock here. + assert_eq!(clock.time_us(Some(40), 0xffff, 6_500_000), 6_500_000); + assert_eq!(clock.time_us(Some(50), 0xffff, 6_500_100), 6_501_000); + // A resync behind the scan clock keeps time from running back. + let mut fast = Clock::default(); + assert_eq!(fast.time_us(Some(0), 0xffff, 0), 0); + assert_eq!(fast.time_us(Some(60_000), 0xffff, 900_000), 6_000_000); + assert_eq!(fast.time_us(Some(0), 0xffff, 2_000_000), 6_000_000); + // A pad without Scan Time runs on the poll clock. + let mut bare = Clock::default(); + assert_eq!(bare.time_us(None, 0xffff, 10), 10); + assert_eq!(bare.time_us(None, 0xffff, 25), 25); +} + +#[test] +fn three_fingers_reach_the_frame() { + let mut pad = frames_pad(); + 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); + let frames = touches(&pad.feed(&rest, 10_000)); + assert_eq!(frames.len(), 1); + assert_eq!( + frames[0].fingers().iter().map(|f| f.id).collect::>(), + [1, 2, 3] + ); + assert_eq!(frames[0].buttons, 1); +} + +#[test] +fn frames_off_is_unchanged() { + // The same reports through a pad with frames mode set and cleared, and + // through one never set: the mouse path's inputs, identical. + let sequence = [ + (report([(true, true, 1, 100, 300), EMPTY], 10, 1, false), 0), + ( + report([(true, true, 1, 350, 300), EMPTY], 20, 1, false), + 300_000, + ), + ( + report([(true, true, 1, 350, 300), EMPTY], 30, 1, true), + 310_000, + ), + (report([EMPTY, EMPTY], 40, 0, false), 320_000), + ]; + let mut plain = Pad::new(); + let mut toggled = Pad::new(); + toggled.ptp.set_frames(true); + toggled.ptp.set_frames(false); + for (bytes, now) in &sequence { + let expected = plain.feed(bytes, *now); + assert!( + !expected + .iter() + .any(|input| matches!(input, Input::Touch(_))), + "no frame without frames mode" + ); + assert_eq!(toggled.feed(bytes, *now), expected); + } +} diff --git a/crates/stela-loader/src/mount_interface.rs b/crates/stela-loader/src/mount_interface.rs index d742f0858c..887051dbc7 100644 --- a/crates/stela-loader/src/mount_interface.rs +++ b/crates/stela-loader/src/mount_interface.rs @@ -44,7 +44,9 @@ pub const MARKER_BYTES: usize = MAGIC.len() + 4 * FIELDS; /// `--dns SERVERS` set the mount network's addresses by hand. Revision 12: /// `--usb4-approve UUID` admits a USB4 device's PCIe tunnel without an IOMMU. /// Revision 13: `--tss` is gone; every `--install` signs with Apple's -/// signing service. +/// signing service. The fork's `--trackpad mt2|builtin`, which cables an +/// emulated Magic Trackpad 2, is a hand-written opt-in setup never writes: +/// no line setup writes changes meaning, so it keeps revision 13. pub const OPTIONS_REVISION: u32 = 13; /// The startup choices, beside `stela.cfg` on the ESP. @@ -391,6 +393,14 @@ mod tests { use super::*; use alloc::vec; + #[test] + fn options_revision_stays_13_beside_the_hand_written_trackpad_option() { + // The fork's `--trackpad` is a hand-written opt-in setup never + // writes, so a revision-13 setup and this stela.efi still accept + // each other's interface. + assert_eq!(OPTIONS_REVISION, 13); + } + #[test] fn the_chosen_disk_stands_in_for_every_word_that_names_it() { let options = "--system --storage @disk --nor @disk --guest-network"; diff --git a/crates/stela-runtime/src/machine/mount.rs b/crates/stela-runtime/src/machine/mount.rs index 96f739e917..21a1e36fce 100644 --- a/crates/stela-runtime/src/machine/mount.rs +++ b/crates/stela-runtime/src/machine/mount.rs @@ -766,9 +766,15 @@ fn add_usbs( } else { "none" }; + let trackpad = if usb.trackpad.is_some() { + " trackpad=attached" + } else { + "" + }; devices.attach_input(controller.port, core::mem::take(&mut usb))?; log(format_args!( - "INPUT attached to USB-C port {} with {disks} USB disks, network={network}\n", + "INPUT attached to USB-C port {} with {disks} USB disks, \ + network={network}{trackpad}\n", controller.port )); } diff --git a/crates/stela-soc/Cargo.toml b/crates/stela-soc/Cargo.toml index f85188d90a..711b72d4a9 100644 --- a/crates/stela-soc/Cargo.toml +++ b/crates/stela-soc/Cargo.toml @@ -15,6 +15,11 @@ workspace = true default = ["std"] # Fixtures the runtime's restore tests drive the USB session through. test-support = [] +# The emulated Magic Trackpad 2's device model, descriptors and report +# encoder (usb::trackpad), which take GPL-2.0-only VoodooInput material: +# stela.efi alone enables it (crates/stela-boot/Cargo.toml), never the +# GPL-3.0-or-later CLI. stela-soc's own tests build it regardless. +trackpad = [] native-profile = ["stela-contracts/native-profile", "stela-engine/native-profile"] std = ["stela-soc-data/std", "stela-engine/std", "stela-contracts/std", "stela-formats/std", "stela-compiler/std"] diff --git a/crates/stela-soc/src/machine.rs b/crates/stela-soc/src/machine.rs index f856860fbb..677a1714a1 100644 --- a/crates/stela-soc/src/machine.rs +++ b/crates/stela-soc/src/machine.rs @@ -19,6 +19,8 @@ pub use transfer_times::{ use crate::Result; pub use crate::pmu::{RtcAnchor, RtcEpoch}; +#[cfg(any(feature = "trackpad", test))] +use crate::usb::trackpad::Trackpad; use crate::usb::{ Function, Speed, ecm::Ecm, @@ -27,6 +29,7 @@ use crate::usb::{ hub::{self, Hub}, session::Session as UsbSession, storage::MassStorage, + trackpad, }; pub use crate::usb::{ ecm::Counters as UsbNetworkCounters, @@ -392,6 +395,10 @@ pub struct UsbCables { /// The keyboard also has a HID System Control interface, for the /// host's request that the guest sleep ([`AppleDevices::system_sleep`]). pub system_control: bool, + /// An emulated Magic Trackpad 2 fed the host's touch frames, on the + /// hub's last port at full speed; refused by a build without + /// stela-soc's `trackpad` feature. + pub trackpad: Option, } /// The USB Bluetooth controller on the native hub. @@ -406,46 +413,100 @@ pub enum UsbBluetooth { impl UsbCables { /// The disks the hub has ports for beside the keyboard and pointer and, - /// with `network` and `bluetooth`, the Ethernet adapter and Bluetooth - /// controller. - pub const fn disk_ports(network: bool, bluetooth: bool) -> usize { - hub::MAX_PORTS - 1 - network as usize - bluetooth as usize + /// with `network`, `bluetooth` and `trackpad`, the Ethernet adapter, + /// Bluetooth controller and trackpad. + pub const fn disk_ports(network: bool, bluetooth: bool, trackpad: bool) -> usize { + hub::MAX_PORTS - 1 - network as usize - bluetooth as usize - trackpad as usize } } /// The functions on the native hub's ports: the keyboard and pointer on -/// port 1, then the Ethernet adapter and Bluetooth controller when there are -/// any, then one mass storage device per host disk. +/// port 1, then the Ethernet adapter and Bluetooth controller when there +/// are any, then one mass storage device per host disk, then the trackpad +/// when there is one, last so the others keep the ports they have without +/// it. struct Attachments { input: Peripheral, + /// Only a build with the trackpad model has one to cable. + #[cfg(any(feature = "trackpad", test))] + trackpad: Option, network: Option, bluetooth: Option, disks: Vec, + /// Touch frames that came with no trackpad to take them. + touch_dropped: u64, +} + +impl Attachments { + /// Whether a trackpad is cabled. + #[cfg(any(feature = "trackpad", test))] + fn has_trackpad(&self) -> bool { + self.trackpad.is_some() + } + + #[cfg(not(any(feature = "trackpad", test)))] + fn has_trackpad(&self) -> bool { + false + } + + /// A host touch frame: the trackpad's, else dropped and counted. + fn touch(&mut self, frame: stela_drivers::input::multitouch::Frame) { + #[cfg(any(feature = "trackpad", test))] + if let Some(trackpad) = &mut self.trackpad { + trackpad.frame(frame); + return; + } + let _ = frame; + self.touch_dropped += 1; + } } impl hub::Ports for Attachments { fn count(&self) -> usize { - 1 + usize::from(self.network.is_some()) + 1 + usize::from(self.has_trackpad()) + + usize::from(self.network.is_some()) + usize::from(self.bluetooth.is_some()) + self.disks.len() } fn speed(&self, port: usize) -> Speed { - if port == 0 { Speed::Full } else { Speed::High } + // The keyboard and pointer and the trackpad are full-speed HID + // functions behind the hub's transaction translator. + if port == 0 || (self.has_trackpad() && port + 1 == self.count()) { + Speed::Full + } else { + Speed::High + } } fn function(&mut self, port: usize) -> &mut dyn Function { let input = core::iter::once(&mut self.input as &mut dyn Function); + #[cfg(any(feature = "trackpad", test))] + let trackpad = self.trackpad.iter_mut().map(|f| f as &mut dyn Function); + #[cfg(not(any(feature = "trackpad", test)))] + let trackpad = core::iter::empty::<&mut dyn Function>(); let network = self.network.iter_mut().map(|f| f as &mut dyn Function); let bluetooth = self.bluetooth.iter_mut().map(|f| f as &mut dyn Function); let disks = self.disks.iter_mut().map(|f| f as &mut dyn Function); - let mut functions = input.chain(network).chain(bluetooth).chain(disks); + let mut functions = input + .chain(network) + .chain(bluetooth) + .chain(disks) + .chain(trackpad); functions.nth(port).expect("a port of the hub's count") } fn function_ref(&self, port: usize) -> &dyn Function { let input = core::iter::once(&self.input as &dyn Function); + #[cfg(any(feature = "trackpad", test))] + let trackpad = self.trackpad.iter().map(|f| f as &dyn Function); + #[cfg(not(any(feature = "trackpad", test)))] + let trackpad = core::iter::empty::<&dyn Function>(); let network = self.network.iter().map(|f| f as &dyn Function); let bluetooth = self.bluetooth.iter().map(|f| f as &dyn Function); let disks = self.disks.iter().map(|f| f as &dyn Function); - let mut functions = input.chain(network).chain(bluetooth).chain(disks); + let mut functions = input + .chain(network) + .chain(bluetooth) + .chain(disks) + .chain(trackpad); functions.nth(port).expect("a port of the hub's count") } } diff --git a/crates/stela-soc/src/machine/tests.rs b/crates/stela-soc/src/machine/tests.rs index 75b7d90550..61f36be1e7 100644 --- a/crates/stela-soc/src/machine/tests.rs +++ b/crates/stela-soc/src/machine/tests.rs @@ -4361,6 +4361,7 @@ fn a_gate_store_is_served_in_its_own_pes_step() { mod data_integration; mod passive; mod pc_sampler; +mod trackpad; /// Host nanoseconds per modelled NOR SPI register access through a board /// shared between PEs, the PIO loop's STATUS read, STATUS write and FIFO diff --git a/crates/stela-soc/src/machine/tests/trackpad.rs b/crates/stela-soc/src/machine/tests/trackpad.rs new file mode 100644 index 0000000000..7a03651674 --- /dev/null +++ b/crates/stela-soc/src/machine/tests/trackpad.rs @@ -0,0 +1,324 @@ +//! The emulated Magic Trackpad 2 on the native hub: its port, and host +//! precision-touchpad frames reaching it. +use super::*; +use crate::usb::{ + BusPeer, Reply, Token, + control::{ + GET_DESCRIPTOR, SET_ADDRESS, SET_CONFIGURATION, + tests::{setup, transfer}, + }, + hub::Ports, + trackpad::{self, Config, Identity, Trackpad}, +}; +use stela_drivers::input::multitouch::{Finger, Frame, Surface}; + +const SURFACE: Surface = Surface { + width_um: 126_900, + height_um: 82_000, +}; + +fn config() -> Config { + Config { + identity: Identity::MagicTrackpad2, + surface: SURFACE, + } +} + +fn attachments(trackpad: bool, network: bool, bluetooth: bool) -> Attachments { + Attachments { + input: Peripheral::new(), + trackpad: trackpad.then(|| Trackpad::new(config(), &trackpad::serial(1))), + network: network.then(|| { + Ecm::with_model(Mac([2, 0, 0, 0, 0, 1]), crate::usb::ecm::Model::Ncm).unwrap() + }), + bluetooth: bluetooth.then(Hci::new), + disks: Vec::new(), + touch_dropped: 0, + } +} + +/// The vendor ID a port's function enumerates with. +fn vendor(function: &mut dyn Function) -> u16 { + let device = transfer(function, setup(0x80, GET_DESCRIPTOR, 0x100, 0, 18), &[]).unwrap(); + u16::from_le_bytes([device[8], device[9]]) +} + +#[test] +fn trackpad_cabled_on_full_speed_port() { + let mut ports = attachments(true, true, true); + assert_eq!(ports.count(), 4); + assert!(ports.count() <= hub::MAX_PORTS); + let speeds: Vec = (0..ports.count()).map(|port| ports.speed(port)).collect(); + assert_eq!(speeds, [Speed::Full, Speed::High, Speed::High, Speed::Full]); + // The trackpad takes the last port: the keyboard and pointer, the + // network adapter and Bluetooth keep the ports they have without it, so + // macOS sees no new network interface. + let mut without = attachments(false, true, true); + for port in 0..3 { + assert_eq!(vendor(ports.function(port)), vendor(without.function(port))); + } + assert_eq!(vendor(ports.function(3)), 0x05ac); + // Alone beside the keyboard and pointer, it is the second. + let mut alone = attachments(true, false, false); + assert_eq!((alone.count(), alone.speed(1)), (2, Speed::Full)); + assert_eq!(vendor(alone.function(1)), 0x05ac); + assert_eq!( + UsbCables::disk_ports(true, true, true), + UsbCables::disk_ports(true, true, false) - 1 + ); + assert_eq!( + UsbCables::disk_ports(false, false, true), + hub::MAX_PORTS - 2 + ); +} + +#[test] +fn no_flag_no_port() { + // Without the trackpad the ports are today's: the keyboard and pointer + // at full speed, then the network adapter and Bluetooth at high speed. + let mut ports = attachments(false, true, true); + assert_eq!(ports.count(), 3); + let speeds: Vec = (0..3).map(|port| ports.speed(port)).collect(); + assert_eq!(speeds, [Speed::Full, Speed::High, Speed::High]); + assert_eq!(vendor(ports.function(0)), 0x1209); + assert_ne!(vendor(ports.function(1)), 0x05ac); + assert_eq!( + UsbCables::disk_ports(false, false, false), + hub::MAX_PORTS - 1 + ); + assert_eq!(UsbCables::disk_ports(true, true, false), hub::MAX_PORTS - 3); +} + +/// A board with a USB controller on connector 1 and the native hub cabled +/// to it with `cables`. +fn cabled(cables: UsbCables) -> AppleDevices { + let mut d = AppleDevices::new(); + let dart = d + .add_dart( + Range { + physical: 0x382f00000, + bytes: 0x4000, + }, + 16, + None, + None, + ) + .unwrap(); + add_usb_phy(&mut d); + d.add_usb(&usb_placement(), dart).unwrap(); + d.attach_input(1, cables).unwrap(); + d +} + +fn the_trackpad(d: &mut AppleDevices) -> &mut Trackpad { + d.usb_masters[0] + .peripheral + .as_mut() + .unwrap() + .ports + .trackpad + .as_mut() + .expect("a trackpad is cabled") +} + +fn enumerate(t: &mut Trackpad) { + transfer(t, setup(0, SET_ADDRESS, 5, 0, 0), &[]).unwrap(); + transfer(t, setup(0, SET_CONFIGURATION, 1, 0, 0), &[]).unwrap(); +} + +/// One report from the multitouch endpoint, or `None` for a NAK. +fn report(t: &mut Trackpad) -> Option> { + let mut out = Vec::new(); + loop { + let mut packet = [0u8; 64]; + match t.packet(0x83, Token::In, &mut packet).unwrap() { + Reply::Ack(n) => { + out.extend_from_slice(&packet[..n]); + if n < 64 { + return Some(out); + } + } + Reply::Nak => return None, + Reply::Stall => panic!("the multitouch endpoint stalled"), + } + } +} + +#[test] +fn touch_routes_to_trackpad() { + let mut d = cabled(UsbCables { + trackpad: Some(config()), + ..UsbCables::default() + }); + enumerate(the_trackpad(&mut d)); + let finger = Finger { + id: 0, + x_um: 63_450, + y_um: 41_000, + tip: true, + confident: true, + }; + d.input(Input::Touch(Frame::new(1_000_000, 0, &[finger]))) + .unwrap(); + let r = report(the_trackpad(&mut d)).expect("the frame reached the trackpad"); + assert_eq!((r[0], r.len()), (0x02, 21)); + assert_eq!(d.trackpad_counters().unwrap().received, 1); + assert!( + d.trackpad_trace() + .contains(&trackpad::TrackpadEvent::Configured(1)) + ); + // The keyboard and mouse still reach the native peripheral. + d.input(Input::MouseButtons(1)).unwrap(); +} + +#[test] +fn a_late_touchpad_s_surface_reaches_the_trackpad() { + let mut d = cabled(UsbCables { + trackpad: Some(config()), + ..UsbCables::default() + }); + let late = Surface { + width_um: 100_000, + height_um: 60_000, + }; + d.set_trackpad_surface(late); + assert_eq!(the_trackpad(&mut d).surface(), late); + // Without a trackpad there is nothing to tell. + let mut bare = cabled(UsbCables::default()); + bare.set_trackpad_surface(late); + assert_eq!(bare.trackpad_counters(), None); +} + +#[test] +fn touch_without_a_trackpad_is_dropped_and_counted() { + let mut d = cabled(UsbCables::default()); + d.input(Input::Touch(Frame::lifted(5))).unwrap(); + d.input(Input::Touch(Frame::lifted(6))).unwrap(); + assert_eq!(d.trackpad_counters(), None); + assert!(d.trackpad_trace().is_empty()); + let hub = d.usb_masters[0].peripheral.as_ref().unwrap(); + assert_eq!(hub.ports.touch_dropped, 2); + assert!(d.usb_diagnostics()[0].contains("touch_dropped=2")); + // Without one, the diagnostics line is today's. + let quiet = cabled(UsbCables::default()); + assert!(!quiet.usb_diagnostics()[0].contains("touch_dropped")); +} + +/// `stela-drivers`' `ptp/tests.rs` fixture: 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, Input Mode in feature report 3 and +/// the switches in feature report 4. +fn ptp_finger() -> Vec { + 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 ptp_descriptor() -> Vec { + let mut d = vec![0x05, 0x0d, 0x09, 0x05, 0xa1, 0x01, 0x85, 0x01]; + d.extend(ptp_finger()); + d.extend(ptp_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 report of the fixture: one finger (confidence, tip, id, x, y) and +/// an empty second slot. +fn ptp_report(finger: (bool, bool, u8, u16, u16), scan: u16) -> Vec { + let mut r = vec![0x01]; + for (confidence, tip, id, x, y) in [finger, (false, false, 0, 0, 0)] { + 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(1); + r.push(0); + r +} + +fn hex(text: &str) -> Vec { + text.split_whitespace() + .map(|byte| u8::from_str_radix(byte, 16).unwrap()) + .collect() +} + +#[test] +fn ptp_to_wire_e2e() { + use stela_drivers::{ + input::ptp::{Profile, Ptp}, + usb::hid::{Translated, Translator}, + }; + let mut translator = Translator::describe(&ptp_descriptor()).unwrap(); + let profile = Profile::select(translator.descriptor().unwrap()).unwrap(); + let mut ptp = Ptp::new(profile); + ptp.set_frames(true); + let mut d = cabled(UsbCables { + trackpad: Some(Config { + identity: Identity::MagicTrackpad2, + surface: ptp.surface(), + }), + ..UsbCables::default() + }); + enumerate(the_trackpad(&mut d)); + let mut wire = Vec::new(); + for (finger, scan, now_us) in [ + ((true, true, 1, 500, 300), 100, 1_000_000), + ((true, true, 1, 600, 300), 180, 1_004_000), + ((true, false, 1, 600, 300), 260, 1_009_000), + ] { + let (mut events, mut inputs) = (Vec::new(), Vec::new()); + let Translated::Data(frame) = + translator.translate(&ptp_report(finger, scan), &mut events, &mut inputs) + else { + panic!("report rejected"); + }; + ptp.report( + translator.descriptor().unwrap(), + &frame, + &events, + now_us, + &mut inputs, + ); + assert!(matches!(inputs[..], [Input::Touch(_)]), "{inputs:?}"); + for input in inputs { + d.input(input).unwrap(); + } + wire.push(report(the_trackpad(&mut d)).unwrap()); + } + wire.push(report(the_trackpad(&mut d)).unwrap()); + assert_eq!(report(the_trackpad(&mut d)), None); + assert_eq!( + wire, + [ + hex("02 00 00 00 00 00 00 03 31 44 1f 00 80 40 f9 6b 14 14 0a 05 81"), + hex("02 00 00 00 00 00 00 03 31 84 1f 00 5c 42 f9 8b 14 14 0a 05 81"), + hex("02 00 00 00 00 00 00 02 31 c4 1f 00 5c 42 f9 eb 00 00 00 00 81"), + hex("02 00 00 00 00 00 00 02 31 c4 1f 00"), + ] + ); +} diff --git a/crates/stela-soc/src/machine/usb.rs b/crates/stela-soc/src/machine/usb.rs index 1e18abd0de..33fac71687 100644 --- a/crates/stela-soc/src/machine/usb.rs +++ b/crates/stela-soc/src/machine/usb.rs @@ -152,15 +152,27 @@ impl AppleDevices { /// HPM reports the attach and the controller's host personality finds /// the hub on its USB2 port. The keyboard and pointer sit on the hub's /// first port, and `cables` names the USB Ethernet adapter, Bluetooth - /// controller and mass storage devices on the next ones. + /// controller, mass storage devices and trackpad on the next ones. The + /// trackpad's serial number is the board's, from its ECID, as the + /// Bluetooth model's address is. A build without the trackpad model + /// (stela-soc's `trackpad` feature) refuses one. pub fn attach_input(&mut self, connector: u32, cables: UsbCables) -> Result<()> { let UsbCables { disks, network, bluetooth, system_control, + trackpad, } = cables; - let extras = usize::from(network.is_some()) + usize::from(bluetooth.is_some()); + #[cfg(not(any(feature = "trackpad", test)))] + if trackpad.is_some() { + return Err(refuse!( + "this build has no Magic Trackpad 2: stela-soc's trackpad feature is off" + )); + } + let extras = usize::from(network.is_some()) + + usize::from(bluetooth.is_some()) + + usize::from(trackpad.is_some()); if 1 + extras + disks.len() > hub::MAX_PORTS { return Err(refuse!("the native hub has seven ports")); } @@ -182,12 +194,16 @@ impl AppleDevices { } else { Peripheral::new() }, + #[cfg(any(feature = "trackpad", test))] + trackpad: trackpad + .map(|config| Trackpad::new(config, &crate::usb::trackpad::serial(self.ecid))), network, bluetooth: bluetooth.map(|kind| match kind { UsbBluetooth::Host => Hci::new(), UsbBluetooth::Model => Hci::modeled(crate::usb::hci::model::address(self.ecid)), }), disks, + touch_dropped: 0, }; master.peripheral = Some(Hub::new(attachments, "0001")?); master.connector.set_connection(Some(typec::Attached { @@ -317,15 +333,59 @@ impl AppleDevices { .map(|peripheral| peripheral.ports.input.leds()) } - /// One host input change for the attached peripheral. + /// One host input change for the attached peripheral; a touch frame + /// for the trackpad, dropped and counted without one. pub fn input(&mut self, input: Input) -> Result<()> { - self.usb_masters + let ports = &mut self + .usb_masters .iter_mut() .find_map(|master| master.peripheral.as_mut()) .ok_or(refuse!("no input peripheral is attached"))? - .ports - .input - .input(input) + .ports; + match input { + Input::Touch(frame) => { + ports.touch(frame); + Ok(()) + } + input => ports.input.input(input), + } + } + + #[cfg(any(feature = "trackpad", test))] + fn usb_trackpad(&mut self) -> Option<&mut Trackpad> { + self.usb_masters + .iter_mut() + .find_map(|master| master.peripheral.as_mut()?.ports.trackpad.as_mut()) + } + + /// The trackpad's trace for the owner's log since it was last taken: + /// configurations, the mode and features the guest asked for, each + /// unknown request once and the frames dropped; empty without one. + pub fn trackpad_trace(&mut self) -> Vec { + #[cfg(any(feature = "trackpad", test))] + if let Some(trackpad) = self.usb_trackpad() { + return trackpad.take_trace(); + } + Vec::new() + } + + /// The surface of a touchpad that arrived after the trackpad was cabled + /// for it to map; nothing without a trackpad. + pub fn set_trackpad_surface(&mut self, surface: stela_drivers::input::multitouch::Surface) { + #[cfg(any(feature = "trackpad", test))] + if let Some(trackpad) = self.usb_trackpad() { + trackpad.set_surface(surface); + } + let _ = surface; + } + + /// The trackpad's frame counters; `None` without one. + pub fn trackpad_counters(&mut self) -> Option { + #[cfg(any(feature = "trackpad", test))] + if let Some(trackpad) = self.usb_trackpad() { + return Some(trackpad.counters()); + } + None } /// Ask the guest to sleep, with a System Sleep press and release on the @@ -423,8 +483,14 @@ impl AppleDevices { c.malformed ) }); + let touch = master + .peripheral + .as_ref() + .map(|hub| hub.ports.touch_dropped) + .filter(|dropped| *dropped != 0) + .map_or_else(String::new, |dropped| format!(" touch_dropped={dropped}")); format!( - "port={} attached={}{why}{host}{hub}{net}", + "port={} attached={}{why}{host}{hub}{net}{touch}", master.number, master.attached || master.peripheral.is_some() ) diff --git a/crates/stela-soc/src/usb.rs b/crates/stela-soc/src/usb.rs index a080a776e9..f49dbb9a44 100644 --- a/crates/stela-soc/src/usb.rs +++ b/crates/stela-soc/src/usb.rs @@ -11,6 +11,11 @@ pub mod mux; pub mod plist; pub mod session; pub mod storage; +pub mod trackpad; + +/// Whether this build carries the emulated Magic Trackpad 2's device model +/// (the `trackpad` feature): stela.efi does, the CLI must not. +pub const TRACKPAD: bool = cfg!(feature = "trackpad"); /// The initial transport profile has USB2 high-speed packets only. pub const MAX_PACKET: usize = 512; diff --git a/crates/stela-soc/src/usb/hid.rs b/crates/stela-soc/src/usb/hid.rs index 4592edfc4b..321d84f0d6 100644 --- a/crates/stela-soc/src/usb/hid.rs +++ b/crates/stela-soc/src/usb/hid.rs @@ -467,6 +467,7 @@ impl Peripheral { let report = self.mouse_report(0, 0, 0, detents).to_vec(); self.queue(MOUSE, report); } + Input::Touch(_) => return Err(refuse!("the native mouse has no touch surface")), } Ok(()) } diff --git a/crates/stela-soc/src/usb/hid/tests.rs b/crates/stela-soc/src/usb/hid/tests.rs index 56bdbb058a..a890203289 100644 --- a/crates/stela-soc/src/usb/hid/tests.rs +++ b/crates/stela-soc/src/usb/hid/tests.rs @@ -62,6 +62,18 @@ fn enumerate(p: &mut Peripheral) { control(p, setup(0x21, SET_IDLE, 0, 0, 0), &[]).unwrap(); } +#[test] +fn peripheral_refuses_touch() { + let mut p = Peripheral::new(); + enumerate(&mut p); + let frame = stela_drivers::input::multitouch::Frame::lifted(0); + assert!(p.input(Input::Touch(frame)).is_err()); + // Nothing queued on any interface. + for endpoint in [KEYBOARD_ENDPOINT, POINTER_ENDPOINT, MOUSE_ENDPOINT] { + assert_eq!(p.ready_at(endpoint), None); + } +} + #[test] fn descriptors_describe_a_composite_keyboard_and_pointer() { let mut p = Peripheral::new(); diff --git a/crates/stela-soc/src/usb/trackpad.rs b/crates/stela-soc/src/usb/trackpad.rs new file mode 100644 index 0000000000..eaaf5cc862 --- /dev/null +++ b/crates/stela-soc/src/usb/trackpad.rs @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +//! An emulated USB Magic Trackpad 2 fed by the host's precision touchpads, +//! so macOS drives them with its own multitouch stack: its gestures, +//! scrolling, pinch and rotate and its Trackpad settings, where the guest's +//! mouse gets only motion and wheel detents. +//! +//! This module holds what the machine and its owner name of the trackpad +//! in every build: its identity, what is cabled ([`Config`]), its serial +//! number, its trace ([`TrackpadEvent`]) and its counters. The device +//! itself (`Trackpad`, a hub port's full-speed function), its descriptors +//! and feature answers (`descriptors`) and its report encoder (`report`) +//! follow GPL-2.0-only VoodooInput material, so they are built only with +//! this crate's `trackpad` feature, which stela.efi alone enables, and in +//! this crate's own tests; without it the machine refuses to cable one +//! ([`super::TRACKPAD`]). +use alloc::{format, string::String}; +use stela_drivers::input::multitouch::Surface; + +#[cfg(any(feature = "trackpad", test))] +pub mod descriptors; +#[cfg(any(feature = "trackpad", test))] +mod function; +#[cfg(any(feature = "trackpad", test))] +pub mod report; +#[cfg(any(feature = "trackpad", test))] +pub use function::{QUEUE, Trackpad}; + +/// Apple's USB vendor ID (Linux hid-ids.h `USB_VENDOR_ID_APPLE`). +pub const VENDOR: u16 = 0x05ac; +/// The Magic Trackpad 2 (hid-ids.h `USB_DEVICE_ID_APPLE_MAGICTRACKPAD2`). +pub const MAGIC_TRACKPAD_2: u16 = 0x0265; +/// The MacBookAir10,1 internal trackpad's product ID, the one VoodooInput +/// presents on macOS 12 and later: the fallback identity. +pub const BUILTIN: u16 = 0x0281; + +/// Which Apple trackpad the device presents. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Identity { + /// The Magic Trackpad 2, 05AC:0265. + MagicTrackpad2, + /// The macOS 12+ internal trackpad ID, 05AC:0281. + Builtin, +} + +impl Identity { + pub fn product(self) -> u16 { + match self { + Self::MagicTrackpad2 => MAGIC_TRACKPAD_2, + Self::Builtin => BUILTIN, + } + } +} + +/// What the owner cables: the identity, and the host surface the frames' +/// positions span. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Config { + pub identity: Identity, + pub surface: Surface, +} + +/// The serial number of the trackpad of the board whose ECID is `ecid`: +/// stable for the machine, "STELA" and 7 hexadecimal digits of SHA-256 +/// of a label and the ECID, so it is no Apple serial and names no ECID. +pub fn serial(ecid: u64) -> String { + use sha2::{Digest, Sha256}; + let mut hash = Sha256::new(); + hash.update(b"Stela Magic Trackpad 2 serial"); + hash.update(ecid.to_le_bytes()); + let digest = hash.finalize(); + let mut serial = String::from("STELA"); + for byte in &digest[..4] { + serial.push_str(&format!("{byte:02X}")); + } + serial.truncate(12); + serial +} + +/// What the device tells its owner's log. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum TrackpadEvent { + /// The guest selected this configuration (0: deconfigured). + Configured(u8), + /// The guest set the mode feature (1: multitouch). + Mode(u8), + /// The guest first read this feature report of the multitouch + /// interface. + Feature(u8), + /// The guest first armed this information query (SET_REPORT feature + /// 0x01), answered or refused. + Query { id: u8, answered: bool }, + /// The first of these requests, which STALLed. + Unknown { + request_type: u8, + request: u8, + value: u16, + index: u16, + }, + /// Host frames dropped from the queue since the last take. + Dropped(u64), +} + +impl core::fmt::Display for TrackpadEvent { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match *self { + Self::Configured(value) => write!(f, "configured {value}"), + Self::Mode(mode) => write!(f, "mode {mode}"), + Self::Feature(id) => write!(f, "feature {id:#04x}"), + Self::Query { id, answered: true } => write!(f, "query {id:#04x}"), + Self::Query { + id, + answered: false, + } => write!(f, "query {id:#04x} refused"), + Self::Unknown { + request_type, + request, + value, + index, + } => write!( + f, + "unknown request_type={request_type:#04x} request={request:#04x} \ + value={value:#06x} index={index}" + ), + Self::Dropped(frames) => write!(f, "dropped {frames} frames"), + } + } +} + +/// How many frames came from the host and went to the guest, and the time +/// the host frames spanned while fingers were down, for a frame rate. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Counters { + pub received: u64, + pub sent: u64, + pub dropped: u64, + /// Frames whose motion went into the newest queued frame of the same + /// contacts, behind a guest reading slower than the pad. + pub coalesced: u64, + /// The sum of the gaps between consecutive received frames under + /// 100 ms, by the frames' own times: the time the pad was reporting. + pub reporting_us: u64, +} + +#[cfg(test)] +mod tests; diff --git a/crates/stela-soc/src/usb/trackpad/descriptors.rs b/crates/stela-soc/src/usb/trackpad/descriptors.rs new file mode 100644 index 0000000000..6fc330b8f3 --- /dev/null +++ b/crates/stela-soc/src/usb/trackpad/descriptors.rs @@ -0,0 +1,249 @@ +// SPDX-License-Identifier: GPL-2.0-only +// The multitouch and actuator report descriptors and the multitouch +// feature answers are VoodooInput d8978137's, verbatim +// (VoodooInputSimulatorDevice.cpp `report_descriptor`, `setReport`, +// `getReport`; VoodooInputActuatorDevice.cpp `actuator_report_descriptor`; +// GPL-2.0; Copyright (c) 2018-2019 Alexandre Daoud and Kishor Prins). The +// identity is Linux hid-ids.h's and the mode switch hid-magicmouse.c's. +// See NOTICE. +//! What the emulated Magic Trackpad 2 says about itself: its device, +//! configuration and HID descriptors, and the answers of its multitouch +//! interface's feature reports. The layout is data: an interface or ID +//! changes here alone. +//! +//! | Interface | Class | Report descriptor | Endpoint | +//! |---|---|---|---| +//! | 0 | HID 3/0/0 | a vendor 0xFF00:0x0B collection with one 1-byte feature report | 0x81 interrupt IN, 64 bytes, every 8 ms | +//! | 1 | HID 3/0/2 | VoodooInput's 110-byte simulator descriptor | 0x83 interrupt IN, 64 bytes, every 1 ms | +//! | 2 | HID 3/0/0 | VoodooInput's 36-byte actuator descriptor | 0x84 interrupt IN, 64 bytes, every 8 ms | +//! +//! Interface 1 is the multitouch one: Windows' driver binds the MT2's +//! `MI_01` and reads endpoint 0x83, and Linux sends the mode switch to the +//! interface whose protocol is mouse. Its descriptor declares the mouse +//! report 0x02 that the multitouch reports reuse, a touch pad application +//! and the vendor input report 0x44 of 1387 bytes, which makes a host size +//! its input transfers for the longest multitouch report. +use super::{VENDOR, report::Mapping}; +use crate::usb::control::{self, CONFIGURATION, DEVICE, Descriptors, INTERFACE}; +use alloc::{string::String, vec, vec::Vec}; + +/// One MT2 firmware's revision (`HID\VID_05AC&PID_0265&REV_0855`). +pub const RELEASE: u16 = 0x0855; + +pub const INTERFACES: usize = 3; +/// The multitouch interface. +pub const MULTITOUCH: u16 = 1; +/// Each interface's interrupt IN endpoint, by interface number. +pub const ENDPOINTS: [u8; INTERFACES] = [0x81, 0x83, 0x84]; +/// Full-speed polling intervals in frames, by interface number. +const INTERVALS: [u8; INTERFACES] = [8, 1, 8]; +pub const MAX_PACKET: usize = 64; + +pub const HID: u8 = 0x21; +pub const REPORT: u8 = 0x22; +/// HID report types in GET/SET_REPORT's wValue high byte. +pub const INPUT_REPORT: u8 = 1; +pub const OUTPUT_REPORT: u8 = 2; +pub const FEATURE_REPORT: u8 = 3; + +/// Interface 0: a vendor collection with one feature report of a byte and +/// no report ID. +pub const VENDOR_DESCRIPTOR: [u8; 21] = [ + 0x06, 0x00, 0xff, // Usage Page (Vendor 0xFF00) + 0x09, 0x0b, // Usage (0x0B) + 0xa1, 0x01, // Collection (Application) + 0x09, 0x0b, // Usage (0x0B) + 0x15, 0x00, 0x26, 0xff, 0x00, // Logical 0..255 + 0x75, 0x08, 0x95, 0x01, 0xb1, 0x02, // one byte, Feature + 0xc0, +]; + +/// Interface 1: VoodooInput's simulator descriptor. +pub const MULTITOUCH_DESCRIPTOR: [u8; 110] = [ + 0x05, 0x01, 0x09, 0x02, 0xa1, 0x01, 0x09, 0x01, 0xa1, 0x00, 0x05, 0x09, 0x19, 0x01, 0x29, 0x03, + 0x15, 0x00, 0x25, 0x01, 0x85, 0x02, 0x95, 0x03, 0x75, 0x01, 0x81, 0x02, 0x95, 0x01, 0x75, 0x05, + 0x81, 0x01, 0x05, 0x01, 0x09, 0x30, 0x09, 0x31, 0x15, 0x81, 0x25, 0x7f, 0x75, 0x08, 0x95, 0x02, + 0x81, 0x06, 0x95, 0x04, 0x75, 0x08, 0x81, 0x01, 0xc0, 0xc0, 0x05, 0x0d, 0x09, 0x05, 0xa1, 0x01, + 0x06, 0x00, 0xff, 0x09, 0x0c, 0x15, 0x00, 0x26, 0xff, 0x00, 0x75, 0x08, 0x95, 0x10, 0x85, 0x3f, + 0x81, 0x22, 0xc0, 0x06, 0x00, 0xff, 0x09, 0x0c, 0xa1, 0x01, 0x06, 0x00, 0xff, 0x09, 0x0c, 0x15, + 0x00, 0x26, 0xff, 0x00, 0x85, 0x44, 0x75, 0x08, 0x96, 0x6b, 0x05, 0x81, 0x00, 0xc0, +]; + +/// Interface 2: VoodooInput's actuator descriptor: input 0x3F of 15 bytes, +/// output 0x53 of 63. +pub const ACTUATOR_DESCRIPTOR: [u8; 36] = [ + 0x06, 0x00, 0xff, 0x09, 0x0d, 0xa1, 0x01, 0x06, 0x00, 0xff, 0x09, 0x0d, 0x15, 0x00, 0x26, 0xff, + 0x00, 0x75, 0x08, 0x85, 0x3f, 0x96, 0x0f, 0x00, 0x81, 0x02, 0x09, 0x0d, 0x85, 0x53, 0x96, 0x3f, + 0x00, 0x91, 0x02, 0xc0, +]; + +/// The report descriptor of interface `interface`. +pub fn report_descriptor(interface: usize) -> Option<&'static [u8]> { + match interface { + 0 => Some(&VENDOR_DESCRIPTOR), + 1 => Some(&MULTITOUCH_DESCRIPTOR), + 2 => Some(&ACTUATOR_DESCRIPTOR), + _ => None, + } +} + +/// The reports interfaces 0 and 2 declare, as (interface, type, ID, bytes +/// after the ID): GET_REPORT answers them with zeros. +pub const DECLARED: [(u16, u8, u8, usize); 3] = [ + (0, FEATURE_REPORT, 0, 1), + (2, INPUT_REPORT, 0x3f, 15), + (2, OUTPUT_REPORT, 0x53, 63), +]; + +/// HID descriptor for a report descriptor of `bytes` (HID 1.11 6.2.1). +pub fn hid_descriptor(bytes: usize) -> [u8; 9] { + [ + 9, + HID, + 0x11, + 0x01, // HID 1.11 + 0, // no country + 1, + REPORT, + bytes as u8, + (bytes >> 8) as u8, + ] +} + +fn device(product: u16) -> [u8; 18] { + let [vendor_low, vendor_high] = VENDOR.to_le_bytes(); + let [product_low, product_high] = product.to_le_bytes(); + let [release_low, release_high] = RELEASE.to_le_bytes(); + [ + 18, + DEVICE, + 0x00, + 0x02, // USB 2.0 + 0, + 0, + 0, // class per interface + control::EP0_PACKET as u8, + vendor_low, + vendor_high, + product_low, + product_high, + release_low, + release_high, + 1, // manufacturer + 2, // product + 3, // serial + 1, // one configuration + ] +} + +fn configuration() -> Vec { + let parts: Vec> = (0..INTERFACES) + .flat_map(|n| { + let protocol = if n == usize::from(MULTITOUCH) { 2 } else { 0 }; + let descriptor = report_descriptor(n).expect("each interface has one"); + [ + vec![9, INTERFACE, n as u8, 0, 1, 3, 0, protocol, 0], + hid_descriptor(descriptor.len()).to_vec(), + vec![ + 7, + control::ENDPOINT, + ENDPOINTS[n], + 3, // interrupt + MAX_PACKET as u8, + 0, + INTERVALS[n], + ], + ] + }) + .collect(); + let parts: Vec<&[u8]> = parts.iter().map(Vec::as_slice).collect(); + // Self-powered, no remote wakeup. + let bytes = control::configuration(1, 0, &parts); + debug_assert_eq!(bytes[1], CONFIGURATION); + bytes +} + +/// The descriptors of a trackpad of product ID `product` with serial +/// `serial`. +pub fn descriptors(product: u16, serial: &str) -> Descriptors { + Descriptors { + device: device(product), + configuration: configuration(), + // Full speed only: device qualifier and other-speed configuration + // STALL. + other_speed: None, + strings: vec![ + String::from("Apple Inc."), + String::from("Magic Trackpad 2"), + String::from(serial), + ], + } +} + +/// The multitouch information queries SET_REPORT feature 0x01 `{01, id}` +/// arms, with the length GET_REPORT feature 0x01 then states: +/// `{01, id, 00, length, 00}`. Query 0xD9 is answered with the whole 0xD9 +/// report instead, as VoodooInput answers it. +pub const QUERIES: [(u8, u8); 7] = [ + (0xdb, 0x49), + (0xd1, 0x01), + (0xd3, 0x0c), + (0xd0, 0x0f), + (0xa1, 0x06), + (0x7f, 0x04), + (0xc8, 0x01), +]; +pub const QUERY: u8 = 0x01; +pub const SENSOR_SURFACE: u8 = 0xd9; +/// The MT2's mode switch (hid-magicmouse.c `feature_mt_trackpad2_usb`). +pub const MODE: u8 = 0x02; + +const D1: [u8; 2] = [0xd1, 0x81]; +const D3: [u8; 13] = [ + 0xd3, 0x01, 0x16, 0x1e, 0x03, 0x95, 0x00, 0x14, 0x1e, 0x62, 0x05, 0x00, 0x00, +]; +const D0: [u8; 16] = [ + 0xd0, 0x02, 0x01, 0x00, 0x14, 0x01, 0x00, 0x1e, 0x00, 0x02, 0x14, 0x02, 0x01, 0x0e, 0x02, 0x00, +]; +const A1: [u8; 7] = [0xa1, 0x00, 0x00, 0x05, 0x00, 0xfc, 0x01]; +const SEVEN_F: [u8; 5] = [0x7f, 0x00, 0x00, 0x00, 0x00]; + +/// The answer to GET_REPORT feature `id` on the multitouch interface, for +/// a surface mapped by `map`: VoodooInput's bytes, with the pad's width and +/// height in 0xD9 ([`Mapping::d9`]). +pub fn feature(id: u8, map: &Mapping) -> Option> { + Some(match id { + 0x00 => vec![0x00, 0x01], + MODE => vec![MODE, 0x01], + 0xd1 => D1.to_vec(), + 0xd3 => D3.to_vec(), + 0xd0 => D0.to_vec(), + 0xa1 => A1.to_vec(), + SENSOR_SURFACE => map.d9().to_vec(), + 0x7f => SEVEN_F.to_vec(), + 0xc8 => vec![0xc8, 0x08], + 0xdb => { + // D1, D3, D0, A1 and D9, each after its length as a 16-bit + // word (D1's in the header), then 7F with none. + let mut all = vec![0xdb, 0x01]; + for part in [&D1[..], &D3, &D0, &A1, &map.d9()] { + all.extend_from_slice(&(part.len() as u16).to_le_bytes()); + all.extend_from_slice(part); + } + all.extend_from_slice(&SEVEN_F); + all + } + _ => return None, + }) +} + +/// The answer GET_REPORT feature 0x01 gives after query `id` was armed. +pub fn query(id: u8, map: &Mapping) -> Option> { + if id == SENSOR_SURFACE { + return Some(map.d9().to_vec()); + } + QUERIES + .iter() + .find(|(query, _)| *query == id) + .map(|&(_, length)| vec![QUERY, id, 0x00, length, 0x00]) +} diff --git a/crates/stela-soc/src/usb/trackpad/function.rs b/crates/stela-soc/src/usb/trackpad/function.rs new file mode 100644 index 0000000000..20d5675009 --- /dev/null +++ b/crates/stela-soc/src/usb/trackpad/function.rs @@ -0,0 +1,465 @@ +// SPDX-License-Identifier: GPL-2.0-only +// The multitouch feature protocol follows VoodooInput d8978137 +// (VoodooInputSimulatorDevice.cpp, GPL-2.0; Copyright (c) 2018-2019 +// Alexandre Daoud and Kishor Prins) and the mode switch Linux +// hid-magicmouse.c (Copyright (c) 2010 Michael Poole and Chase Douglas). +// See NOTICE. +//! The emulated Magic Trackpad 2 itself, as a hub port's full-speed +//! [`Function`], built with the `trackpad` feature alone (see the parent +//! module). +//! +//! Evidence: the identity 05AC:0265 (Linux hid-ids.h +//! `USB_DEVICE_ID_APPLE_MAGICTRACKPAD2`; Windows' AmtPtpDevice.inf binds its +//! `MI_01`), the mode switch SET_REPORT feature 0x02 `{02, 01}` on the +//! multitouch interface (hid-magicmouse.c `magicmouse_enable_multitouch`), +//! the report layout (hid-magicmouse.c and VoodooInput, +//! [`report`](super::report)), and VoodooInput's simulator, whose report +//! descriptor and answers to Apple's multitouch feature requests Intel +//! macOS's multitouch driver accepts ([`descriptors`]). VoodooInput +//! presents itself over I2C under an internal trackpad's ID; that macOS +//! takes the same frames and answers from a USB 05AC:0265 is not shown by +//! any source, so `Identity::Builtin` gives VoodooInput's own ID, one +//! constant away. +//! +//! The function sends frames whatever mode the guest set: VoodooInput never +//! waits for a switch, and waiting would make a missed switch a dead pad. +//! Every request the tables do not answer STALLs and is reported once +//! (`TrackpadEvent::Unknown`), which is how the device converges on what +//! macOS asks. +//! +//! Host frames queue until the guest's interrupt IN on endpoint 0x83, and +//! are encoded only then, so a frame's touch states follow what the guest +//! was sent: a frame dropped from the queue can delay a Start or a Stop but +//! never lose one. Once two frames are queued, a frame of the newest one's +//! contacts and buttons replaces it (their motion coalesces, counted apart), +//! so a guest reading slower than the pad lags two frames, not a queue's +//! worth; frames of changing contacts queue up to [`QUEUE`], past which the +//! oldest is dropped, counted. An unconfigured guest keeps the newest frame +//! only. A bus reset +//! or a new configuration forgets every contact, so a finger still down +//! starts again. A report longer than the endpoint's 64-byte packets (six +//! or more fingers) goes out over consecutive packets, the last one short. +use super::{ + Config, Counters, TrackpadEvent, + descriptors::{ + self, DECLARED, ENDPOINTS, FEATURE_REPORT, HID, INTERFACES, MAX_PACKET, MODE, MULTITOUCH, + QUERY, REPORT, + }, + report::{Encoder, Mapping}, +}; +use crate::Result; +use crate::usb::{ + BusPeer, Function, Reply, Token, + control::{ + CLASS, CLEAR_FEATURE, Control, ENDPOINT_HALT, GET_DESCRIPTOR, GET_INTERFACE, GET_STATUS, + Outcome, RECIPIENT_ENDPOINT, RECIPIENT_INTERFACE, Requests, SET_FEATURE, SET_INTERFACE, + STANDARD, Setup, Stall, + }, +}; +use alloc::{collections::VecDeque, vec, vec::Vec}; +use stela_drivers::input::multitouch::{Frame, Surface}; + +/// Host frames waiting for the guest at most. +pub const QUEUE: usize = 32; +/// Queued frames from which a frame of the newest one's contacts and +/// buttons replaces it: the guest's next report and the newest motion +/// stay, so a guest reading slower than the pad lags two frames at most. +const COALESCE_FROM: usize = 2; +/// Trace entries kept between the owner's takes. +const TRACE: usize = 64; +/// Distinct unknown requests reported. +const UNKNOWN: usize = 64; + +const GET_REPORT: u8 = 0x01; +const GET_IDLE: u8 = 0x02; +const GET_PROTOCOL: u8 = 0x03; +const SET_REPORT: u8 = 0x09; +const SET_IDLE: u8 = 0x0a; +const SET_PROTOCOL: u8 = 0x0b; +const REPORT_PROTOCOL: u8 = 1; + +/// The gap between frames under which they are one stretch of reporting. +const REPORTING_GAP_US: u64 = 100_000; + +pub struct Trackpad { + control: Control, + state: State, +} + +struct State { + configuration: u8, + map: Mapping, + encoder: Encoder, + queue: VecDeque, + /// The rest of a report longer than a packet, for the next IN. + pending: Vec, + /// The information query armed by SET_REPORT feature 0x01. + query: Option, + /// The mode the guest last set, which the trace says once per change. + mode: Option, + halted: [bool; INTERFACES], + /// Feature reports and queries already reported. + features: Vec, + queries: Vec, + unknown: Vec<(u8, u8, u16, u16)>, + trace: Vec, + counters: Counters, + /// Drops since the last take. + dropped: u64, + last_time: Option, +} + +impl Trackpad { + pub fn new(config: Config, serial: &str) -> Self { + Self { + control: Control::new(descriptors::descriptors(config.identity.product(), serial)), + state: State { + configuration: 0, + map: Mapping::mt2(config.surface), + encoder: Encoder::new(), + queue: VecDeque::with_capacity(QUEUE), + pending: Vec::new(), + query: None, + mode: None, + halted: [false; INTERFACES], + features: Vec::new(), + queries: Vec::new(), + unknown: Vec::new(), + trace: Vec::new(), + counters: Counters::default(), + dropped: 0, + last_time: None, + }, + } + } + + /// The host surface the function maps. + pub fn surface(&self) -> Surface { + self.state.map.surface() + } + + /// Map `surface` from now on: a touchpad that arrived after the + /// cabling, which was made with the MT2's own size. Feature 0xD9 and the + /// frames that follow take it. + pub fn set_surface(&mut self, surface: Surface) { + self.state.map = Mapping::mt2(surface); + } + + /// One host frame, for the guest's next interrupt IN. + pub fn frame(&mut self, frame: Frame) { + let state = &mut self.state; + state.counters.received += 1; + if let Some(last) = state.last_time.replace(frame.time_us) { + let gap = frame.time_us.saturating_sub(last); + if gap < REPORTING_GAP_US { + state.counters.reporting_us += gap; + } + } + if state.configuration == 0 { + state.queue.clear(); + state.queue.push_back(frame); + return; + } + if state.queue.len() >= COALESCE_FROM + && let Some(back) = state.queue.back_mut() + && same_contacts(back, &frame) + { + *back = frame; + state.counters.coalesced += 1; + return; + } + if state.queue.len() == QUEUE { + state.queue.pop_front(); + state.counters.dropped += 1; + state.dropped += 1; + } + state.queue.push_back(frame); + } + + /// What the function did since the last take: configurations, the mode + /// and features the guest asked for, each unknown request once, and the + /// frames dropped meanwhile. + pub fn take_trace(&mut self) -> Vec { + let mut trace = core::mem::take(&mut self.state.trace); + if self.state.dropped != 0 { + trace.push(TrackpadEvent::Dropped(core::mem::take( + &mut self.state.dropped, + ))); + } + trace + } + + pub fn counters(&self) -> Counters { + self.state.counters + } + + /// Whether the guest has the function configured. + pub fn configured(&self) -> bool { + self.state.configuration != 0 + } +} + +/// Whether two frames list the same contacts, touching and confident +/// alike, and the same buttons. +fn same_contacts(a: &Frame, b: &Frame) -> bool { + a.buttons == b.buttons + && a.fingers().len() == b.fingers().len() + && a.fingers() + .iter() + .zip(b.fingers()) + .all(|(a, b)| (a.id, a.tip, a.confident) == (b.id, b.tip, b.confident)) +} + +impl State { + fn note(&mut self, event: TrackpadEvent) { + if self.trace.len() < TRACE { + self.trace.push(event); + } + } + + /// A request no table answers: reported once, then STALLed. + fn unknown(&mut self, setup: Setup) -> Result { + let key = (setup.request_type, setup.request, setup.value, setup.index); + if !self.unknown.contains(&key) && self.unknown.len() < UNKNOWN { + self.unknown.push(key); + self.note(TrackpadEvent::Unknown { + request_type: key.0, + request: key.1, + value: key.2, + index: key.3, + }); + } + Err(Stall) + } + + /// Forget what the guest was sent: a bus reset or a new configuration. + fn forget(&mut self) { + self.encoder.reset(); + self.pending.clear(); + self.query = None; + self.halted = [false; INTERFACES]; + // Only the newest frame is still the pad's state. + if let Some(newest) = self.queue.pop_back() { + self.queue.clear(); + self.queue.push_back(newest); + } + } + + fn interface(setup: &Setup) -> Option { + let interface = usize::from(setup.index & 0xff); + (interface < INTERFACES && setup.index >> 8 == 0).then_some(interface) + } + + fn endpoint(setup: &Setup) -> Option { + ENDPOINTS + .iter() + .position(|&endpoint| u16::from(endpoint) == setup.index) + } + + /// A HID class request to interface `interface`. + fn class(&mut self, setup: Setup, interface: usize, data: &[u8]) -> Result { + let (kind, id) = ((setup.value >> 8) as u8, setup.value as u8); + let multitouch = interface == usize::from(MULTITOUCH); + match (setup.request, setup.device_to_host()) { + (GET_REPORT, true) if multitouch && kind == FEATURE_REPORT => { + let answer = if id == QUERY { + self.query + .and_then(|query| descriptors::query(query, &self.map)) + } else { + descriptors::feature(id, &self.map) + }; + let Some(answer) = answer else { + return self.unknown(setup); + }; + if !self.features.contains(&id) { + self.features.push(id); + self.note(TrackpadEvent::Feature(id)); + } + Ok(Outcome::Data(answer)) + } + (SET_REPORT, false) if multitouch && kind == FEATURE_REPORT => match (id, data) { + (QUERY, [QUERY, query, ..]) => { + let answered = descriptors::query(*query, &self.map).is_some(); + if !self.queries.contains(query) { + self.queries.push(*query); + self.note(TrackpadEvent::Query { + id: *query, + answered, + }); + } + if !answered { + self.query = None; + return self.unknown(setup); + } + self.query = Some(*query); + Ok(Outcome::Done) + } + (MODE, [MODE, mode, ..]) => { + // Linux sends it again after each reset-resume. + if self.mode.replace(*mode) != Some(*mode) { + self.note(TrackpadEvent::Mode(*mode)); + } + Ok(Outcome::Done) + } + _ => self.unknown(setup), + }, + (GET_REPORT, true) if !multitouch => { + let declared = DECLARED + .iter() + .find(|&&(n, declared_kind, declared_id, _)| { + usize::from(n) == interface && declared_kind == kind && declared_id == id + }); + match declared { + Some(&(_, _, id, bytes)) => { + let mut answer = vec![0u8; bytes + usize::from(id != 0)]; + answer[0] = id; + Ok(Outcome::Data(answer)) + } + None => self.unknown(setup), + } + } + // The vendor interface's feature and the actuator's output + // reports are taken and ignored: the pad's click is mechanical. + (SET_REPORT, false) if !multitouch => Ok(Outcome::Done), + (GET_IDLE, true) => Ok(Outcome::Data(vec![0])), + // Reports go out on change alone (as `usb::hid`'s). + (SET_IDLE, false) if setup.value >> 8 == 0 => Ok(Outcome::Done), + (GET_PROTOCOL, true) => Ok(Outcome::Data(vec![REPORT_PROTOCOL])), + (SET_PROTOCOL, false) if setup.value == u16::from(REPORT_PROTOCOL) => Ok(Outcome::Done), + _ => self.unknown(setup), + } + } + + /// One IN packet on the multitouch endpoint: the rest of a long report, + /// else the next frame's report, else the header-only report owed after + /// a lift. + fn interrupt_in(&mut self, buffer: &mut [u8]) -> Reply { + if self.pending.is_empty() { + let mut report = Vec::new(); + if let Some(frame) = self.queue.pop_front() { + self.encoder.encode(&frame, &self.map, &mut report); + } else if !self.encoder.tail(&mut report) { + return Reply::Nak; + } + self.counters.sent += 1; + self.pending = report; + } + let n = self.pending.len().min(MAX_PACKET).min(buffer.len()); + buffer[..n].copy_from_slice(&self.pending[..n]); + self.pending.drain(..n); + Reply::Ack(n) + } +} + +impl Requests for State { + fn configure(&mut self, value: u8) -> Result<(), Stall> { + if value != self.configuration { + self.note(TrackpadEvent::Configured(value)); + } + self.configuration = value; + self.forget(); + Ok(()) + } + + fn request(&mut self, setup: Setup, data: &[u8]) -> Result { + let read = setup.device_to_host(); + match (setup.kind(), setup.recipient(), setup.request, read) { + (CLASS, RECIPIENT_INTERFACE, ..) => match Self::interface(&setup) { + Some(interface) => self.class(setup, interface, data), + None => self.unknown(setup), + }, + (STANDARD, RECIPIENT_INTERFACE, GET_DESCRIPTOR, true) => { + let descriptor = Self::interface(&setup).and_then(|interface| { + match ((setup.value >> 8) as u8, setup.value as u8) { + (HID, 0) => descriptors::report_descriptor(interface) + .map(|report| descriptors::hid_descriptor(report.len()).to_vec()), + (REPORT, 0) => { + descriptors::report_descriptor(interface).map(<[u8]>::to_vec) + } + _ => None, + } + }); + match descriptor { + Some(bytes) => Ok(Outcome::Data(bytes)), + None => self.unknown(setup), + } + } + (STANDARD, RECIPIENT_INTERFACE, GET_STATUS, true) + if Self::interface(&setup).is_some() => + { + Ok(Outcome::Data(vec![0, 0])) + } + (STANDARD, RECIPIENT_INTERFACE, GET_INTERFACE, true) + if Self::interface(&setup).is_some() => + { + Ok(Outcome::Data(vec![0])) + } + (STANDARD, RECIPIENT_INTERFACE, SET_INTERFACE, false) + if setup.value == 0 && Self::interface(&setup).is_some() => + { + Ok(Outcome::Done) + } + (STANDARD, RECIPIENT_ENDPOINT, GET_STATUS, true) => match Self::endpoint(&setup) { + Some(n) => Ok(Outcome::Data(vec![u8::from(self.halted[n]), 0])), + None => self.unknown(setup), + }, + (STANDARD, RECIPIENT_ENDPOINT, CLEAR_FEATURE | SET_FEATURE, false) + if setup.value == ENDPOINT_HALT => + { + match Self::endpoint(&setup) { + Some(n) => { + self.halted[n] = setup.request == SET_FEATURE; + Ok(Outcome::Done) + } + None => self.unknown(setup), + } + } + _ => self.unknown(setup), + } + } +} + +impl BusPeer for Trackpad { + fn reset(&mut self) -> Result<()> { + self.control.reset(&mut self.state)?; + self.state.forget(); + Ok(()) + } + + fn packet(&mut self, endpoint: u8, token: Token, data: &mut [u8]) -> Result { + if endpoint == 0 { + return self.control.packet(token, data, &mut self.state); + } + let state = &mut self.state; + let Some(n) = ENDPOINTS.iter().position(|&ours| ours == endpoint | 0x80) else { + return Ok(Reply::Stall); + }; + Ok(match token { + _ if state.configuration == 0 || state.halted[n] => Reply::Stall, + Token::In if n == usize::from(MULTITOUCH) => state.interrupt_in(data), + // The vendor and actuator interfaces never report. + Token::In => Reply::Nak, + Token::Out | Token::Setup => Reply::Stall, + }) + } +} + +impl Function for Trackpad { + fn set_time(&mut self, _now: u64) {} + + fn ready_at(&self, endpoint: u8) -> Option { + let state = &self.state; + let multitouch = ENDPOINTS[usize::from(MULTITOUCH)]; + if endpoint | 0x80 != multitouch + || state.configuration == 0 + || state.halted[usize::from(MULTITOUCH)] + { + return None; + } + (!state.queue.is_empty() || !state.pending.is_empty() || state.encoder.owes_tail()) + .then_some(0) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/stela-soc/src/usb/trackpad/function/tests.rs b/crates/stela-soc/src/usb/trackpad/function/tests.rs new file mode 100644 index 0000000000..0d65561b0a --- /dev/null +++ b/crates/stela-soc/src/usb/trackpad/function/tests.rs @@ -0,0 +1,629 @@ +// SPDX-License-Identifier: GPL-2.0-only +// The expected descriptors and feature answers are VoodooInput's (see +// the parent module). +use super::*; +use crate::usb::control::{ + CONFIGURATION, DEVICE, GET_CONFIGURATION, INTERFACE, SET_ADDRESS, SET_CONFIGURATION, STRING, + string, + tests::{setup, transfer}, +}; +use crate::usb::trackpad::{Identity, serial}; +use alloc::vec::Vec; +use stela_drivers::input::multitouch::Finger; + +const ELAN: Surface = Surface { + width_um: 126_900, + height_um: 82_000, +}; +const ENGLISH: u16 = 0x0409; + +fn trackpad(identity: Identity) -> Trackpad { + Trackpad::new( + Config { + identity, + surface: ELAN, + }, + &serial(0x0011_2233_4455_6677), + ) +} + +fn enumerate(t: &mut Trackpad) { + transfer(t, setup(0, SET_ADDRESS, 3, 0, 0), &[]).unwrap(); + transfer(t, setup(0, SET_CONFIGURATION, 1, 0, 0), &[]).unwrap(); +} + +fn configured() -> Trackpad { + let mut t = trackpad(Identity::MagicTrackpad2); + enumerate(&mut t); + t +} + +fn get_feature(t: &mut Trackpad, id: u8, length: u16) -> Result, Stall> { + transfer( + t, + setup(0xa1, GET_REPORT, 0x0300 | u16::from(id), 1, length), + &[], + ) +} + +fn set_feature(t: &mut Trackpad, id: u8, data: &[u8]) -> Result, Stall> { + transfer( + t, + setup( + 0x21, + SET_REPORT, + 0x0300 | u16::from(id), + 1, + data.len() as u16, + ), + data, + ) +} + +/// One interrupt transfer on endpoint `endpoint`, packet by packet until a +/// short one: `None` for a NAK, `Err` for a STALL. +fn read(t: &mut Trackpad, endpoint: u8) -> core::result::Result>, ()> { + let mut report = Vec::new(); + loop { + let mut packet = [0u8; 64]; + match t.packet(endpoint, Token::In, &mut packet).unwrap() { + Reply::Ack(n) => { + report.extend_from_slice(&packet[..n]); + if n < 64 { + return Ok(Some(report)); + } + } + Reply::Nak if report.is_empty() => return Ok(None), + Reply::Nak => panic!("a NAK inside a report"), + Reply::Stall => return Err(()), + } + } +} + +fn report(t: &mut Trackpad) -> Vec { + read(t, 0x83).unwrap().expect("a report is due") +} + +/// Pad units of the ELAN over its millimetres, as the host's frames round +/// them. +fn elan(id: u8, x: u64, y: u64, tip: bool, confident: bool) -> Finger { + Finger { + id, + x_um: ((x * 126_900 + 3987 / 2) / 3987) as u32, + y_um: ((y * 82_000 + 2579 / 2) / 2579) as u32, + tip, + confident, + } +} + +fn hex(text: &str) -> Vec { + text.split_whitespace() + .map(|byte| u8::from_str_radix(byte, 16).unwrap()) + .collect() +} + +#[test] +fn enumerates_as_05ac_0265() { + let mut t = trackpad(Identity::MagicTrackpad2); + let device = transfer(&mut t, setup(0x80, GET_DESCRIPTOR, 0x100, 0, 18), &[]).unwrap(); + assert_eq!( + device, + [ + 18, DEVICE, 0x00, 0x02, 0, 0, 0, 64, 0xac, 0x05, 0x65, 0x02, 0x55, 0x08, 1, 2, 3, 1 + ] + ); + enumerate(&mut t); + assert_eq!( + transfer(&mut t, setup(0x80, GET_CONFIGURATION, 0, 0, 1), &[]).unwrap(), + [1] + ); + let config = transfer(&mut t, setup(0x80, GET_DESCRIPTOR, 0x200, 0, 255), &[]).unwrap(); + assert_eq!(config[1], CONFIGURATION); + assert_eq!( + usize::from(u16::from_le_bytes([config[2], config[3]])), + config.len() + ); + assert_eq!(config[4], 3, "three interfaces"); + assert_eq!(config[7], 0xc0, "self-powered, no remote wakeup"); + // Walk it: each interface, its HID descriptor and its endpoint. + let (mut interfaces, mut hids, mut endpoints) = (Vec::new(), Vec::new(), Vec::new()); + let mut at = usize::from(config[0]); + while at < config.len() { + let d = &config[at..at + usize::from(config[at])]; + match d[1] { + INTERFACE => interfaces.push((d[2], d[4], d[5], d[6], d[7])), + HID => hids.push(u16::from_le_bytes([d[7], d[8]])), + 0x05 => endpoints.push((d[2], d[3], u16::from_le_bytes([d[4], d[5]]), d[6])), + other => panic!("descriptor type {other:#x}"), + } + at += d.len(); + } + assert_eq!(at, config.len()); + assert_eq!( + interfaces, + [(0, 1, 3, 0, 0), (1, 1, 3, 0, 2), (2, 1, 3, 0, 0)], + "HID; the multitouch interface's protocol is mouse" + ); + assert_eq!(hids, [21, 110, 36]); + assert_eq!( + endpoints, + [(0x81, 3, 64, 8), (0x83, 3, 64, 1), (0x84, 3, 64, 8)] + ); + // The report descriptors, VoodooInput's on interfaces 1 and 2. + for (interface, bytes) in [ + (0, &descriptors::VENDOR_DESCRIPTOR[..]), + (1, &descriptors::MULTITOUCH_DESCRIPTOR[..]), + (2, &descriptors::ACTUATOR_DESCRIPTOR[..]), + ] { + let got = transfer( + &mut t, + setup(0x81, GET_DESCRIPTOR, 0x2200, interface, 512), + &[], + ) + .unwrap(); + assert_eq!(got, bytes); + let hid = transfer( + &mut t, + setup(0x81, GET_DESCRIPTOR, 0x2100, interface, 9), + &[], + ) + .unwrap(); + assert_eq!(hid, descriptors::hid_descriptor(bytes.len())); + } + assert_eq!( + &descriptors::MULTITOUCH_DESCRIPTOR[..4], + [0x05, 0x01, 0x09, 0x02] + ); + assert_eq!( + &descriptors::MULTITOUCH_DESCRIPTOR[104..], + [0x96, 0x6b, 0x05, 0x81, 0x00, 0xc0] + ); + // The strings. + for (n, text) in [ + (1, "Apple Inc."), + (2, "Magic Trackpad 2"), + (3, serial(0x0011_2233_4455_6677).as_str()), + ] { + assert_eq!( + transfer( + &mut t, + setup( + 0x80, + GET_DESCRIPTOR, + u16::from(STRING) << 8 | n, + ENGLISH, + 255 + ), + &[] + ) + .unwrap(), + string(text) + ); + } + // Full speed only. + assert!(transfer(&mut t, setup(0x80, GET_DESCRIPTOR, 0x600, 0, 10), &[]).is_err()); +} + +#[test] +fn builtin_identity_is_0281() { + let mut t = trackpad(Identity::Builtin); + let device = transfer(&mut t, setup(0x80, GET_DESCRIPTOR, 0x100, 0, 18), &[]).unwrap(); + assert_eq!( + (device[8], device[9], device[10], device[11]), + (0xac, 0x05, 0x81, 0x02) + ); +} + +#[test] +fn feature_protocol() { + let mut t = configured(); + let map = Mapping::mt2(ELAN); + set_feature(&mut t, 0x01, &[0x01, 0xd3]).unwrap(); + assert_eq!( + get_feature(&mut t, 0x01, 64).unwrap(), + [0x01, 0xd3, 0x00, 0x0c, 0x00] + ); + // Every query VoodooInput answers, with its length. + for (query, length) in [ + (0xdb, 0x49), + (0xd1, 0x01), + (0xd0, 0x0f), + (0xa1, 0x06), + (0x7f, 0x04), + (0xc8, 0x01), + ] { + set_feature(&mut t, 0x01, &[0x01, query]).unwrap(); + assert_eq!( + get_feature(&mut t, 0x01, 64).unwrap(), + [0x01, query, 0x00, length, 0x00] + ); + } + // Query 0xD9 is answered with the surface itself. + set_feature(&mut t, 0x01, &[0x01, 0xd9]).unwrap(); + assert_eq!(get_feature(&mut t, 0x01, 64).unwrap(), map.d9()); + assert_eq!(get_feature(&mut t, 0x00, 64).unwrap(), [0x00, 0x01]); + assert_eq!(get_feature(&mut t, 0xd1, 64).unwrap(), [0xd1, 0x81]); + assert_eq!( + get_feature(&mut t, 0xd3, 64).unwrap(), + hex("d3 01 16 1e 03 95 00 14 1e 62 05 00 00") + ); + assert_eq!( + get_feature(&mut t, 0xd0, 64).unwrap(), + hex("d0 02 01 00 14 01 00 1e 00 02 14 02 01 0e 02 00") + ); + assert_eq!( + get_feature(&mut t, 0xa1, 64).unwrap(), + hex("a1 00 00 05 00 fc 01") + ); + assert_eq!(get_feature(&mut t, 0xd9, 64).unwrap(), map.d9()); + assert_eq!( + get_feature(&mut t, 0x7f, 64).unwrap(), + hex("7f 00 00 00 00") + ); + assert_eq!(get_feature(&mut t, 0xc8, 64).unwrap(), [0xc8, 0x08]); + assert_eq!(get_feature(&mut t, 0x02, 64).unwrap(), [0x02, 0x01]); + // 0xDB: VoodooInput's composite with our surface, 72 bytes over two + // packets of endpoint 0. + let mut db = hex( + "db 01 02 00 d1 81 0d 00 d3 01 16 1e 03 95 00 14 1e 62 05 00 00 10 00 \ + d0 02 01 00 14 01 00 1e 00 02 14 02 01 0e 02 00 07 00 a1 00 00 05 00 fc 01 11 00", + ); + db.extend_from_slice(&map.d9()); + db.extend_from_slice(&hex("7f 00 00 00 00")); + assert_eq!(db.len(), 72); + assert_eq!(get_feature(&mut t, 0xdb, 255).unwrap(), db); + // Each feature once in the trace, in the order first asked. + let trace = t.take_trace(); + let features: Vec = trace + .iter() + .filter_map(|event| match event { + TrackpadEvent::Feature(id) => Some(*id), + _ => None, + }) + .collect(); + assert_eq!( + features, + [ + 0x01, 0x00, 0xd1, 0xd3, 0xd0, 0xa1, 0xd9, 0x7f, 0xc8, 0x02, 0xdb + ] + ); + assert!(trace.contains(&TrackpadEvent::Query { + id: 0xd3, + answered: true + })); + assert!(t.take_trace().is_empty()); +} + +#[test] +fn mode_switch_logged() { + let mut t = configured(); + t.take_trace(); + // Linux's and Windows' switch: SET_REPORT wValue 0x0302, wIndex 1. + let mode = |t: &mut Trackpad, value: u8| { + transfer(t, setup(0x21, SET_REPORT, 0x0302, 1, 2), &[0x02, value]).unwrap(); + }; + mode(&mut t, 1); + assert_eq!(t.take_trace(), [TrackpadEvent::Mode(1)]); + // Windows reads it first. + assert_eq!(get_feature(&mut t, 0x02, 2).unwrap(), [0x02, 0x01]); + // Linux sends it again after each reset-resume: one line per change. + mode(&mut t, 1); + t.reset().unwrap(); + enumerate(&mut t); + mode(&mut t, 1); + assert!( + !t.take_trace().contains(&TrackpadEvent::Mode(1)), + "the same mode again" + ); + mode(&mut t, 0); + mode(&mut t, 0); + assert_eq!(t.take_trace(), [TrackpadEvent::Mode(0)]); +} + +#[test] +fn unknown_stalls_once() { + let mut t = configured(); + t.take_trace(); + for _ in 0..3 { + assert!(get_feature(&mut t, 0x42, 64).is_err()); + } + let unknown = TrackpadEvent::Unknown { + request_type: 0xa1, + request: GET_REPORT, + value: 0x0342, + index: 1, + }; + assert_eq!(t.take_trace(), [unknown]); + // An input report the tables do not hold, and an unknown query. + assert!(transfer(&mut t, setup(0xa1, GET_REPORT, 0x0102, 1, 64), &[]).is_err()); + assert!(set_feature(&mut t, 0x01, &[0x01, 0x42]).is_err()); + assert!(get_feature(&mut t, 0x01, 64).is_err(), "nothing armed"); + assert!(set_feature(&mut t, 0x01, &[0x01, 0x42]).is_err()); + let trace = t.take_trace(); + assert!(trace.contains(&TrackpadEvent::Query { + id: 0x42, + answered: false + })); + assert_eq!( + trace + .iter() + .filter(|e| matches!(e, TrackpadEvent::Unknown { .. })) + .count(), + 3, + "GET input 0x02, SET query, GET query: each once" + ); + // The pipe works after each STALL. + assert_eq!(get_feature(&mut t, 0xd1, 64).unwrap(), [0xd1, 0x81]); +} + +#[test] +fn the_other_interfaces_answer_their_declared_reports() { + let mut t = configured(); + assert_eq!( + transfer(&mut t, setup(0xa1, GET_REPORT, 0x0300, 0, 8), &[]).unwrap(), + [0] + ); + let actuator = transfer(&mut t, setup(0xa1, GET_REPORT, 0x013f, 2, 64), &[]).unwrap(); + assert_eq!(actuator.len(), 16); + assert_eq!(actuator[0], 0x3f); + assert!(actuator[1..].iter().all(|b| *b == 0)); + // The actuator's haptic output is taken and ignored. + let mut haptic = vec![0x53]; + haptic.extend([0x11; 63]); + transfer(&mut t, setup(0x21, SET_REPORT, 0x0253, 2, 64), &haptic).unwrap(); + assert!(transfer(&mut t, setup(0xa1, GET_REPORT, 0x0301, 0, 8), &[]).is_err()); + // Their endpoints never report. + assert_eq!(read(&mut t, 0x81), Ok(None)); + assert_eq!(read(&mut t, 0x84), Ok(None)); + assert_eq!(t.ready_at(0x81), None); + // Idle and protocol requests. + transfer(&mut t, setup(0x21, SET_IDLE, 0, 1, 0), &[]).unwrap(); + assert!(transfer(&mut t, setup(0x21, SET_IDLE, 0x0400, 1, 0), &[]).is_err()); + assert_eq!( + transfer(&mut t, setup(0xa1, GET_PROTOCOL, 0, 1, 1), &[]).unwrap(), + [1] + ); +} + +#[test] +fn frames_flow_without_switch() { + let mut t = configured(); + assert_eq!(t.ready_at(0x83), None); + assert_eq!(read(&mut t, 0x83), Ok(None)); + t.frame(Frame::new(1_000_000, 0, &[elan(0, 1993, 1289, true, true)])); + assert_eq!(t.ready_at(0x83), Some(0)); + assert_eq!( + report(&mut t), + hex("02 00 00 00 00 00 00 03 31 44 1f 00 7f 60 f9 6b 14 14 0a 05 81") + ); + assert_eq!(t.ready_at(0x83), None); + // The lift, then the header alone, then nothing. + t.frame(Frame::new( + 1_008_000, + 0, + &[elan(0, 1993, 1289, false, true)], + )); + let stop = report(&mut t); + assert_eq!(stop[7], 0x02); + assert_eq!(stop[15] >> 5, 7, "Stop"); + assert_eq!(t.ready_at(0x83), Some(0), "the header-only report is owed"); + assert_eq!(report(&mut t), hex("02 00 00 00 00 00 00 02 31 84 1f 00")); + assert_eq!(read(&mut t, 0x83), Ok(None)); + assert_eq!(t.counters().received, 2); + assert_eq!(t.counters().sent, 3); + assert_eq!(t.counters().reporting_us, 8_000); +} + +#[test] +fn an_unconfigured_guest_keeps_the_newest_frame() { + let mut t = trackpad(Identity::MagicTrackpad2); + for n in 0..50 { + t.frame(Frame::new( + n * 8_000, + 0, + &[elan(0, 1000 + n, 1000, true, true)], + )); + } + // Endpoints of an unconfigured device STALL. + assert_eq!(read(&mut t, 0x83), Err(())); + assert_eq!(t.ready_at(0x83), None); + enumerate(&mut t); + let r = report(&mut t); + assert_eq!(r.len(), 21); + assert_eq!(r[15] >> 5, 3, "Start"); + assert_eq!(read(&mut t, 0x83), Ok(None), "one frame was kept"); +} + +/// A report's first finger's X. +fn first_x(report: &[u8]) -> i16 { + i16::from_le_bytes([report[12], report[13] & 0x1f]) << 3 >> 3 +} + +#[test] +fn queue_bound_keeps_lift() { + let mut t = configured(); + t.take_trace(); + // One finger moving for 100 frames without an IN: past the second + // queued frame its motion coalesces into the newest, counted apart. + for n in 0..100u64 { + t.frame(Frame::new( + n * 8_000, + 0, + &[elan(0, 500 + 10 * n, 1000, true, true)], + )); + } + // The lift differs from the newest: it queues behind it. + t.frame(Frame::new(800_000, 0, &[])); + assert!(t.take_trace().is_empty(), "nothing dropped"); + let counters = t.counters(); + assert_eq!((counters.dropped, counters.coalesced), (0, 98)); + let mut reports = Vec::new(); + while let Some(r) = read(&mut t, 0x83).unwrap() { + reports.push(r); + } + assert_eq!( + reports.len(), + 4, + "the first and newest motion, the lift, the header" + ); + assert_eq!(reports[0][15] >> 5, 3, "Start"); + assert_eq!(reports[1][15] >> 5, 4, "Active"); + // The Active report is the newest motion. + let moved = Mapping::mt2(ELAN) + .to_mt2(elan(0, 500 + 990, 1000, true, true).x_um, 0) + .0; + assert_eq!(first_x(&reports[1]), moved); + assert_eq!((reports[2].len(), reports[2][15] >> 5), (21, 7), "Stop"); + assert_eq!(reports[3].len(), 12, "the header alone"); + // Contacts that keep changing drop one frame each past the bound. + let mut t = configured(); + t.take_trace(); + for n in 0..100u64 { + let fingers = [ + elan(0, 500, 1000, true, true), + elan(1, 900, 1000, true, true), + ]; + let count = 1 + (n % 2) as usize; + t.frame(Frame::new(n * 8_000, 0, &fingers[..count])); + } + assert_eq!(t.take_trace(), [TrackpadEvent::Dropped(100 - QUEUE as u64)]); + assert_eq!(t.counters().coalesced, 0); +} + +#[test] +fn a_slow_guest_lags_two_frames_at_most() { + // The pad reports twice per guest IN: the guest's next report is never + // more than two frames behind the pad, where a queue filling to its + // bound would hold it back by up to 31. + let mut t = configured(); + let mut x = 500; + let mut frame = |t: &mut Trackpad| { + x += 10; + t.frame(Frame::new(x * 1_000, 0, &[elan(0, x, 1000, true, true)])); + Mapping::mt2(ELAN) + .to_mt2(elan(0, x, 1000, true, true).x_um, 0) + .0 + }; + let mut xs = Vec::new(); + for _ in 0..60 { + xs.push(frame(&mut t)); + xs.push(frame(&mut t)); + let reported = first_x(&read(&mut t, 0x83).unwrap().unwrap()); + // The newest frame or one of the two before it. + let recent = &xs[xs.len().saturating_sub(3)..]; + assert!(recent.contains(&reported), "{reported} not in {recent:?}"); + } + let mut queued = 0; + while read(&mut t, 0x83).unwrap().is_some() { + queued += 1; + } + assert!(queued <= 2, "{queued} frames queued"); + let counters = t.counters(); + assert_eq!(counters.dropped, 0); + assert!(counters.coalesced >= 55, "{counters:?}"); +} + +#[test] +fn a_new_surface_maps_later_frames() { + // A touchpad that arrives after the cabling gives its own surface. + let mut t = configured(); + let fixture = Surface { + width_um: 100_000, + height_um: 60_000, + }; + t.set_surface(fixture); + assert_eq!(t.surface(), fixture); + let d9 = get_feature(&mut t, 0xd9, 64).unwrap(); + assert_eq!(d9[..9], Mapping::mt2(fixture).d9()[..9]); + assert_eq!(&d9[1..5], &10_000u32.to_le_bytes()); + // Its centre is the MT2's. + let centre = Finger { + id: 0, + x_um: 50_000, + y_um: 30_000, + tip: true, + confident: true, + }; + t.frame(Frame::new(0, 0, &[centre])); + assert_eq!(first_x(&report(&mut t)), 128); +} + +#[test] +fn reset_frees_slots() { + let mut t = configured(); + let finger = |time| Frame::new(time, 0, &[elan(3, 2000, 1000, true, true)]); + t.frame(finger(0)); + report(&mut t); + t.frame(finger(8_000)); + assert_eq!(report(&mut t)[15] >> 5, 4, "Active"); + // A bus reset (the guest slept), then a new enumeration: the finger + // still down starts again, as identifier 1, with no stale Stop. + t.reset().unwrap(); + assert_eq!(read(&mut t, 0x83), Err(()), "unconfigured"); + enumerate(&mut t); + t.frame(finger(500_000)); + let again = report(&mut t); + assert_eq!(again.len(), 21, "one finger, no Stop beside it"); + assert_eq!((again[15] >> 5, again[20] & 0xf), (3, 1)); + let trace = t.take_trace(); + assert!(trace.contains(&TrackpadEvent::Configured(0))); + assert_eq!( + trace + .iter() + .filter(|e| **e == TrackpadEvent::Configured(1)) + .count(), + 2 + ); +} + +#[test] +fn a_resting_palm_stays_a_palm() { + let mut t = configured(); + // A palm the pad never trusts, resting through typing, then lifting. + for (n, tip) in [true, true, true, false].into_iter().enumerate() { + t.frame(Frame::new( + n as u64 * 8_000, + 0, + &[elan(2, 700, 2300, tip, false)], + )); + let r = report(&mut t); + assert_eq!(r[1], 0, "no click"); + assert_eq!(r[15] >> 2 & 7, 6, "typed Palm in every report"); + } +} + +#[test] +fn six_fingers_span_two_packets() { + let mut t = configured(); + let six: Vec = (0..6) + .map(|n| elan(n, 400 + 500 * u64::from(n), 1200, true, true)) + .collect(); + t.frame(Frame::new(0, 0, &six)); + let mut first = [0u8; 64]; + assert_eq!( + t.packet(0x83, Token::In, &mut first).unwrap(), + Reply::Ack(64) + ); + assert_eq!(t.ready_at(0x83), Some(0), "the rest is due"); + let mut rest = [0u8; 64]; + assert_eq!( + t.packet(0x83, Token::In, &mut rest).unwrap(), + Reply::Ack(12 + 6 * 9 - 64) + ); + assert_eq!(read(&mut t, 0x83), Ok(None)); +} + +#[test] +fn halted_endpoint_stalls_until_cleared() { + let mut t = configured(); + transfer(&mut t, setup(0x02, SET_FEATURE, 0, 0x83, 0), &[]).unwrap(); + assert_eq!( + transfer(&mut t, setup(0x82, GET_STATUS, 0, 0x83, 2), &[]).unwrap(), + [1, 0] + ); + t.frame(Frame::new(0, 0, &[elan(0, 100, 100, true, true)])); + assert_eq!(t.ready_at(0x83), None); + assert_eq!(read(&mut t, 0x83), Err(())); + transfer(&mut t, setup(0x02, CLEAR_FEATURE, 0, 0x83, 0), &[]).unwrap(); + assert_eq!(report(&mut t).len(), 21); +} diff --git a/crates/stela-soc/src/usb/trackpad/report.rs b/crates/stela-soc/src/usb/trackpad/report.rs new file mode 100644 index 0000000000..e3ad464ee3 --- /dev/null +++ b/crates/stela-soc/src/usb/trackpad/report.rs @@ -0,0 +1,373 @@ +// SPDX-License-Identifier: GPL-2.0-only +// The report layout and the constants of a pad without pressure follow +// VoodooInput d8978137 (VoodooInputSimulatorDevice.{hpp,cpp}, GPL-2.0; +// Copyright (c) 2018-2019 Alexandre Daoud and Kishor Prins), and the range +// and decoding Linux hid-magicmouse.c (Copyright (c) 2010 Michael Poole and +// Chase Douglas). See NOTICE. +//! The Magic Trackpad 2's multitouch input report (report 0x02 on its +//! multitouch interface), from host touch [`Frame`]s. +//! +//! A report is a 12-byte header and 9 bytes per finger, at most 15 fingers, +//! as Linux `__magicmouse_raw_event` checks it (`TRACKPAD2_USB_REPORT_ID`). +//! Header: the report ID, the button in byte 1 bit 0 (Linux `clicks`), five +//! zero bytes, 0x03 while a finger touches or the button is down and 0x02 +//! otherwise, the inner multitouch report ID 0x31 and a 21-bit millisecond +//! timestamp packed as `ms << 3 | 4`, `ms >> 5`, `ms >> 13` (VoodooInput +//! `constructReportGated`). Finger: X and Y as signed 13-bit values, Y +//! upward, the finger type and touch state, touch major and minor, size, +//! pressure, and the identifier with orientation 4 (Linux +//! `magicmouse_emit_touch` reads every field back). +//! +//! Positions use the MT2's own resolution (hid-magicmouse.c +//! `TRACKPAD2_MIN_X`..`TRACKPAD2_DIMENSION_Y`: 7612 units over 160.00 mm, +//! 5065 over 114.90 mm) with the host pad centred on the MT2's centre, so a +//! millimetre of finger travel is a millimetre whether macOS scales by the +//! reported surface (feature 0xD9) or by the MT2's own size. +//! +//! Each host contact takes a slot when it first touches and keeps it until +//! one Stop follows its lift; the identifier is the slot plus one, and new +//! contacts take slots round-robin, so a new touch never reuses the +//! identifier a lift has just freed. A contact's first report is Start, +//! then Active while it touches; the report of the frame where it lifts or +//! leaves the frame carries Stop, at its last position and type, with its +//! sizes and pressure 0. When the pad empties, the next report owed is the +//! 12-byte header alone ([`Encoder::tail`]). +//! +//! The pad states no pressure or size, so a touching finger has +//! VoodooInput's constants for such pads: pressure 5, size 10, major and +//! minor 20, and pressure 120 on every finger while the button is down. +//! Finger types: index, middle, ring and little by report order, palm for a +//! contact the pad marks without confidence, and thumb for the lowest +//! confident finger while four or more contacts touch or the button is +//! down, so a thumb's click and the index finger's drag, and a four-finger +//! pinch, read as macOS expects. That is the behavior VoodooI2C's native +//! engine shows (VoodooI2C is GPL-3.0, so none of its code is used here), +//! except that a palm is never made the thumb. +use alloc::vec::Vec; +use stela_drivers::input::multitouch::{Frame, Surface}; + +pub const REPORT_ID: u8 = 0x02; +pub const HEADER: usize = 12; +pub const FINGER: usize = 9; +/// The most fingers Linux reads from one report. +pub const MAX_FINGERS: usize = 15; +const MULTITOUCH_REPORT_ID: u8 = 0x31; +/// hid-magicmouse.c `TRACKPAD2_MIN_X`/`MAX_X` and `MIN_Y`/`MAX_Y`, Y +/// downward as Linux reports it. +const MT2_X: (i64, i64) = (-3678, 3934); +const MT2_Y: (i64, i64) = (-2478, 2587); +/// `TRACKPAD2_DIMENSION_X`/`_Y`, in micrometres. +const MT2_UM: (i64, i64) = (160_000, 114_900); +/// The millisecond timestamp's width. +const MS_BITS: u32 = 21; + +const MAJOR: u8 = 20; +const MINOR: u8 = 20; +const SIZE: u8 = 10; +const PRESSURE: u8 = 5; +const CLICK_PRESSURE: u8 = 120; +/// VoodooInput's angle: pi/2, Linux orientation 0. +const ORIENTATION: u8 = 4; +/// VoodooInput `TouchStates`. +const START: u8 = 3; +const ACTIVE: u8 = 4; +const STOP: u8 = 7; +/// VoodooInput `MT2FingerType`. +const THUMB: u8 = 1; +const INDEX: u8 = 2; +const PALM: u8 = 6; +/// Contacts touching at once from which the lowest is the thumb. +const THUMB_CONTACTS: usize = 4; + +/// Round `n / d` half away from zero. +fn rdiv(n: i64, d: i64) -> i64 { + let q = n.abs() / d; + let q = if 2 * (n.abs() % d) >= d { q + 1 } else { q }; + if n < 0 { -q } else { q } +} + +/// The least and greatest X and Y feature 0xD9 states after the surface. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum D9Range { + /// VoodooInput's bytes verbatim: X -7356 to 7869 (about twice + /// hid-magicmouse.c's `TRACKPAD2_MIN_X`/`MAX_X`), Y -174 to 9956. Intel + /// macOS takes them, though they are not the range the reports carry. + VoodooInput, + /// The range the reports carry: the host surface's corners. + Emitted, +} + +/// The range feature 0xD9 sends: VoodooInput's, the one Intel macOS is +/// known to take, for the first boot. One edit makes it +/// [`D9Range::Emitted`]. +pub const D9_RANGE: D9Range = D9Range::VoodooInput; + +/// VoodooInput's 0xD9 range bytes (`VoodooInputSimulatorDevice.cpp`). +const VOODOO_INPUT_D9_RANGE: [u8; 8] = [0x44, 0xe3, 0x52, 0xff, 0xbd, 0x1e, 0xe4, 0x26]; + +/// Where a host surface's positions land on the MT2's. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Mapping { + surface: Surface, +} + +impl Mapping { + /// The host surface at the MT2's resolution, centred. + pub fn mt2(surface: Surface) -> Self { + Self { surface } + } + + pub fn surface(&self) -> Surface { + self.surface + } + + /// The MT2 position of host position `x_um`, `y_um` (from the top-left + /// corner, y downward): X, and Y upward as the wire carries it. + pub fn to_mt2(&self, x_um: u32, y_um: u32) -> (i16, i16) { + let centre = |(min, max): (i64, i64)| (min + max).div_euclid(2); + let span = |(min, max): (i64, i64)| max - min; + let width = i64::from(self.surface.width_um); + let height = i64::from(self.surface.height_um); + let x = centre(MT2_X) + rdiv((i64::from(x_um) - width / 2) * span(MT2_X), MT2_UM.0); + let y = centre(MT2_Y) + rdiv((i64::from(y_um) - height / 2) * span(MT2_Y), MT2_UM.1); + ( + x.clamp(MT2_X.0, MT2_X.1) as i16, + -(y.clamp(MT2_Y.0, MT2_Y.1)) as i16, + ) + } + + /// Feature report 0xD9, the sensor surface, with [`D9_RANGE`]. + pub fn d9(&self) -> [u8; 17] { + self.d9_with(D9_RANGE) + } + + /// Feature report 0xD9: the surface's width and height in 0.01 mm + /// (u32), then the least and greatest X and Y (i16, Y upward) of + /// `range`, all little-endian. + pub fn d9_with(&self, range: D9Range) -> [u8; 17] { + let hundredths = |um: u32| um.saturating_add(5) / 10; + let mut report = [0u8; 17]; + report[0] = 0xd9; + report[1..5].copy_from_slice(&hundredths(self.surface.width_um).to_le_bytes()); + report[5..9].copy_from_slice(&hundredths(self.surface.height_um).to_le_bytes()); + match range { + D9Range::VoodooInput => report[9..].copy_from_slice(&VOODOO_INPUT_D9_RANGE), + D9Range::Emitted => { + let (min_x, max_y) = self.to_mt2(0, 0); + let (max_x, min_y) = self.to_mt2(self.surface.width_um, self.surface.height_um); + for (at, value) in [(9, min_x), (11, min_y), (13, max_x), (15, max_y)] { + report[at..at + 2].copy_from_slice(&value.to_le_bytes()); + } + } + } + report + } +} + +/// A contact the guest has seen touch: the host's identifier, and what its +/// last report said of it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Slot { + host: u8, + x: i16, + y: i16, + kind: u8, +} + +/// The MT2 state the guest has been sent. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Encoder { + slots: [Option; MAX_FINGERS], + /// Where the next new contact's slot search starts. + next: usize, + /// The timestamp of the header-only report owed after the last lift. + tail: Option, +} + +/// One finger's 9 bytes. +fn finger(x: i16, y: i16, kind: u8, state: u8, touching: Option, identifier: u8) -> [u8; 9] { + let x = (x as u16) & 0x1fff; + let y = (y as u16) & 0x1fff; + let (major, minor, size, pressure) = match touching { + Some(pressure) => (MAJOR, MINOR, SIZE, pressure), + None => (0, 0, 0, 0), + }; + [ + x as u8, + ((x >> 8) as u8 & 0x1f) | ((y & 0x7) as u8) << 5, + (y >> 3) as u8, + ((y >> 11) as u8 & 0x3) | (kind & 7) << 2 | (state & 7) << 5, + major, + minor, + size, + pressure, + (identifier & 0xf) | ORIENTATION << 5, + ] +} + +fn header(button: bool, active: bool, ms: u32, out: &mut Vec) { + out.extend_from_slice(&[ + REPORT_ID, + u8::from(button), + 0, + 0, + 0, + 0, + 0, + if active { 0x03 } else { 0x02 }, + MULTITOUCH_REPORT_ID, + (ms << 3 | 4) as u8, + (ms >> 5) as u8, + (ms >> 13) as u8, + ]); +} + +/// A frame's time as the report's millisecond counter. +fn millis(time_us: u64) -> u32 { + ((time_us / 1000) % (1 << MS_BITS)) as u32 +} + +impl Encoder { + pub fn new() -> Self { + Self::default() + } + + /// Forget every contact: a reconfigured guest has seen none. + pub fn reset(&mut self) { + *self = Self::default(); + } + + /// Append the report of `frame` to `out`, through `map`, and note what + /// the guest was told. + pub fn encode(&mut self, frame: &Frame, map: &Mapping, out: &mut Vec) { + let ms = millis(frame.time_us); + let button = frame.buttons & 1 != 0; + let touching = |host: u8| { + frame + .fingers() + .iter() + .find(|finger| finger.id == host && finger.tip) + }; + // Contacts that lift in this frame: their slot's last report, then + // Stop. Slots free only after this report, so a new contact cannot + // take the identifier of one stopping beside it. + let mut stopping = [false; MAX_FINGERS]; + for (n, slot) in self.slots.iter().enumerate() { + if let Some(slot) = slot { + stopping[n] = touching(slot.host).is_none(); + } + } + // Contacts landing: the next free slot, round-robin; one that finds + // none waits for a later frame. + let mut started = [false; MAX_FINGERS]; + for finger in frame.fingers().iter().filter(|finger| finger.tip) { + if self + .slots + .iter() + .flatten() + .any(|slot| slot.host == finger.id) + { + continue; + } + let Some(n) = (0..MAX_FINGERS) + .map(|step| (self.next + step) % MAX_FINGERS) + .find(|&n| self.slots[n].is_none()) + else { + break; + }; + self.slots[n] = Some(Slot { + host: finger.id, + x: 0, + y: 0, + kind: INDEX, + }); + started[n] = true; + self.next = (n + 1) % MAX_FINGERS; + } + // Positions and types of the touching contacts, in report order. + let mut order = 0; + let mut touched = 0; + for (n, slot) in self.slots.iter_mut().enumerate() { + let Some(slot) = slot else { + continue; + }; + if !stopping[n] { + let finger = touching(slot.host).expect("a touching slot's contact touches"); + (slot.x, slot.y) = map.to_mt2(finger.x_um, finger.y_um); + slot.kind = if finger.confident { + INDEX + (order % 4) as u8 + } else { + PALM + }; + touched += 1; + } + order += 1; + } + if touched >= THUMB_CONTACTS || button { + // The lowest confident finger: the least Y upward, the last of + // equals, as VoodooI2C's `>=` picks it. + let thumb = self + .slots + .iter() + .enumerate() + .filter_map(|(n, slot)| { + slot.filter(|s| !stopping[n] && s.kind != PALM) + .map(|s| (n, s.y)) + }) + .fold(None, |lowest: Option<(usize, i16)>, (n, y)| match lowest { + Some((_, least)) if y > least => lowest, + _ => Some((n, y)), + }); + if let Some((n, _)) = thumb + && let Some(slot) = &mut self.slots[n] + { + slot.kind = THUMB; + } + } + let pressure = if button { CLICK_PRESSURE } else { PRESSURE }; + header(button, touched > 0 || button, ms, out); + let mut stopped = false; + for (n, entry) in self.slots.iter_mut().enumerate() { + let Some(slot) = *entry else { + continue; + }; + let identifier = n as u8 + 1; + if stopping[n] { + out.extend_from_slice(&finger(slot.x, slot.y, slot.kind, STOP, None, identifier)); + *entry = None; + stopped = true; + } else { + let state = if started[n] { START } else { ACTIVE }; + out.extend_from_slice(&finger( + slot.x, + slot.y, + slot.kind, + state, + Some(pressure), + identifier, + )); + } + } + // The header alone says the button is up too, so it is owed only + // once the button is. + self.tail = (stopped && touched == 0 && !button).then_some(ms); + } + + /// Append the header-only report owed after the last contact's Stop, at + /// that report's time; false, appending nothing, when none is owed. + pub fn tail(&mut self, out: &mut Vec) -> bool { + let Some(ms) = self.tail.take() else { + return false; + }; + header(false, false, ms, out); + true + } + + /// Whether a header-only report is owed. + pub fn owes_tail(&self) -> bool { + self.tail.is_some() + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/stela-soc/src/usb/trackpad/report/tests.rs b/crates/stela-soc/src/usb/trackpad/report/tests.rs new file mode 100644 index 0000000000..a2687dbc1c --- /dev/null +++ b/crates/stela-soc/src/usb/trackpad/report/tests.rs @@ -0,0 +1,458 @@ +// SPDX-License-Identifier: GPL-2.0-only +// The expected reports follow VoodooInput's layout and constants (see the +// parent module); `linux_decode` ports hid-magicmouse.c. +use super::*; +use alloc::{vec, vec::Vec}; +use stela_drivers::input::multitouch::Finger; + +/// The ELAN 04F3:32E2: 3987 by 2579 units over 126.90 by 82.00 mm. +const ELAN: Surface = Surface { + width_um: 126_900, + height_um: 82_000, +}; +/// `ptp/tests.rs`'s fixture pad: 1000 by 600 units over 100 by 60 mm. +const FIXTURE: Surface = Surface { + width_um: 100_000, + height_um: 60_000, +}; + +/// One touch as Linux reads it, with the finger type, which it does not. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Touch { + id: u8, + x: i32, + y: i32, + size: u8, + orientation: i32, + major: u8, + minor: u8, + pressure: u8, + state: u8, + down: bool, + kind: u8, +} + +/// Linux hid-magicmouse.c's MT2 USB path, line for line: +/// `__magicmouse_raw_event`'s `TRACKPAD2_USB_REPORT_ID` case (the size +/// checks and `clicks = data[1]`) and `magicmouse_emit_touch`'s MT2 branch. +/// `None` where Linux drops the report. +fn linux_decode(data: &[u8]) -> Option<(u8, Vec)> { + if data.first() != Some(&REPORT_ID) { + return None; + } + let size = data.len(); + if size < 12 || !(size - 12).is_multiple_of(9) { + return None; + } + let npoints = (size - 12) / 9; + if npoints > 15 { + return None; + } + let touches = (0..npoints) + .map(|ii| { + let t = &data[12 + ii * 9..12 + ii * 9 + 9]; + let b = |n: usize| u32::from(t[n]); + // `int` shifts: the bytes' bits shifted to the top, then an + // arithmetic shift down. + let x = ((b(1) << 27 | b(0) << 19) as i32) >> 19; + let y = -(((b(3) << 30 | b(2) << 22 | b(1) << 14) as i32) >> 19); + let state = t[3] & 0xc0; + Touch { + id: t[8] & 0xf, + x, + y, + size: t[6], + orientation: i32::from(t[8] >> 5) - 4, + major: t[4], + minor: t[5], + pressure: t[7], + state, + down: state == 0x80, + kind: t[3] >> 2 & 7, + } + }) + .collect(); + Some((data[1], touches)) +} + +fn hex(text: &str) -> Vec { + text.split_whitespace() + .map(|byte| u8::from_str_radix(byte, 16).unwrap()) + .collect() +} + +/// Pad units over a pad's millimetres, rounded as the host's frames round +/// them (`ptp_frames`). +fn on(units: (u64, u64), surface: Surface, x: u64, y: u64) -> (u32, u32) { + let scale = + |value: u64, extent: u32, span: u64| ((value * u64::from(extent) + span / 2) / span) as u32; + ( + scale(x, surface.width_um, units.0), + scale(y, surface.height_um, units.1), + ) +} + +fn elan(id: u8, x: u64, y: u64, tip: bool, confident: bool) -> Finger { + let (x_um, y_um) = on((3987, 2579), ELAN, x, y); + Finger { + id, + x_um, + y_um, + tip, + confident, + } +} + +fn encoded(encoder: &mut Encoder, frame: &Frame, map: &Mapping) -> Vec { + let mut out = Vec::new(); + encoder.encode(frame, map, &mut out); + out +} + +#[test] +fn golden_elan_a_to_f() { + let map = Mapping::mt2(ELAN); + let mut e = Encoder::new(); + let ms = |ms: u64| ms * 1000; + // A: a finger lands at the centre. + let a = Frame::new(ms(1000), 0, &[elan(0, 1993, 1289, true, true)]); + assert_eq!( + encoded(&mut e, &a, &map), + hex("02 00 00 00 00 00 00 03 31 44 1f 00 7f 60 f9 6b 14 14 0a 05 81") + ); + // B: it moves. + let b = Frame::new(ms(1008), 0, &[elan(0, 2500, 1000, true, true)]); + assert_eq!( + encoded(&mut e, &b, &map), + hex("02 00 00 00 00 00 00 03 31 84 1f 00 7f 03 2c 88 14 14 0a 05 81") + ); + // C: a second finger lands lower, the button goes down: pressure 120, + // and the lower finger is the thumb. + let c = Frame::new( + ms(1016), + 1, + &[ + elan(0, 2500, 1000, true, true), + elan(1, 1000, 2000, true, true), + ], + ); + assert_eq!( + encoded(&mut e, &c, &map), + hex( + "02 01 00 00 00 00 00 03 31 c4 1f 00 7f 03 2c 88 14 14 0a 78 81 \ + a0 da 7c 67 14 14 0a 78 82" + ) + ); + // D: both lift, listed with their tips up. + let d = Frame::new( + ms(1024), + 0, + &[ + elan(0, 2500, 1000, false, true), + elan(1, 1000, 2000, false, true), + ], + ); + assert_eq!( + encoded(&mut e, &d, &map), + hex( + "02 00 00 00 00 00 00 02 31 04 20 00 7f 03 2c e8 00 00 00 00 81 \ + a0 da 7c e7 00 00 00 00 82" + ) + ); + assert!(e.owes_tail()); + // E: nothing on the pad: the header alone, which is the tail owed. + let empty = Frame::new(ms(1034), 0, &[]); + assert_eq!( + encoded(&mut e, &empty, &map), + hex("02 00 00 00 00 00 00 02 31 54 20 00") + ); + assert!(!e.owes_tail()); + // F: a palm, kept and typed Palm, takes the next identifier. + let f = Frame::new(ms(1042), 0, &[elan(7, 300, 2400, true, false)]); + assert_eq!( + encoded(&mut e, &f, &map), + hex("02 00 00 00 00 00 00 03 31 94 20 00 7c d6 36 7b 14 14 0a 05 83") + ); +} + +#[test] +fn golden_fixture_e2e() { + let map = Mapping::mt2(FIXTURE); + let mut e = Encoder::new(); + let at = |x: u64, y: u64, tip: bool| { + let (x_um, y_um) = on((1000, 600), FIXTURE, x, y); + Finger { + id: 1, + x_um, + y_um, + tip, + confident: true, + } + }; + let one = Frame::new(1_000_000, 0, &[at(500, 300, true)]); + assert_eq!( + encoded(&mut e, &one, &map), + hex("02 00 00 00 00 00 00 03 31 44 1f 00 80 40 f9 6b 14 14 0a 05 81") + ); + let two = Frame::new(1_008_000, 0, &[at(600, 300, true)]); + assert_eq!( + encoded(&mut e, &two, &map), + hex("02 00 00 00 00 00 00 03 31 84 1f 00 5c 42 f9 8b 14 14 0a 05 81") + ); + let lift = Frame::new(1_016_000, 0, &[at(600, 300, false)]); + assert_eq!( + encoded(&mut e, &lift, &map), + hex("02 00 00 00 00 00 00 02 31 c4 1f 00 5c 42 f9 eb 00 00 00 00 81") + ); + let mut tail = Vec::new(); + assert!(e.tail(&mut tail)); + assert_eq!(tail, hex("02 00 00 00 00 00 00 02 31 c4 1f 00")); + tail.clear(); + assert!(!e.tail(&mut tail), "once"); + assert!(tail.is_empty()); +} + +#[test] +fn a_contact_left_out_of_the_frame_stops() { + let map = Mapping::mt2(ELAN); + let mut e = Encoder::new(); + let down = Frame::new(0, 0, &[elan(4, 2000, 1000, true, true)]); + encoded(&mut e, &down, &map); + let gone = Frame::new(8_000, 0, &[]); + let (clicks, touches) = linux_decode(&encoded(&mut e, &gone, &map)).unwrap(); + assert_eq!(clicks, 0); + assert_eq!(touches.len(), 1); + assert_eq!((touches[0].id, touches[0].state), (1, 0xc0)); + assert_eq!( + (touches[0].major, touches[0].size, touches[0].pressure), + (0, 0, 0) + ); + assert!(e.owes_tail()); + // A lift with the button still down owes no header-only report, which + // would say the button is up. + let mut e = Encoder::new(); + let held = Frame::new(0, 1, &[elan(4, 2000, 1000, true, true)]); + encoded(&mut e, &held, &map); + let lifted = Frame::new(8_000, 1, &[]); + let report = encoded(&mut e, &lifted, &map); + assert_eq!((report[1], report[7]), (1, 0x03)); + assert!(!e.owes_tail()); +} + +#[test] +fn linux_round_trip() { + let map = Mapping::mt2(ELAN); + for i in 0..=20u32 { + for j in 0..=20u32 { + let (x_um, y_um) = (ELAN.width_um * i / 20, ELAN.height_um * j / 20); + let (x, y) = map.to_mt2(x_um, y_um); + for button in [0u8, 1] { + let mut e = Encoder::new(); + let finger = Finger { + id: 9, + x_um, + y_um, + tip: true, + confident: true, + }; + for (time, state, down) in [(0, 0x40, false), (8_000, 0x80, true)] { + let report = encoded(&mut e, &Frame::new(time, button, &[finger]), &map); + let (clicks, touches) = linux_decode(&report).expect("Linux takes it"); + assert_eq!(clicks, button); + let t = touches[0]; + assert_eq!((t.x, t.y), (i32::from(x), -i32::from(y)), "{i},{j}"); + assert_eq!((t.state, t.down), (state, down)); + assert_eq!((t.id, t.orientation), (1, 0)); + assert_eq!(t.pressure, if button == 1 { 120 } else { 5 }); + assert_eq!((t.major, t.minor, t.size), (20, 20, 10)); + } + } + } + } +} + +#[test] +fn corners_centre_and_aspect() { + let map = Mapping::mt2(ELAN); + // The corners land inside the MT2's range, the pad centred on its + // centre (128, 54 downward). + assert_eq!(map.to_mt2(0, 0), (-2891, 1753)); + assert_eq!(map.to_mt2(126_900, 82_000), (3147, -1861)); + assert_eq!(map.to_mt2(63_450, 41_000), (128, -54)); + // One resolution per axis: 47.575 units per mm across and 44.08 down, + // the MT2's own, so the pad's 126.9 by 82.0 mm keep their ratio in + // millimetres. + let (left, top) = map.to_mt2(0, 0); + let (right, bottom) = map.to_mt2(126_900, 82_000); + let width_um = i64::from(right - left) * 160_000 / 7612; + let height_um = i64::from(top - bottom) * 114_900 / 5065; + assert!((width_um - 126_900).abs() < 50, "{width_um}"); + assert!((height_um - 82_000).abs() < 50, "{height_um}"); + // A surface larger than the MT2's is clamped to its range. + let large = Mapping::mt2(Surface { + width_um: 300_000, + height_um: 200_000, + }); + assert_eq!(large.to_mt2(0, 0), (-3678, 2478)); + assert_eq!(large.to_mt2(300_000, 200_000), (3934, -2587)); +} + +#[test] +fn d9_is_surface_and_range() { + let map = Mapping::mt2(ELAN); + // Sent: the pad's surface, then VoodooInput's range bytes verbatim + // (-7356, -174, 7869, 9956), which Intel macOS takes. + assert_eq!(D9_RANGE, D9Range::VoodooInput); + assert_eq!( + map.d9().to_vec(), + hex("d9 92 31 00 00 08 20 00 00 44 e3 52 ff bd 1e e4 26") + ); + assert_eq!(map.d9(), map.d9_with(D9Range::VoodooInput)); + // The variant one constant away: the range the reports carry. + let mut emitted = hex("d9 92 31 00 00 08 20 00 00"); + for value in [-2891i16, -1861, 3147, 1753] { + emitted.extend(value.to_le_bytes()); + } + assert_eq!(map.d9_with(D9Range::Emitted).to_vec(), emitted); +} + +#[test] +fn palm_type_and_thumb() { + let map = Mapping::mt2(ELAN); + let kinds = |report: &[u8]| -> Vec { + let (_, touches) = linux_decode(report).unwrap(); + touches.iter().map(|t| t.kind).collect() + }; + // A palm alone, for its whole life: Palm, then Stop as Palm. + let mut e = Encoder::new(); + let palm = |tip| elan(3, 1000, 2400, tip, false); + assert_eq!( + kinds(&encoded(&mut e, &Frame::new(0, 0, &[palm(true)]), &map)), + [6] + ); + assert_eq!( + kinds(&encoded(&mut e, &Frame::new(8_000, 0, &[palm(true)]), &map)), + [6] + ); + assert_eq!( + kinds(&encoded( + &mut e, + &Frame::new(16_000, 0, &[palm(false)]), + &map + )), + [6] + ); + // The button with two fingers: the lower (larger y) is the thumb; the + // other keeps its order's type. + let mut e = Encoder::new(); + let two = [ + elan(1, 2000, 2000, true, true), + elan(2, 2200, 500, true, true), + ]; + assert_eq!( + kinds(&encoded(&mut e, &Frame::new(0, 1, &two), &map)), + [1, 3] + ); + // Without the button and with fewer than four contacts, no thumb. + assert_eq!( + kinds(&encoded(&mut e, &Frame::new(8_000, 0, &two), &map)), + [2, 3] + ); + // A palm lowest of all is never the thumb: the lowest finger is. + let mut e = Encoder::new(); + let with_palm = [ + elan(1, 2000, 1500, true, true), + elan(2, 2200, 500, true, true), + elan(3, 1000, 2500, true, false), + ]; + assert_eq!( + kinds(&encoded(&mut e, &Frame::new(0, 1, &with_palm), &map)), + [1, 3, 6] + ); + // Four fingers touching make the lowest a thumb without the button. + let mut e = Encoder::new(); + let four: Vec = (0..4) + .map(|n| { + elan( + n, + 500 + 700 * u64::from(n), + 1000 + 100 * u64::from(n), + true, + true, + ) + }) + .collect(); + assert_eq!( + kinds(&encoded(&mut e, &Frame::new(0, 0, &four), &map)), + [2, 3, 4, 1] + ); +} + +#[test] +fn fifteen_finger_cap() { + let map = Mapping::mt2(ELAN); + let mut e = Encoder::new(); + let fingers = |base: u8| -> Vec { + (0..10) + .map(|n| elan(base + n, 300 * u64::from(n) + 100, 1200, true, true)) + .collect() + }; + let first = encoded(&mut e, &Frame::new(0, 0, &fingers(0)), &map); + assert_eq!(linux_decode(&first).unwrap().1.len(), 10); + // Ten others replace them at once: ten Stops, and five of the new + // contacts in the slots left; Linux takes the 15. + let second = encoded(&mut e, &Frame::new(8_000, 0, &fingers(20)), &map); + assert_eq!(second.len(), HEADER + MAX_FINGERS * FINGER); + let (_, touches) = linux_decode(&second).unwrap(); + assert_eq!(touches.iter().filter(|t| t.state == 0xc0).count(), 10); + assert_eq!(touches.iter().filter(|t| t.state == 0x40).count(), 5); + // The other five start once the Stops freed their slots. + let third = encoded(&mut e, &Frame::new(16_000, 0, &fingers(20)), &map); + let (_, touches) = linux_decode(&third).unwrap(); + assert_eq!(touches.len(), 10); + assert_eq!(touches.iter().filter(|t| t.state == 0x40).count(), 5); + assert_eq!(touches.iter().filter(|t| t.state == 0x80).count(), 5); + let mut ids: Vec = touches.iter().map(|t| t.id).collect(); + ids.sort_unstable(); + ids.dedup(); + assert_eq!(ids.len(), 10, "every contact its own identifier"); +} + +#[test] +fn identifiers_rotate_and_reset_starts_over() { + let map = Mapping::mt2(ELAN); + let mut e = Encoder::new(); + let tap = |e: &mut Encoder, id: u8, time: u64| -> u8 { + let down = encoded( + e, + &Frame::new(time, 0, &[elan(id, 2000, 1000, true, true)]), + &map, + ); + encoded(e, &Frame::new(time + 8_000, 0, &[]), &map); + linux_decode(&down).unwrap().1[0].id + }; + assert_eq!(tap(&mut e, 0, 0), 1); + assert_eq!(tap(&mut e, 0, 20_000), 2, "a new touch, a new identifier"); + // A contact still down when the guest forgets everything starts again. + let down = Frame::new(40_000, 0, &[elan(5, 2000, 1000, true, true)]); + encoded(&mut e, &down, &map); + e.reset(); + let again = encoded( + &mut e, + &Frame::new(48_000, 0, &[elan(5, 2000, 1000, true, true)]), + &map, + ); + let t = linux_decode(&again).unwrap().1[0]; + assert_eq!((t.id, t.state), (1, 0x40)); +} + +#[test] +fn timestamps_wrap_at_21_bits() { + let map = Mapping::mt2(ELAN); + let mut e = Encoder::new(); + let report = encoded(&mut e, &Frame::new(((1 << 21) + 5) * 1000, 0, &[]), &map); + assert_eq!(&report[9..12], &[5 << 3 | 4, 0, 0]); + let report = encoded(&mut e, &Frame::new(((1 << 21) - 1) * 1000, 0, &[]), &map); + assert_eq!(&report[9..12], &[0xfc, 0xff, 0xff]); + assert_eq!(vec![report[0], report[8]], [REPORT_ID, 0x31]); +} diff --git a/crates/stela-soc/src/usb/trackpad/tests.rs b/crates/stela-soc/src/usb/trackpad/tests.rs new file mode 100644 index 0000000000..610c27a128 --- /dev/null +++ b/crates/stela-soc/src/usb/trackpad/tests.rs @@ -0,0 +1,55 @@ +use super::*; +use alloc::string::ToString; + +#[test] +fn the_serial_is_the_machine_s_and_no_ecid() { + let a = serial(0x0011_2233_4455_6677); + assert_eq!(a, serial(0x0011_2233_4455_6677), "stable"); + assert_ne!(a, serial(0x0011_2233_4455_6678)); + assert_eq!(a.len(), 12); + assert!(a.starts_with("STELA")); + assert!(a[5..].bytes().all(|b| b.is_ascii_hexdigit())); + assert!(!a.contains("2233"), "no digits of the ECID"); +} + +#[test] +fn identities_are_apple_s_ids() { + assert_eq!(VENDOR, 0x05ac); + assert_eq!(Identity::MagicTrackpad2.product(), 0x0265); + assert_eq!(Identity::Builtin.product(), 0x0281); +} + +#[test] +fn events_read_as_log_lines() { + for (event, line) in [ + (TrackpadEvent::Configured(1), "configured 1"), + (TrackpadEvent::Mode(1), "mode 1"), + (TrackpadEvent::Feature(0xd9), "feature 0xd9"), + ( + TrackpadEvent::Query { + id: 0xd3, + answered: true, + }, + "query 0xd3", + ), + ( + TrackpadEvent::Query { + id: 0x42, + answered: false, + }, + "query 0x42 refused", + ), + ( + TrackpadEvent::Unknown { + request_type: 0xa1, + request: 0x01, + value: 0x0342, + index: 1, + }, + "unknown request_type=0xa1 request=0x01 value=0x0342 index=1", + ), + (TrackpadEvent::Dropped(3), "dropped 3 frames"), + ] { + assert_eq!(event.to_string(), line); + } +}