use serde::{Deserialize, Serialize};
use crate::error::IronError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum InputDeviceType {
Keyboard,
Mouse,
Touchpad,
Trackball,
Trackpoint,
GameController,
Tablet,
Touchscreen,
Stylus,
Remote,
Biometric,
Other,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum InputInterface {
USB,
Bluetooth,
PS2,
I2C,
SPI,
Serial,
Internal,
Wireless,
Virtual,
Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InputDevice {
pub name: String,
pub device_type: Option<InputDeviceType>,
pub interface: InputInterface,
pub vendor: String,
pub product: String,
pub physical_path: String,
pub is_active: Option<bool>,
pub capabilities: Vec<String>,
}
pub struct InputMonitor {
devices: Vec<InputDevice>,
}
#[cfg(target_os = "windows")]
fn classify_enumerator(id: &str) -> Option<InputInterface> {
let upper = id.to_uppercase();
match upper.split('\\').next().unwrap_or("") {
"USB" | "USBSTOR" => Some(InputInterface::USB),
"BTHENUM" | "BTHLEDEVICE" | "BTH" => Some(InputInterface::Bluetooth),
"ACPI" => Some(InputInterface::PS2),
"HIDI2C" => Some(InputInterface::I2C),
"SWD" | "ROOT" => Some(InputInterface::Virtual),
_ => None,
}
}
#[cfg(target_os = "windows")]
fn interface_from_device_tree(instance_id: &str) -> InputInterface {
use std::os::windows::ffi::OsStrExt;
use windows::core::PCWSTR;
use windows::Win32::Devices::DeviceAndDriverInstallation::{
CM_Get_Device_IDW, CM_Get_Parent, CM_Locate_DevNodeW, CM_LOCATE_DEVNODE_NORMAL, CR_SUCCESS,
};
if let Some(direct) = classify_enumerator(instance_id) {
return direct;
}
let wide: Vec<u16> = std::ffi::OsStr::new(instance_id)
.encode_wide()
.chain(std::iter::once(0))
.collect();
let mut devinst = 0u32;
if unsafe {
CM_Locate_DevNodeW(
&mut devinst,
PCWSTR(wide.as_ptr()),
CM_LOCATE_DEVNODE_NORMAL,
)
} != CR_SUCCESS
{
return InputInterface::Unknown;
}
let mut node = devinst;
for _ in 0..8 {
let mut parent = 0u32;
if unsafe { CM_Get_Parent(&mut parent, node, 0) } != CR_SUCCESS {
return InputInterface::Unknown;
}
let mut buf = [0u16; 512];
if unsafe { CM_Get_Device_IDW(parent, &mut buf, 0) } != CR_SUCCESS {
return InputInterface::Unknown;
}
let len = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
let id = String::from_utf16_lossy(&buf[..len]);
if let Some(found) = classify_enumerator(&id) {
return found;
}
node = parent;
}
InputInterface::Unknown
}
#[cfg(target_os = "windows")]
fn device_vendor(item: &serde_json::Value, instance_id: &str) -> String {
let raw = item["Manufacturer"].as_str().unwrap_or("").trim();
if !raw.is_empty() && !raw.starts_with('(') {
return raw.to_string();
}
match crate::usb::parse_vid_pid(instance_id).0 {
Some(vid) => format!("0x{vid:04x}"),
None => String::new(),
}
}
#[cfg(target_os = "windows")]
fn device_product(instance_id: &str) -> String {
match crate::usb::parse_vid_pid(instance_id).1 {
Some(pid) => format!("0x{pid:04x}"),
None => String::new(),
}
}
impl InputMonitor {
pub fn new() -> Result<Self, IronError> {
let mut monitor = Self {
devices: Vec::new(),
};
monitor.refresh()?;
Ok(monitor)
}
pub fn refresh(&mut self) -> Result<(), IronError> {
self.devices.clear();
#[cfg(target_os = "linux")]
self.refresh_linux()?;
#[cfg(target_os = "windows")]
self.refresh_windows()?;
#[cfg(target_os = "macos")]
self.refresh_macos()?;
Ok(())
}
pub fn devices(&self) -> &[InputDevice] {
&self.devices
}
pub fn devices_by_type(&self, device_type: InputDeviceType) -> Vec<&InputDevice> {
self.devices
.iter()
.filter(|d| d.device_type == Some(device_type))
.collect()
}
pub fn keyboards(&self) -> Vec<&InputDevice> {
self.devices_by_type(InputDeviceType::Keyboard)
}
pub fn pointing_devices(&self) -> Vec<&InputDevice> {
self.devices
.iter()
.filter(|d| {
matches!(
d.device_type,
Some(
InputDeviceType::Mouse
| InputDeviceType::Touchpad
| InputDeviceType::Trackball
| InputDeviceType::Trackpoint
)
)
})
.collect()
}
pub fn game_controllers(&self) -> Vec<&InputDevice> {
self.devices_by_type(InputDeviceType::GameController)
}
#[cfg(target_os = "linux")]
fn refresh_linux(&mut self) -> Result<(), IronError> {
let content = match std::fs::read_to_string("/proc/bus/input/devices") {
Ok(c) => c,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(e) => {
return Err(IronError::System(format!(
"cannot read /proc/bus/input/devices: {e}"
)))
}
};
let mut name = String::new();
let mut phys = String::new();
let mut sysfs = String::new();
let mut handlers = String::new();
let mut bitmap_ev = String::new();
let mut bitmap_key = String::new();
let mut bitmap_rel = String::new();
let mut bitmap_abs = String::new();
let mut vendor_id = String::new();
let mut product_id = String::new();
let flush = |devices: &mut Vec<InputDevice>,
name: &str,
phys: &str,
sysfs: &str,
handlers: &str,
bitmap_ev: &str,
bitmap_key: &str,
bitmap_rel: &str,
bitmap_abs: &str,
vendor_id: &str,
product_id: &str| {
if name.is_empty() {
return;
}
let device_type = Some(classify_linux(
handlers, bitmap_ev, bitmap_key, bitmap_rel, bitmap_abs,
));
let interface = Self::infer_interface_linux(phys, sysfs);
let mut caps = Vec::new();
if !bitmap_key.is_empty() && bitmap_key != "0" {
caps.push("keys".into());
}
if !bitmap_rel.is_empty() && bitmap_rel != "0" {
caps.push("relative-axes".into());
}
if !bitmap_abs.is_empty() && bitmap_abs != "0" {
caps.push("absolute-axes".into());
}
if handlers.contains("js") {
caps.push("joystick".into());
}
devices.push(InputDevice {
name: name.to_string(),
device_type,
interface,
vendor: if vendor_id.is_empty() {
String::new()
} else {
format!("0x{vendor_id}")
},
product: if product_id.is_empty() {
String::new()
} else {
format!("0x{product_id}")
},
physical_path: sysfs.to_string(),
is_active: Some(handlers.contains("event")),
capabilities: caps,
});
};
for line in content.lines() {
if line.is_empty() {
flush(
&mut self.devices,
&name,
&phys,
&sysfs,
&handlers,
&bitmap_ev,
&bitmap_key,
&bitmap_rel,
&bitmap_abs,
&vendor_id,
&product_id,
);
name.clear();
phys.clear();
sysfs.clear();
handlers.clear();
bitmap_ev.clear();
bitmap_key.clear();
bitmap_rel.clear();
bitmap_abs.clear();
vendor_id.clear();
product_id.clear();
} else if let Some(rest) = line.strip_prefix("N: Name=\"") {
name = rest.trim_end_matches('"').to_string();
} else if let Some(rest) = line.strip_prefix("P: Phys=") {
phys = rest.to_string();
} else if let Some(rest) = line.strip_prefix("S: Sysfs=") {
sysfs = rest.to_string();
} else if let Some(rest) = line.strip_prefix("H: Handlers=") {
handlers = rest.to_string();
} else if let Some(rest) = line.strip_prefix("I: Bus=") {
for part in rest.split_whitespace() {
if let Some(v) = part.strip_prefix("Vendor=") {
vendor_id = v.to_string();
} else if let Some(p) = part.strip_prefix("Product=") {
product_id = p.to_string();
}
}
} else if let Some(rest) = line.strip_prefix("B: EV=") {
bitmap_ev = rest.to_string();
} else if let Some(rest) = line.strip_prefix("B: KEY=") {
bitmap_key = rest.to_string();
} else if let Some(rest) = line.strip_prefix("B: REL=") {
bitmap_rel = rest.to_string();
} else if let Some(rest) = line.strip_prefix("B: ABS=") {
bitmap_abs = rest.to_string();
}
}
flush(
&mut self.devices,
&name,
&phys,
&sysfs,
&handlers,
&bitmap_ev,
&bitmap_key,
&bitmap_rel,
&bitmap_abs,
&vendor_id,
&product_id,
);
Ok(())
}
#[cfg(target_os = "linux")]
fn infer_interface_linux(phys: &str, _sysfs: &str) -> InputInterface {
let p = phys.to_lowercase();
if p.contains("usb") {
InputInterface::USB
} else if p.contains("bluetooth") || p.contains("bt") {
InputInterface::Bluetooth
} else if p.contains("i8042") || p.contains("ps/2") || p.contains("isa") {
InputInterface::PS2
} else if p.contains("i2c") {
InputInterface::I2C
} else if p.contains("spi") {
InputInterface::SPI
} else if p.contains("serial") || p.contains("tty") {
InputInterface::Serial
} else if p.contains("virtual") || p.contains("input") {
InputInterface::Virtual
} else {
InputInterface::Unknown
}
}
#[cfg(target_os = "windows")]
fn refresh_windows(&mut self) -> Result<(), IronError> {
let keyboards = crate::core::command::capture_json(
"powershell",
&["-NoProfile", "-Command", "Get-CimInstance Win32_Keyboard | Select-Object Name, Manufacturer, Description, DeviceID, Status, Layout | ConvertTo-Json -Compress"],
)?;
if let Some(val) = keyboards {
let items = crate::core::command::json_items(&val);
for item in &items {
let name = item["Name"]
.as_str()
.unwrap_or("Unknown Keyboard")
.to_string();
let device_id = item["DeviceID"].as_str().unwrap_or("").to_string();
let iface = interface_from_device_tree(&device_id);
self.devices.push(InputDevice {
name,
device_type: Some(InputDeviceType::Keyboard),
interface: iface,
vendor: device_vendor(item, &device_id),
product: device_product(&device_id),
physical_path: device_id,
is_active: Some(item["Status"].as_str() == Some("OK")),
capabilities: Vec::new(),
});
}
}
let pointers = crate::core::command::capture_json(
"powershell",
&["-NoProfile", "-Command", "Get-CimInstance Win32_PointingDevice | Select-Object Name, Manufacturer, Description, DeviceID, Status, PointingType, NumberOfButtons | ConvertTo-Json -Compress"],
)?;
if let Some(val) = pointers {
let items = crate::core::command::json_items(&val);
for item in &items {
let name = item["Name"]
.as_str()
.unwrap_or("Unknown Pointing Device")
.to_string();
let device_type = Some(pointing_device_type(&item["PointingType"]));
let device_id = item["DeviceID"].as_str().unwrap_or("").to_string();
let iface = interface_from_device_tree(&device_id);
let caps = button_capabilities(&item["NumberOfButtons"]);
self.devices.push(InputDevice {
name,
device_type,
interface: iface,
vendor: device_vendor(item, &device_id),
product: device_product(&device_id),
physical_path: device_id,
is_active: Some(item["Status"].as_str() == Some("OK")),
capabilities: caps,
});
}
}
Ok(())
}
#[cfg(target_os = "macos")]
fn refresh_macos(&mut self) -> Result<(), IronError> {
let text = crate::core::command::capture(
"system_profiler",
&["SPUSBDataType", "-detailLevel", "mini"],
)?;
let mut current_name = String::new();
let mut current_vendor = String::new();
let mut current_product = String::new();
for line in text.lines() {
let trimmed = line.trim();
if trimmed.ends_with(':') && !trimmed.starts_with("USB") && !trimmed.is_empty() {
if !current_name.is_empty() {
self.maybe_add_macos_device(¤t_name, ¤t_vendor, ¤t_product);
}
current_name = trimmed.trim_end_matches(':').to_string();
current_vendor.clear();
current_product.clear();
} else if let Some(v) = trimmed.strip_prefix("Vendor ID:") {
current_vendor = v.trim().to_string();
} else if let Some(p) = trimmed.strip_prefix("Product ID:") {
current_product = p.trim().to_string();
}
}
if !current_name.is_empty() {
self.maybe_add_macos_device(¤t_name, ¤t_vendor, ¤t_product);
}
let text = crate::core::command::capture(
"system_profiler",
&["SPBluetoothDataType", "-detailLevel", "mini"],
)?;
self.devices.extend(parse_macos_bluetooth_inputs(&text));
Ok(())
}
#[cfg(target_os = "macos")]
fn maybe_add_macos_device(&mut self, name: &str, vendor: &str, product: &str) {
let lower = name.to_lowercase();
let is_input = [
"keyboard",
"mouse",
"trackpad",
"touchpad",
"gamepad",
"controller",
"joystick",
"tablet",
"wacom",
"intuos",
"touchscreen",
]
.iter()
.any(|k| lower.contains(k));
if !is_input {
return; }
self.devices.push(InputDevice {
name: name.to_string(),
device_type: None,
interface: InputInterface::USB,
vendor: vendor.to_string(),
product: product.to_string(),
physical_path: String::new(),
is_active: None,
capabilities: Vec::new(),
});
}
}
impl Default for InputMonitor {
fn default() -> Self {
Self::new().unwrap_or(Self {
devices: Vec::new(),
})
}
}
impl std::fmt::Display for InputDeviceType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Keyboard => write!(f, "Keyboard"),
Self::Mouse => write!(f, "Mouse"),
Self::Touchpad => write!(f, "Touchpad"),
Self::Trackball => write!(f, "Trackball"),
Self::Trackpoint => write!(f, "Trackpoint"),
Self::GameController => write!(f, "Game Controller"),
Self::Tablet => write!(f, "Tablet"),
Self::Touchscreen => write!(f, "Touchscreen"),
Self::Stylus => write!(f, "Stylus"),
Self::Remote => write!(f, "Remote"),
Self::Biometric => write!(f, "Biometric"),
Self::Other => write!(f, "Other"),
}
}
}
impl std::fmt::Display for InputInterface {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::USB => write!(f, "USB"),
Self::Bluetooth => write!(f, "Bluetooth"),
Self::PS2 => write!(f, "PS/2"),
Self::I2C => write!(f, "I2C"),
Self::SPI => write!(f, "SPI"),
Self::Serial => write!(f, "Serial"),
Self::Internal => write!(f, "Internal"),
Self::Wireless => write!(f, "Wireless"),
Self::Virtual => write!(f, "Virtual"),
Self::Unknown => write!(f, "Unknown"),
}
}
}
#[cfg(any(target_os = "windows", test))]
fn button_capabilities(value: &serde_json::Value) -> Vec<String> {
match value.as_u64() {
Some(buttons) if buttons > 0 => vec![format!("buttons:{buttons}")],
_ => Vec::new(),
}
}
#[cfg(test)]
mod button_tests {
use super::button_capabilities;
#[test]
fn a_button_count_is_emitted_only_when_read() {
assert_eq!(
button_capabilities(&serde_json::json!(5)),
vec!["buttons:5".to_string()]
);
assert!(button_capabilities(&serde_json::json!(0)).is_empty());
assert!(button_capabilities(&serde_json::Value::Null).is_empty());
assert!(button_capabilities(&serde_json::json!("3")).is_empty());
}
}
#[cfg(target_os = "windows")]
fn pointing_device_type(value: &serde_json::Value) -> InputDeviceType {
if let Some(code) = value.as_u64() {
return match code {
3 => InputDeviceType::Mouse,
4 => InputDeviceType::Trackball,
5 => InputDeviceType::Trackpoint,
7 => InputDeviceType::Touchpad,
8 => InputDeviceType::Touchscreen,
_ => InputDeviceType::Other,
};
}
match value.as_str() {
Some("Mouse") => InputDeviceType::Mouse,
Some("Track Ball") => InputDeviceType::Trackball,
Some("Track Point") => InputDeviceType::Trackpoint,
Some("Touch Pad") => InputDeviceType::Touchpad,
Some("Touch Screen") => InputDeviceType::Touchscreen,
_ => InputDeviceType::Other,
}
}
#[cfg(all(test, target_os = "windows"))]
mod pointing_tests {
use super::{pointing_device_type, InputDeviceType};
#[test]
fn pointing_type_decides_the_class_not_the_name() {
assert_eq!(
pointing_device_type(&serde_json::json!(7)),
InputDeviceType::Touchpad
);
assert_eq!(
pointing_device_type(&serde_json::json!("Touch Pad")),
InputDeviceType::Touchpad
);
assert_eq!(
pointing_device_type(&serde_json::json!(3)),
InputDeviceType::Mouse
);
}
#[test]
fn an_unnamed_pointing_type_is_other_not_a_mouse() {
assert_eq!(
pointing_device_type(&serde_json::json!(1)),
InputDeviceType::Other
);
assert_eq!(
pointing_device_type(&serde_json::json!(2)),
InputDeviceType::Other
);
assert_eq!(
pointing_device_type(&serde_json::Value::Null),
InputDeviceType::Other
);
}
}
#[cfg(all(test, target_os = "windows"))]
mod enumerator_tests {
use super::{classify_enumerator, InputInterface};
#[test]
fn hid_is_a_device_class_and_names_no_transport() {
assert_eq!(
classify_enumerator(r"HID\VID_046D&PID_C548&MI_01&COL01\A&27230CC3&0&0000"),
None
);
}
#[test]
fn an_enumerator_prefix_names_its_transport() {
assert_eq!(
classify_enumerator(r"USB\VID_046D&PID_C548&MI_01\9&24c94812&0&0001"),
Some(InputInterface::USB)
);
assert_eq!(
classify_enumerator(r"BTHENUM\Dev_0000\7&2&0"),
Some(InputInterface::Bluetooth)
);
assert_eq!(
classify_enumerator(r"ACPI\PNP0303\4&1"),
Some(InputInterface::PS2)
);
assert_eq!(
classify_enumerator(r"ROOT\SYSTEM\0000"),
Some(InputInterface::Virtual)
);
assert_eq!(
classify_enumerator(r"usb\vid_046d"),
Some(InputInterface::USB)
);
}
#[test]
fn an_unrecognised_enumerator_is_not_forced_into_a_transport() {
assert_eq!(classify_enumerator(r"PCI\VEN_1022&DEV_43F7"), None);
assert_eq!(classify_enumerator(""), None);
assert_eq!(classify_enumerator(r"SOMETHINGNEW\X"), None);
}
}
#[cfg(all(test, target_os = "windows"))]
mod windows_vendor_tests {
use super::{device_product, device_vendor};
use serde_json::json;
const NO_IDS: &str = r"ACPI\PNP0303\4&1";
const ATEN_KEYBOARD: &str = r"USB\VID_0557&PID_220E&MI_00\B&2F3F2B&0&0000";
#[test]
fn a_driver_package_provider_is_not_a_device_vendor() {
assert_eq!(
device_vendor(&json!({"Manufacturer": "Microsoft"}), NO_IDS),
"Microsoft"
);
assert_eq!(
device_vendor(
&json!({"Manufacturer": "(Standard system devices)"}),
NO_IDS
),
""
);
assert_eq!(
device_vendor(&json!({"Manufacturer": "(Standard keyboards)"}), NO_IDS),
""
);
assert_eq!(device_vendor(&json!({"Manufacturer": ""}), NO_IDS), "");
assert_eq!(device_vendor(&json!({}), NO_IDS), "");
assert_eq!(
device_vendor(&json!({"Manufacturer": "Logitech (Suisse) SA"}), NO_IDS),
"Logitech (Suisse) SA"
);
}
#[test]
fn a_blank_or_driver_provided_manufacturer_falls_back_to_the_numeric_id() {
assert_eq!(
device_vendor(&json!({"Manufacturer": ""}), ATEN_KEYBOARD),
"0x0557"
);
assert_eq!(
device_vendor(
&json!({"Manufacturer": "(Standard system devices)"}),
ATEN_KEYBOARD
),
"0x0557"
);
assert_eq!(
device_vendor(&json!({"Manufacturer": "Microsoft"}), ATEN_KEYBOARD),
"Microsoft"
);
}
#[test]
fn the_product_id_comes_from_the_instance_path() {
assert_eq!(
device_product(r"HID\VID_046D&PID_C548&MI_01&COL01\A&27230CC3&0&0000"),
"0xc548"
);
assert_eq!(device_product(ATEN_KEYBOARD), "0x220e");
assert_eq!(device_product(NO_IDS), "");
}
}
#[cfg(any(target_os = "linux", test))]
const EV_KEY: usize = 0x01;
#[cfg(any(target_os = "linux", test))]
const EV_REL: usize = 0x02;
#[cfg(any(target_os = "linux", test))]
const EV_ABS: usize = 0x03;
#[cfg(any(target_os = "linux", test))]
const REL_X: usize = 0x00;
#[cfg(any(target_os = "linux", test))]
const REL_Y: usize = 0x01;
#[cfg(any(target_os = "linux", test))]
const ABS_X: usize = 0x00;
#[cfg(any(target_os = "linux", test))]
const ABS_Y: usize = 0x01;
#[cfg(any(target_os = "linux", test))]
const KEY_A: usize = 30;
#[cfg(any(target_os = "linux", test))]
const KEY_SPACE: usize = 57;
#[cfg(any(target_os = "linux", test))]
const BTN_LEFT: usize = 0x110;
#[cfg(any(target_os = "linux", test))]
const BTN_GAMEPAD: usize = 0x130;
#[cfg(any(target_os = "linux", test))]
const BTN_TOOL_PEN: usize = 0x140;
#[cfg(any(target_os = "linux", test))]
const BTN_TOOL_FINGER: usize = 0x145;
#[cfg(any(target_os = "linux", test))]
const BTN_TOUCH: usize = 0x14a;
#[cfg(any(target_os = "linux", test))]
fn bitmap_has(bitmap: &str, bit: usize) -> bool {
let word_bits = usize::BITS as usize;
let words: Vec<&str> = bitmap.split_whitespace().collect();
let Some(index) = words.len().checked_sub(bit / word_bits + 1) else {
return false;
};
u64::from_str_radix(words[index], 16)
.map(|word| (word >> (bit % word_bits)) & 1 == 1)
.unwrap_or(false)
}
#[cfg(any(target_os = "linux", test))]
fn classify_linux(handlers: &str, ev: &str, key: &str, rel: &str, abs: &str) -> InputDeviceType {
let has_abs_xy = bitmap_has(ev, EV_ABS) && bitmap_has(abs, ABS_X) && bitmap_has(abs, ABS_Y);
if has_abs_xy {
if bitmap_has(key, BTN_TOOL_FINGER) {
return InputDeviceType::Touchpad;
}
if bitmap_has(key, BTN_TOOL_PEN) {
return InputDeviceType::Tablet;
}
if bitmap_has(key, BTN_TOUCH) {
return InputDeviceType::Touchscreen;
}
}
if bitmap_has(ev, EV_KEY) && bitmap_has(key, KEY_A) && bitmap_has(key, KEY_SPACE) {
return InputDeviceType::Keyboard;
}
let joystick = handlers.split_whitespace().any(|h| {
h.strip_prefix("js")
.is_some_and(|index| !index.is_empty() && index.chars().all(|c| c.is_ascii_digit()))
});
if joystick || bitmap_has(key, BTN_GAMEPAD) {
return InputDeviceType::GameController;
}
if bitmap_has(ev, EV_REL)
&& bitmap_has(rel, REL_X)
&& bitmap_has(rel, REL_Y)
&& bitmap_has(key, BTN_LEFT)
{
return InputDeviceType::Mouse;
}
InputDeviceType::Other
}
#[cfg(any(target_os = "macos", test))]
fn parse_macos_bluetooth_inputs(text: &str) -> Vec<InputDevice> {
let mut found: Vec<InputDevice> = Vec::new();
let mut owner: Option<(usize, usize)> = None;
for line in text.lines() {
let trimmed = line.trim();
let indent = line.len() - line.trim_start().len();
if let Some((_, header_indent)) = owner {
if !trimmed.is_empty() && indent <= header_indent {
owner = None;
}
}
if let Some(v) = trimmed.strip_prefix("Vendor ID:") {
let v = v.trim();
if let (Some((idx, _)), false) = (owner, v.is_empty()) {
found[idx].vendor = v.to_string();
}
continue;
}
let lower = trimmed.to_lowercase();
if (lower.contains("keyboard")
|| lower.contains("mouse")
|| lower.contains("trackpad")
|| lower.contains("magic"))
&& trimmed.ends_with(':')
{
let name = trimmed.trim_end_matches(':').to_string();
found.push(InputDevice {
name,
device_type: None,
interface: InputInterface::Bluetooth,
vendor: String::new(),
product: String::new(),
physical_path: String::new(),
is_active: None,
capabilities: Vec::new(),
});
owner = Some((found.len() - 1, indent));
}
}
found
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_capability_bit_is_read_from_the_word_that_holds_it() {
assert!(bitmap_has("2", 1));
assert!(!bitmap_has("2", 0));
assert!(!bitmap_has("2", 200));
let word = usize::BITS as usize;
assert!(bitmap_has("1 0", word));
assert!(!bitmap_has("1 0", word - 1));
}
#[cfg(target_pointer_width = "64")]
#[test]
fn a_linux_input_device_is_classified_by_capability_not_by_name() {
let keyboard_keys = "402000000 3803078f800d001 feffffdfffefffff fffffffffffffffe";
assert_eq!(
classify_linux("sysrq kbd event0", "120013", keyboard_keys, "", ""),
InputDeviceType::Keyboard
);
assert_eq!(
classify_linux("event4", "17", "10000 0 0 0 0", "903", ""),
InputDeviceType::Mouse
);
assert_eq!(
classify_linux("event3", "b", "20 0 0 0 0 0", "", "3"),
InputDeviceType::Touchpad
);
assert_eq!(
classify_linux("event5", "b", "400 0 0 0 0 0", "", "3"),
InputDeviceType::Touchscreen
);
assert_eq!(
classify_linux("event6", "b", "1 0 0 0 0 0", "", "3"),
InputDeviceType::Tablet
);
assert_eq!(
classify_linux("event7 js0", "1b", "", "", ""),
InputDeviceType::GameController
);
assert_eq!(
classify_linux("event8", "1", "", "", ""),
InputDeviceType::Other
);
}
#[cfg(target_os = "linux")]
#[test]
fn an_empty_physical_path_names_no_transport() {
assert_eq!(
InputMonitor::infer_interface_linux("", ""),
InputInterface::Unknown
);
assert_eq!(
InputMonitor::infer_interface_linux("usb-0000:00:14.0-1/input0", ""),
InputInterface::USB
);
}
#[test]
fn test_input_monitor_creation() {
match InputMonitor::new() {
Ok(_monitor) => {}
Err(e) => {
let why = e.to_string();
assert!(
why.len() > 10,
"enumeration failed without saying why: {why:?}"
);
}
}
}
#[test]
fn test_input_monitor_default() {
let monitor = InputMonitor::default();
let _ = monitor.devices();
}
#[test]
fn test_input_device_type_display() {
assert_eq!(InputDeviceType::Keyboard.to_string(), "Keyboard");
assert_eq!(
InputDeviceType::GameController.to_string(),
"Game Controller"
);
}
#[test]
fn test_macos_bluetooth_vendor_is_read_per_device_not_assumed() {
let i = |n: usize| " ".repeat(n);
let text = [
"Bluetooth:".to_string(),
format!("{}Connected:", i(6)),
format!("{}Magic Keyboard:", i(10)),
format!("{}Address: AA:BB:CC:DD:EE:FF", i(14)),
format!("{}Vendor ID: 0x004C", i(14)),
format!("{}Product ID: 0x0320", i(14)),
format!("{}Magic Trackpad:", i(10)),
format!("{}Address: 11:22:33:44:55:66", i(14)),
format!("{}Headphones:", i(10)),
format!("{}Vendor ID: 0x0075", i(14)),
]
.join("\n");
let devices = parse_macos_bluetooth_inputs(&text);
assert_eq!(devices.len(), 2);
assert_eq!(devices[0].name, "Magic Keyboard");
assert_eq!(devices[0].vendor, "0x004C");
assert_eq!(devices[1].name, "Magic Trackpad");
assert_eq!(devices[1].vendor, "");
assert_eq!(devices[0].device_type, None);
assert_eq!(devices[1].device_type, None);
}
#[test]
fn test_input_device_serialization() {
let device = InputDevice {
name: "Test Keyboard".into(),
device_type: Some(InputDeviceType::Keyboard),
interface: InputInterface::USB,
vendor: "TestVendor".into(),
product: "TestProduct".into(),
physical_path: "/sys/test".into(),
is_active: Some(true),
capabilities: vec!["keys".into()],
};
let json = serde_json::to_string(&device).unwrap();
assert!(json.contains("Test Keyboard"));
let _: InputDevice = serde_json::from_str(&json).unwrap();
}
#[test]
fn test_filter_by_type() {
let monitor = InputMonitor::default();
let _keyboards = monitor.keyboards();
let _pointing = monitor.pointing_devices();
let _controllers = monitor.game_controllers();
}
}