ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
//! Input device monitoring — keyboards, mice, touchpads, game controllers, tablets.
//!
//! # Platform Support
//!
//! - **Linux**: Reads `/sys/class/input/`, `/proc/bus/input/devices`
//! - **Windows**: Uses WMI (`Win32_Keyboard`, `Win32_PointingDevice`)
//! - **macOS**: Uses `system_profiler SPUSBDataType` and IOKit inference
//!
//! # Examples
//!
//! ```no_run
//! use ironmonitor::input::InputMonitor;
//!
//! let monitor = InputMonitor::new().unwrap();
//! for device in monitor.devices() {
//!     println!("{}: {:?} ({})", device.name, device.device_type, device.interface);
//! }
//! ```

use serde::{Deserialize, Serialize};

use crate::error::IronError;

/// Type of input device
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum InputDeviceType {
    /// Standard keyboard
    Keyboard,
    /// Mouse
    Mouse,
    /// Touchpad / trackpad
    Touchpad,
    /// Trackball
    Trackball,
    /// Trackpoint / pointing stick
    Trackpoint,
    /// Game controller / gamepad / joystick
    GameController,
    /// Drawing tablet / digitizer
    Tablet,
    /// Touchscreen
    Touchscreen,
    /// Stylus / pen input
    Stylus,
    /// Remote control / media keys
    Remote,
    /// Biometric reader (fingerprint, etc.)
    Biometric,
    /// Other or unrecognized input
    Other,
}

/// Connection interface for the input device
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum InputInterface {
    USB,
    Bluetooth,
    PS2,
    I2C,
    SPI,
    Serial,
    Internal,
    Wireless,
    Virtual,
    Unknown,
}

/// Information about a single input device
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InputDevice {
    /// Device name
    pub name: String,
    /// Device type (keyboard, mouse, etc.), or `None` where the platform did not
    /// report one. macOS and the Bluetooth branch used to pick it from the
    /// product name, with a Mouse fallback for every name the match missed.
    pub device_type: Option<InputDeviceType>,
    /// Connection interface
    pub interface: InputInterface,
    /// Vendor name or ID
    pub vendor: String,
    /// Product name or ID
    pub product: String,
    /// Physical path (sysfs path on Linux, device instance on Windows)
    pub physical_path: String,
    /// Whether the device appears active / connected
    /// Whether the platform reports the device as connected and usable.
    ///
    /// `None` where it was not established. Linux reads it from the device's
    /// `Handlers` line and Windows from `Status`, both of which answer the
    /// question the entity asks. macOS set the literal `true` at every
    /// construction site -- including the Bluetooth branch, and the entity's own
    /// description names that exact case: "a Bluetooth keyboard out of range is
    /// still enumerated".
    pub is_active: Option<bool>,
    /// Device-specific capabilities (e.g., "buttons:5", "axes:2")
    pub capabilities: Vec<String>,
}

/// Monitor for input devices (keyboards, mice, game controllers, etc.)
pub struct InputMonitor {
    devices: Vec<InputDevice>,
}

/// Match a device instance id's enumerator prefix to a transport.
///
/// The enumerator is the segment before the first backslash: `USB`, `BTHENUM`,
/// `ACPI`, `HID`. **`HID` is deliberately absent from this table** — it names a
/// device class and says nothing about how the device is attached, which is the
/// whole reason [`interface_from_device_tree`] has to walk the parent chain.
#[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` is classic Bluetooth, `BTHLEDEVICE` is Low Energy.
        "BTHENUM" | "BTHLEDEVICE" | "BTH" => Some(InputInterface::Bluetooth),
        "ACPI" => Some(InputInterface::PS2),
        "HIDI2C" => Some(InputInterface::I2C),
        "SWD" | "ROOT" => Some(InputInterface::Virtual),
        _ => None,
    }
}

/// The transport a device instance sits on, following the parent chain.
///
/// A `HID\...` instance id names a device *class*, not a transport: the same
/// prefix covers a USB mouse, a Bluetooth keyboard and an I2C touchpad. The
/// reader used to look only at the device's own id and answer `Unknown` for
/// every HID node, which was the honest answer to the question it was asking.
///
/// It is not the only question available. Windows records
/// `DEVPKEY_Device_Parent`, and the HID node's parent carries the transport in
/// its own enumerator prefix -- on this machine, the HID mouse
/// `HID\VID_046D&PID_C548&MI_01\...` has the parent
/// `USB\VID_046D&PID_C548&MI_01\...`. Walking up until an enumerator is
/// recognised turns a refusal to guess into a reading.
///
/// Still `Unknown` when the walk finds nothing it recognises, which is the same
/// answer as before and for the same reason: naming a transport this crate has
/// not established would be the guess the old comment declined to make.
#[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;
    // SAFETY: `wide` is NUL-terminated and outlives the call.
    if unsafe {
        CM_Locate_DevNodeW(
            &mut devinst,
            PCWSTR(wide.as_ptr()),
            CM_LOCATE_DEVNODE_NORMAL,
        )
    } != CR_SUCCESS
    {
        return InputInterface::Unknown;
    }

    // Bounded: the device tree is a tree and terminates on its own, but a
    // corrupted one should not hang a monitoring process.
    let mut node = devinst;
    for _ in 0..8 {
        let mut parent = 0u32;
        // SAFETY: `parent` is a live local; the call writes one `u32`.
        if unsafe { CM_Get_Parent(&mut parent, node, 0) } != CR_SUCCESS {
            return InputInterface::Unknown;
        }

        let mut buf = [0u16; 512];
        // SAFETY: `buf` is the buffer the call fills, sized by its own length.
        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
}

/// The manufacturer WMI reports for an input device, if it named one.
///
/// Windows fills `Manufacturer` on many device nodes with the *driver package
/// provider* rather than the hardware vendor, and marks those by convention
/// with parentheses: "(Standard system devices)", "(Standard keyboards)",
/// "(Standard mouse types)". Those name who wrote the inbox driver, not who
/// built the device, and publishing one as a vendor would be the same class of
/// error as publishing "Unknown" -- a real-looking string standing in for an
/// absence. The resolver's own guard rejects the word "unknown"; it has no way
/// to know about this convention, so the reader applies it here.
///
/// Verified on this machine: `Win32_PointingDevice` reports "Microsoft" for one
/// device and "(Standard system devices)" for another, and `Win32_Keyboard`
/// reports an empty string for all three keyboards.
///
/// Where the column says nothing usable the *numeric* vendor id in the device's
/// instance path does, and the entity asks for "vendor name or numeric id,
/// whichever the platform gave" -- so the fallback below is the entity being
/// answered rather than a second-best guess. Before it, five of this machine's
/// six input devices published no vendor at all while `USB\VID_0557` sat in
/// their instance paths.
#[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();
    }
    // "Vendor name **or numeric id**, whichever the platform gave" -- and the
    // platform gave one, in the instance path: `USB\VID_0557&PID_220E&MI_00`.
    // The Linux reader has always published `0x046d` from
    // `/proc/bus/input/devices`; this branch is what makes Windows answer the
    // same entity the same way instead of reporting an empty reader.
    match crate::usb::parse_vid_pid(instance_id).0 {
        Some(vid) => format!("0x{vid:04x}"),
        None => String::new(),
    }
}

/// The numeric product id in an input device's instance path.
///
/// This was `String::new()` for every Windows input device -- hardcoded, with
/// the ontology reporting "reader returned an empty string" as though the
/// platform had been asked. It had not been: `HID\VID_046D&PID_C548&MI_01&COL01`
/// carries the product id, the crate already has a parser for that shape in
/// `usb`, and Linux publishes the same field from the same kind of id.
///
/// Empty for a device whose path carries no `PID_` -- a PS/2 keyboard on
/// `ACPI\PNP0303`, a virtual device on `ROOT\` -- which the resolver then
/// reports absent, honestly this time.
#[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 {
    /// Create a new InputMonitor and enumerate all input devices.
    pub fn new() -> Result<Self, IronError> {
        let mut monitor = Self {
            devices: Vec::new(),
        };
        monitor.refresh()?;
        Ok(monitor)
    }

    /// Refresh the list of input devices from the system.
    /// Re-enumerate keyboards, pointing devices and other input hardware.
    ///
    /// Returns `Err` when the enumeration failed, and `Ok` with an empty list
    /// only when it succeeded and found nothing -- which the resolver publishes
    /// as `board.input.<none>`. See [`crate::core::command`].
    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(())
    }

    /// Get all detected input devices.
    pub fn devices(&self) -> &[InputDevice] {
        &self.devices
    }

    /// Get devices filtered by type.
    pub fn devices_by_type(&self, device_type: InputDeviceType) -> Vec<&InputDevice> {
        self.devices
            .iter()
            .filter(|d| d.device_type == Some(device_type))
            .collect()
    }

    /// Get all keyboards.
    pub fn keyboards(&self) -> Vec<&InputDevice> {
        self.devices_by_type(InputDeviceType::Keyboard)
    }

    /// Get all mice and pointing devices.
    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()
    }

    /// Get all game controllers.
    pub fn game_controllers(&self) -> Vec<&InputDevice> {
        self.devices_by_type(InputDeviceType::GameController)
    }

    #[cfg(target_os = "linux")]
    fn refresh_linux(&mut self) -> Result<(), IronError> {
        // Parse /proc/bus/input/devices for comprehensive device info
        // A machine with no /proc/bus/input/devices has no input layer at
        // all, which is a real answer; an unreadable one is not.
        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,
                // `format!("0x{}", ...)` on an id the `I:` line did not carry
                // produced the string `"0x"` -- a non-empty value naming
                // nothing, which the resolver would publish as a reading. An
                // absent id stays absent.
                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=") {
                // Format: Bus=XXXX Vendor=XXXX Product=XXXX Version=XXXX
                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 last device
        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 {
            // An empty `P:` line names no path, so it says nothing about the
            // transport. This used to be `Virtual`.
            InputInterface::Unknown
        }
    }

    #[cfg(target_os = "windows")]
    fn refresh_windows(&mut self) -> Result<(), IronError> {
        // Keyboards via WMI
        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();
                // A bare `HID\` instance names the device class, not the
                // transport -- it may be Bluetooth or I2C rather than USB. An
                // earlier note said exactly that while the code reported USB
                // anyway; then the code stopped guessing and answered `Unknown`
                // for every HID node. Neither was necessary: the parent chain
                // records the transport. See `interface_from_device_tree`.
                let iface = interface_from_device_tree(&device_id);
                self.devices.push(InputDevice {
                    name,
                    device_type: Some(InputDeviceType::Keyboard),
                    interface: iface,
                    // Both queries now select `Manufacturer`, which they did
                    // not before -- the field was hardcoded empty and the
                    // ontology reported "reader returned an empty string" for
                    // it. On this machine `Win32_Keyboard.Manufacturer` really
                    // is blank on all three keyboards, so the numeric vendor id
                    // in the instance path answers instead; see
                    // `device_vendor`.
                    vendor: device_vendor(item, &device_id),
                    product: device_product(&device_id),
                    physical_path: device_id,
                    is_active: Some(item["Status"].as_str() == Some("OK")),
                    // No capability is read here. This used to be the literal
                    // "keys", which every keyboard was given whether or not the
                    // platform said so.
                    capabilities: Vec::new(),
                });
            }
        }

        // Pointing devices via WMI
        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();
                // The type comes from `PointingType`, which the query already
                // selects. It used to be a substring match on the display name,
                // so a product name containing "touchpad" decided the class, and
                // every name the match missed became a Mouse. A type the platform
                // does not name is `Other`, not a guess.
                let device_type = Some(pointing_device_type(&item["PointingType"]));
                let device_id = item["DeviceID"].as_str().unwrap_or("").to_string();
                // See the keyboard branch above.
                let iface = interface_from_device_tree(&device_id);
                // The capability is emitted only when the count was read. A missing
                // `NumberOfButtons` used to be `0`, which is a count of no buttons,
                // and a device the platform did not count was published as having
                // none.
                // "relative-axes" used to be a literal on every pointing device.
                // Only the button count is read.
                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> {
        // Use system_profiler for HID devices
        let text = crate::core::command::capture(
            "system_profiler",
            &["SPUSBDataType", "-detailLevel", "mini"],
        )?;
        // Parse USB tree for HID/input devices
        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() {
                // This is a device name
                if !current_name.is_empty() {
                    // Check if previous device was an input device
                    self.maybe_add_macos_device(&current_name, &current_vendor, &current_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(&current_name, &current_vendor, &current_product);
        }

        // Also check for Bluetooth input devices
        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) {
        // Whether this USB device is an input device at all is still decided by
        // its name, as it always was. Its type is not: system_profiler's mini
        // detail carries no HID usage, so the type is not read. It used to be
        // chosen by the same name match, which put every unmatched input device
        // in the Mouse class.
        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; // Skip non-input USB devices
        }
        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"),
        }
    }
}

/// The `buttons:N` capability from a `Win32_PointingDevice.NumberOfButtons`
/// value. Nothing is emitted unless the count was read and is positive. A
/// missing value used to be read as zero, which is a count the platform never
/// gave.
#[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()]
        );
        // A count of zero is a reading too, but it names no button capability.
        assert!(button_capabilities(&serde_json::json!(0)).is_empty());
        // Absent, null and non-numeric values were not read.
        assert!(button_capabilities(&serde_json::Value::Null).is_empty());
        assert!(button_capabilities(&serde_json::json!("3")).is_empty());
    }
}

/// The device type of a `Win32_PointingDevice` row from its `PointingType`.
///
/// The CIM value map is a uint16: 3 Mouse, 4 Track Ball, 5 Track Point,
/// 7 Touch Pad, 8 Touch Screen. The string spelling is accepted too, since the
/// property has been seen both ways. Any other value, or none, is `Other`.
#[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() {
        // A touchpad whose product name says nothing about it is still a touchpad.
        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() {
        // "Other" (1) and "Unknown" (2) in the value map, and a missing property.
        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};

    /// The reason the parent walk exists at all.
    #[test]
    fn hid_is_a_device_class_and_names_no_transport() {
        // A HID instance id is compatible with USB, Bluetooth and I2C alike,
        // so it must not resolve to any of them on its own. This is the real
        // id of this machine's mouse.
        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() {
        // The parent of that HID node, and the shapes of the other buses.
        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)
        );

        // Instance ids arrive in both cases.
        assert_eq!(
            classify_enumerator(r"usb\vid_046d"),
            Some(InputInterface::USB)
        );
    }

    #[test]
    fn an_unrecognised_enumerator_is_not_forced_into_a_transport() {
        // Absence, not a nearest match. Naming a transport this crate has not
        // established is the guess the reader exists to avoid.
        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;

    /// A PS/2 keyboard's instance path: no `VID_`, no `PID_`, so there is
    /// nothing to fall back to and the absence stands.
    const NO_IDS: &str = r"ACPI\PNP0303\4&1";
    /// This machine's KVM keyboard, whose manufacturer Windows leaves blank.
    const ATEN_KEYBOARD: &str = r"USB\VID_0557&PID_220E&MI_00\B&2F3F2B&0&0000";

    /// Windows' parenthesised driver-provider strings are not vendors.
    #[test]
    fn a_driver_package_provider_is_not_a_device_vendor() {
        // Real values from `Win32_PointingDevice` on the development host.
        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),
            ""
        );

        // An absent or blank column stays absent rather than becoming a name.
        assert_eq!(device_vendor(&json!({"Manufacturer": ""}), NO_IDS), "");
        assert_eq!(device_vendor(&json!({}), NO_IDS), "");

        // A real vendor that merely contains a bracket keeps it; only a
        // leading one marks the convention.
        assert_eq!(
            device_vendor(&json!({"Manufacturer": "Logitech (Suisse) SA"}), NO_IDS),
            "Logitech (Suisse) SA"
        );
    }

    /// The entity is "vendor name **or numeric id**, whichever the platform
    /// gave", and the instance path gives one where the column does not.
    #[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"
        );
        // A real name still outranks the number.
        assert_eq!(
            device_vendor(&json!({"Manufacturer": "Microsoft"}), ATEN_KEYBOARD),
            "Microsoft"
        );
    }

    /// `product` was hardcoded empty on Windows while the id sat in the path.
    #[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), "");
    }
}

// Event codes from the kernel's `input-event-codes.h`.
#[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;

/// Whether bit `bit` is set in a kernel capability bitmap such as `KEY=`.
///
/// The kernel prints each bitmap as hexadecimal machine words, most significant
/// word first, so the last word holds bits 0 to word-size-1. The word size is
/// the pointer width, which is the kernel's `long` on the targets this crate
/// builds for. A bitmap too short to reach `bit` does not have it.
#[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)
}

/// Device type from the kernel's capability bitmaps in `/proc/bus/input/devices`.
///
/// The device name is not consulted: a name containing "pen" or "media" says
/// nothing about what the device can do. A device the bitmaps do not identify
/// is `Other`.
#[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);
    // Absolute-position devices, told apart by the tool button they report.
    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;
    }
    // The joystick handler is `js` followed by its index, as in `js0`.
    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
}

/// Bluetooth input devices from `system_profiler SPBluetoothDataType`.
///
/// A `Vendor ID:` line belongs to the device whose block contains it: the
/// nearest header above it, indented less than the line itself. The vendor is
/// empty when no such line is present. It used to be the literal "Apple" for
/// every device, which named a vendor that was never read.
#[cfg(any(target_os = "macos", test))]
fn parse_macos_bluetooth_inputs(text: &str) -> Vec<InputDevice> {
    let mut found: Vec<InputDevice> = Vec::new();
    // (index into `found`, header indent) while that device's block is open.
    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();
            // The type is not read from system_profiler's entry. It used to be
            // chosen from the name, with Mouse for everything the match missed.
            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::*;

    /// Constructing the monitor either enumerates or says why it could not.
    ///
    /// This asserted `is_ok()`, which was true by construction until 6.0.0
    /// because `refresh` could not fail. Now that it can, the contract is
    /// weaker and more useful: **whatever happens, the caller can tell which
    /// happened.** A failure has to carry a reason, because a reason is the
    /// whole difference between "this machine has none" and "nobody looked".
    #[test]
    fn a_capability_bit_is_read_from_the_word_that_holds_it() {
        assert!(bitmap_has("2", 1));
        assert!(!bitmap_has("2", 0));
        // A bit beyond the end of the bitmap is not set.
        assert!(!bitmap_has("2", 200));
        // With two words, the less significant one holds bits 0 to word-size-1.
        let word = usize::BITS as usize;
        assert!(bitmap_has("1 0", word));
        assert!(!bitmap_has("1 0", word - 1));
    }

    // Captured shapes from `/proc/bus/input/devices` on a 64-bit kernel.
    #[cfg(target_pointer_width = "64")]
    #[test]
    fn a_linux_input_device_is_classified_by_capability_not_by_name() {
        // AT keyboard: EV_KEY, with KEY_A and KEY_SPACE in the last KEY word.
        let keyboard_keys = "402000000 3803078f800d001 feffffdfffefffff fffffffffffffffe";
        assert_eq!(
            classify_linux("sysrq kbd event0", "120013", keyboard_keys, "", ""),
            InputDeviceType::Keyboard
        );
        // Optical mouse: EV_REL with REL_X, REL_Y and BTN_LEFT. No name says so.
        assert_eq!(
            classify_linux("event4", "17", "10000 0 0 0 0", "903", ""),
            InputDeviceType::Mouse
        );
        // Touchpad: absolute X/Y and BTN_TOOL_FINGER.
        assert_eq!(
            classify_linux("event3", "b", "20 0 0 0 0 0", "", "3"),
            InputDeviceType::Touchpad
        );
        // Touchscreen: absolute X/Y and BTN_TOUCH, without a pen tool.
        assert_eq!(
            classify_linux("event5", "b", "400 0 0 0 0 0", "", "3"),
            InputDeviceType::Touchscreen
        );
        // Pen tablet: absolute X/Y and BTN_TOOL_PEN.
        assert_eq!(
            classify_linux("event6", "b", "1 0 0 0 0 0", "", "3"),
            InputDeviceType::Tablet
        );
        // A joystick is identified by the kernel's js handler.
        assert_eq!(
            classify_linux("event7 js0", "1b", "", "", ""),
            InputDeviceType::GameController
        );
        // Only EV_SYN: no capability identifies it, so it is not given a type.
        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"
        );
    }

    /// Shaped like `system_profiler SPBluetoothDataType` output: a device's
    /// attributes sit one level below its header, and a sibling header ends the
    /// block. Indentation is built here, not written as a literal run.
    #[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");
        // No Vendor ID under the trackpad, and the headphones' ID does not
        // belong to it: it stays empty, not "Apple".
        assert_eq!(devices[1].name, "Magic Trackpad");
        assert_eq!(devices[1].vendor, "");
        // Neither is a type the platform reported, so neither is claimed: the
        // name is not evidence of a kind.
        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();
    }
}