Skip to main content

device/
human_interface.rs

1//! Human interface emulation device contract (`/devices/human_interface/emulation`, kind `b'h'`).
2//!
3//! A Xila device can act as a USB or Bluetooth keyboard, media remote and mouse toward the
4//! computer it is connected to (shortcuts, screenshots, play/pause, volume). An application
5//! writes messages to the device node. The upper half
6//! (`drivers_peripherals::human_interface`) validates the message structure and forwards
7//! HID reports to the target controller (`peripherals::human_interface::HumanInterfaceController`),
8//! which every USB and Bluetooth Low Energy lower half implements. The shared HID report
9//! descriptor lives in `peripherals::human_interface`.
10//!
11//! # File contract
12//!
13//! The node is write-only for reports: `read` fails with `Unsupported`. The connection
14//! status is a control command, which WebAssembly guests reach through the `fd_control`
15//! import of the Wasm host.
16//!
17//! ## Write
18//!
19//! Each `write` contains one or more messages of exactly [`MESSAGE_SIZE`] (8) bytes. A write
20//! whose length is not a multiple of 8 fails with `InvalidArgument`. Every message must
21//! decode: an unknown kind in byte 0 or a non-zero reserved byte makes the message invalid.
22//! Reserved bytes are written as zero on encode.
23//!
24//! The upper half sends the messages of one write one by one and returns the number of
25//! accepted bytes: when the first message is invalid or its report cannot be sent, the
26//! write fails with an error; when a later message fails, the write returns the accepted
27//! byte count, a multiple of [`MESSAGE_SIZE`].
28//!
29//! Byte 0 of a message is the kind:
30//!
31//! | Kind | Name             | Byte 1                                             | Bytes 2 to 7                                                                |
32//! |------|------------------|----------------------------------------------------|-----------------------------------------------------------------------------|
33//! | `1`  | keyboard         | modifier bitmask, see [`Modifiers`]               | up to six key usages from the HID Keyboard/Keypad page (0x07), `0` = none   |
34//! | `2`  | consumer control | consumer usage (HID page 0x0C), little endian, `0` = release | must be `0`                                                          |
35//! | `3`  | mouse            | buttons bitmask, see [`MouseButtons`]              | x (i8), y (i8), wheel (i8), pan (i8) in bytes 2 to 5, bytes 6 and 7 must be `0` |
36//! | `4`  | system control   | usage from the HID Generic Desktop page: `0x81` power down, `0x82` sleep, `0x83` wake up, `0` = release | must be `0` |
37//!
38//! A keyboard message is the full pressed state: an all-zero keyboard message releases all
39//! keys.
40//!
41//! ## Control commands (kind `b'h'`)
42//!
43//! | Number | Command     | Direction | Input        | Output      | Effect                                                        |
44//! |--------|-------------|-----------|--------------|-------------|---------------------------------------------------------------|
45//! | `0x00` | `GET_STATUS` | Read      | `VersionAbi` | `StatusAbi` | Returns the connection state and the keyboard LED bitmask.   |
46//!
47//! Every struct starts with a `version` field equal to [`ABI_VERSION`] and carries zeroed
48//! `reserved` fields. A wrong version or a non-zero reserved field is `InvalidArgument`.
49
50use core::fmt;
51use core::ops::{BitAnd, BitOr};
52
53use file_system::{ControlCommand, define_command};
54
55/// Path of the emulation device node in the virtual file system.
56pub const EMULATION_PATH: &str = "/devices/human_interface/emulation";
57
58/// Size of one message in bytes.
59pub const MESSAGE_SIZE: usize = 8;
60
61/// Kind byte of a keyboard message. Also the report identifier of the keyboard report.
62pub const KIND_KEYBOARD: u8 = 1;
63/// Kind byte of a consumer control message. Also the report identifier of the consumer report.
64pub const KIND_CONSUMER: u8 = 2;
65/// Kind byte of a mouse message. Also the report identifier of the mouse report.
66pub const KIND_MOUSE: u8 = 3;
67/// Kind byte of a system control message. Also the report identifier of the system report.
68pub const KIND_SYSTEM: u8 = 4;
69
70/// Number of key usages in one keyboard message.
71pub const KEY_COUNT: usize = 6;
72
73/// Version of every control ABI struct in this module.
74pub const ABI_VERSION: u16 = 1;
75
76/// Keyboard indicator bit 0: num lock is on.
77pub const INDICATOR_NUM_LOCK: u8 = 1 << 0;
78/// Keyboard indicator bit 1: caps lock is on.
79pub const INDICATOR_CAPS_LOCK: u8 = 1 << 1;
80/// Keyboard indicator bit 2: scroll lock is on.
81pub const INDICATOR_SCROLL_LOCK: u8 = 1 << 2;
82
83/// Error of the message protocol.
84#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
85pub enum Error {
86    /// The input is not a valid message: an unknown kind, a length that is not a multiple of
87    /// [`MESSAGE_SIZE`], or a non-zero reserved byte.
88    InvalidArgument,
89}
90
91impl fmt::Display for Error {
92    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
93        match self {
94            Self::InvalidArgument => write!(formatter, "invalid human interface message"),
95        }
96    }
97}
98
99impl core::error::Error for Error {}
100
101/// Generates a hand-written bitmask type with the given named bits.
102macro_rules! bitmask {
103    (
104        $(#[$type_doc:meta])*
105        $name:ident, $bits:ty;
106        $( $(#[$doc:meta])* $constant:ident = $value:expr; )*
107    ) => {
108        $(#[$type_doc])*
109        #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
110        pub struct $name($bits);
111
112        impl $name {
113            /// No bit set.
114            pub const NONE: Self = Self(0);
115            $( $(#[$doc])* pub const $constant: Self = Self($value); )*
116
117            /// Every defined bit.
118            pub const ALL: Self = Self(0 $(| $value)*);
119
120            /// Empty bitmask.
121            pub const fn empty() -> Self {
122                Self::NONE
123            }
124
125            /// Bitmask from raw bits; unknown bits are retained.
126            pub const fn from_bits_retain(bits: $bits) -> Self {
127                Self(bits)
128            }
129
130            /// Raw bits of the bitmask.
131            pub const fn bits(self) -> $bits {
132                self.0
133            }
134
135            /// `true` when no bit is set.
136            pub const fn is_empty(self) -> bool {
137                self.0 == 0
138            }
139
140            /// `true` when every bit of `other` is set.
141            pub const fn contains(self, other: Self) -> bool {
142                (self.0 & other.0) == other.0
143            }
144
145            /// `true` when at least one bit is set in both.
146            pub const fn intersects(self, other: Self) -> bool {
147                (self.0 & other.0) != 0
148            }
149
150            /// Union of two bitmasks.
151            pub const fn union(self, other: Self) -> Self {
152                Self(self.0 | other.0)
153            }
154
155            /// Set the bits of `other`.
156            pub const fn insert(&mut self, other: Self) {
157                self.0 |= other.0;
158            }
159
160            /// Clear the bits of `other`.
161            pub const fn remove(&mut self, other: Self) {
162                self.0 &= !other.0;
163            }
164        }
165
166        impl BitOr for $name {
167            type Output = Self;
168            fn bitor(self, other: Self) -> Self {
169                self.union(other)
170            }
171        }
172
173        impl BitAnd for $name {
174            type Output = Self;
175            fn bitand(self, other: Self) -> Self {
176                Self(self.0 & other.0)
177            }
178        }
179    };
180}
181
182bitmask! {
183    /// Keyboard modifier bitmask, HID standard order: left control, left shift, left alt,
184    /// left GUI, then the right ones.
185    Modifiers, u8;
186    /// Left control.
187    LEFT_CONTROL = 1 << 0;
188    /// Left shift.
189    LEFT_SHIFT = 1 << 1;
190    /// Left alt.
191    LEFT_ALT = 1 << 2;
192    /// Left GUI (Windows, command, super).
193    LEFT_GUI = 1 << 3;
194    /// Right control.
195    RIGHT_CONTROL = 1 << 4;
196    /// Right shift.
197    RIGHT_SHIFT = 1 << 5;
198    /// Right alt (alt gr).
199    RIGHT_ALT = 1 << 6;
200    /// Right GUI.
201    RIGHT_GUI = 1 << 7;
202}
203
204bitmask! {
205    /// Mouse buttons bitmask: left, right, middle.
206    MouseButtons, u8;
207    /// Left button.
208    LEFT = 1 << 0;
209    /// Right button.
210    RIGHT = 1 << 1;
211    /// Middle button.
212    MIDDLE = 1 << 2;
213}
214
215/// One message of the emulation device.
216///
217/// A message is the full state of one function: a keyboard message lists every pressed key,
218/// so an all-zero keyboard message releases all keys.
219#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
220pub enum Message {
221    /// Keyboard state: modifier bitmask and up to six key usages from the HID
222    /// Keyboard/Keypad page (0x07), for example [`keyboard::A`]. `0` marks an empty slot.
223    Keyboard {
224        /// Modifier bitmask, see [`Modifiers`].
225        modifiers: Modifiers,
226        /// Up to six pressed key usages, `0` = none.
227        keys: [u8; KEY_COUNT],
228    },
229    /// Consumer control usage from the HID Consumer page (0x0C), for example
230    /// [`consumer::PLAY_PAUSE`]. `0` releases the control.
231    Consumer {
232        /// Consumer usage, little endian on the wire.
233        usage: u16,
234    },
235    /// Mouse movement and buttons.
236    Mouse {
237        /// Buttons bitmask, see [`MouseButtons`].
238        buttons: MouseButtons,
239        /// Horizontal movement in pixels, positive to the right.
240        x: i8,
241        /// Vertical movement in pixels, positive down.
242        y: i8,
243        /// Vertical wheel steps, positive up.
244        wheel: i8,
245        /// Horizontal pan steps, positive right.
246        pan: i8,
247    },
248    /// System control usage from the HID Generic Desktop page: [`system::POWER_DOWN`],
249    /// [`system::SLEEP`], [`system::WAKE_UP`]. `0` releases the control.
250    System {
251        /// System usage.
252        usage: u8,
253    },
254}
255
256impl Message {
257    /// Encode the message as its 8 wire bytes, kind in byte 0. Reserved bytes are zero.
258    pub fn encode(&self) -> [u8; MESSAGE_SIZE] {
259        let mut bytes = [0u8; MESSAGE_SIZE];
260        match self {
261            Self::Keyboard { modifiers, keys } => {
262                bytes[0] = KIND_KEYBOARD;
263                bytes[1] = modifiers.bits();
264                bytes[2..].copy_from_slice(keys);
265            }
266            Self::Consumer { usage } => {
267                bytes[0] = KIND_CONSUMER;
268                bytes[1..3].copy_from_slice(&usage.to_le_bytes());
269            }
270            Self::Mouse {
271                buttons,
272                x,
273                y,
274                wheel,
275                pan,
276            } => {
277                bytes[0] = KIND_MOUSE;
278                bytes[1] = buttons.bits();
279                bytes[2] = *x as u8;
280                bytes[3] = *y as u8;
281                bytes[4] = *wheel as u8;
282                bytes[5] = *pan as u8;
283            }
284            Self::System { usage } => {
285                bytes[0] = KIND_SYSTEM;
286                bytes[1] = *usage;
287            }
288        }
289        bytes
290    }
291
292    /// Decode one 8-byte message. An unknown kind in byte 0 or a non-zero reserved byte
293    /// fails with [`Error::InvalidArgument`].
294    pub fn decode(bytes: &[u8; MESSAGE_SIZE]) -> Result<Self, Error> {
295        /// Reserved bytes of a message must be zero.
296        fn check_reserved(reserved: &[u8]) -> Result<(), Error> {
297            if reserved.iter().any(|&byte| byte != 0) {
298                return Err(Error::InvalidArgument);
299            }
300            Ok(())
301        }
302        match bytes[0] {
303            KIND_KEYBOARD => Ok(Self::Keyboard {
304                modifiers: Modifiers::from_bits_retain(bytes[1]),
305                keys: bytes[2..]
306                    .try_into()
307                    .expect("slice of MESSAGE_SIZE - 2 bytes"),
308            }),
309            KIND_CONSUMER => {
310                check_reserved(&bytes[3..])?;
311                Ok(Self::Consumer {
312                    usage: u16::from_le_bytes([bytes[1], bytes[2]]),
313                })
314            }
315            KIND_MOUSE => {
316                check_reserved(&bytes[6..])?;
317                Ok(Self::Mouse {
318                    buttons: MouseButtons::from_bits_retain(bytes[1]),
319                    x: bytes[2] as i8,
320                    y: bytes[3] as i8,
321                    wheel: bytes[4] as i8,
322                    pan: bytes[5] as i8,
323                })
324            }
325            KIND_SYSTEM => {
326                check_reserved(&bytes[2..])?;
327                Ok(Self::System { usage: bytes[1] })
328            }
329            _ => Err(Error::InvalidArgument),
330        }
331    }
332}
333
334/// Iterator over the messages of one write.
335///
336/// [`Messages::new`] checks that the length of the write is a multiple of [`MESSAGE_SIZE`];
337/// every item decodes one message and fails with [`Error::InvalidArgument`] on an unknown kind
338/// or a non-zero reserved byte.
339#[derive(Clone, Debug)]
340pub struct Messages<'a> {
341    remaining: &'a [u8],
342}
343
344impl<'a> Messages<'a> {
345    /// Validate the write length and return its message iterator.
346    pub fn new(bytes: &'a [u8]) -> Result<Self, Error> {
347        if !bytes.len().is_multiple_of(MESSAGE_SIZE) {
348            return Err(Error::InvalidArgument);
349        }
350        Ok(Self { remaining: bytes })
351    }
352}
353
354impl Iterator for Messages<'_> {
355    type Item = Result<Message, Error>;
356
357    fn next(&mut self) -> Option<Self::Item> {
358        if self.remaining.is_empty() {
359            return None;
360        }
361        let (head, tail) = self.remaining.split_at(MESSAGE_SIZE);
362        self.remaining = tail;
363        Some(Message::decode(
364            head.try_into().expect("MESSAGE_SIZE bytes"),
365        ))
366    }
367
368    fn size_hint(&self) -> (usize, Option<usize>) {
369        let count = self.remaining.len() / MESSAGE_SIZE;
370        (count, Some(count))
371    }
372}
373
374impl ExactSizeIterator for Messages<'_> {}
375impl core::iter::FusedIterator for Messages<'_> {}
376
377/// Generates the Keyboard/Keypad page (0x07) usage constants with doc comments.
378macro_rules! keyboard_usages {
379    ( $( $name:ident = $value:expr, $doc:literal; )* ) => {
380        /// Keyboard/Keypad page (0x07) usages.
381        pub mod keyboard {
382            $( #[doc = $doc] pub const $name: u8 = $value; )*
383        }
384    };
385}
386
387keyboard_usages! {
388    A = 0x04, "Letter A key.";
389    B = 0x05, "Letter B key.";
390    C = 0x06, "Letter C key.";
391    D = 0x07, "Letter D key.";
392    E = 0x08, "Letter E key.";
393    F = 0x09, "Letter F key.";
394    G = 0x0A, "Letter G key.";
395    H = 0x0B, "Letter H key.";
396    I = 0x0C, "Letter I key.";
397    J = 0x0D, "Letter J key.";
398    K = 0x0E, "Letter K key.";
399    L = 0x0F, "Letter L key.";
400    M = 0x10, "Letter M key.";
401    N = 0x11, "Letter N key.";
402    O = 0x12, "Letter O key.";
403    P = 0x13, "Letter P key.";
404    Q = 0x14, "Letter Q key.";
405    R = 0x15, "Letter R key.";
406    S = 0x16, "Letter S key.";
407    T = 0x17, "Letter T key.";
408    U = 0x18, "Letter U key.";
409    V = 0x19, "Letter V key.";
410    W = 0x1A, "Letter W key.";
411    X = 0x1B, "Letter X key.";
412    Y = 0x1C, "Letter Y key.";
413    Z = 0x1D, "Letter Z key.";
414    NUMBER_1 = 0x1E, "Digit 1 key.";
415    NUMBER_2 = 0x1F, "Digit 2 key.";
416    NUMBER_3 = 0x20, "Digit 3 key.";
417    NUMBER_4 = 0x21, "Digit 4 key.";
418    NUMBER_5 = 0x22, "Digit 5 key.";
419    NUMBER_6 = 0x23, "Digit 6 key.";
420    NUMBER_7 = 0x24, "Digit 7 key.";
421    NUMBER_8 = 0x25, "Digit 8 key.";
422    NUMBER_9 = 0x26, "Digit 9 key.";
423    NUMBER_0 = 0x27, "Digit 0 key.";
424    ENTER = 0x28, "Enter (return) key.";
425    ESCAPE = 0x29, "Escape key.";
426    BACKSPACE = 0x2A, "Backspace key.";
427    TAB = 0x2B, "Tab key.";
428    SPACE = 0x2C, "Space bar.";
429    CAPS_LOCK = 0x39, "Caps lock key.";
430    F1 = 0x3A, "Function key F1.";
431    F2 = 0x3B, "Function key F2.";
432    F3 = 0x3C, "Function key F3.";
433    F4 = 0x3D, "Function key F4.";
434    F5 = 0x3E, "Function key F5.";
435    F6 = 0x3F, "Function key F6.";
436    F7 = 0x40, "Function key F7.";
437    F8 = 0x41, "Function key F8.";
438    F9 = 0x42, "Function key F9.";
439    F10 = 0x43, "Function key F10.";
440    F11 = 0x44, "Function key F11.";
441    F12 = 0x45, "Function key F12.";
442    PRINT_SCREEN = 0x46, "Print screen key.";
443    SCROLL_LOCK = 0x47, "Scroll lock key.";
444    PAUSE = 0x48, "Pause (break) key.";
445    INSERT = 0x49, "Insert key.";
446    HOME = 0x4A, "Home key.";
447    PAGE_UP = 0x4B, "Page up key.";
448    DELETE = 0x4C, "Delete (forward) key.";
449    END = 0x4D, "End key.";
450    PAGE_DOWN = 0x4E, "Page down key.";
451    ARROW_RIGHT = 0x4F, "Right arrow key.";
452    ARROW_LEFT = 0x50, "Left arrow key.";
453    ARROW_DOWN = 0x51, "Down arrow key.";
454    ARROW_UP = 0x52, "Up arrow key.";
455    F13 = 0x68, "Function key F13.";
456    F14 = 0x69, "Function key F14.";
457    F15 = 0x6A, "Function key F15.";
458    F16 = 0x6B, "Function key F16.";
459    F17 = 0x6C, "Function key F17.";
460    F18 = 0x6D, "Function key F18.";
461    F19 = 0x6E, "Function key F19.";
462    F20 = 0x6F, "Function key F20.";
463    F21 = 0x70, "Function key F21.";
464    F22 = 0x71, "Function key F22.";
465    F23 = 0x72, "Function key F23.";
466    F24 = 0x73, "Function key F24.";
467}
468
469/// Consumer page (0x0C) usages: media remote controls.
470pub mod consumer {
471    /// Play/pause.
472    pub const PLAY_PAUSE: u16 = 0x00CD;
473    /// Next track.
474    pub const NEXT_TRACK: u16 = 0x00B5;
475    /// Previous track.
476    pub const PREVIOUS_TRACK: u16 = 0x00B6;
477    /// Stop.
478    pub const STOP: u16 = 0x00B7;
479    /// Volume up.
480    pub const VOLUME_UP: u16 = 0x00E9;
481    /// Volume down.
482    pub const VOLUME_DOWN: u16 = 0x00EA;
483    /// Mute.
484    pub const MUTE: u16 = 0x00E2;
485}
486
487/// Generic Desktop page (0x01) system control usages.
488pub mod system {
489    /// System power down.
490    pub const POWER_DOWN: u8 = 0x81;
491    /// System sleep.
492    pub const SLEEP: u8 = 0x82;
493    /// System wake up.
494    pub const WAKE_UP: u8 = 0x83;
495}
496
497file_system::plain_data! {
498    #[repr(C)]
499    /// Carries only the ABI version and a reserved field. Input of [`GET_STATUS`].
500    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
501    pub struct VersionAbi {
502        pub version: u16,
503        pub reserved: u16,
504    }
505}
506
507file_system::plain_data! {
508    #[repr(C)]
509    /// Connection state and keyboard indicators of the computer. Output of [`GET_STATUS`].
510    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
511    pub struct StatusAbi {
512        pub version: u16,
513        /// `1` when a computer is connected and listening, else `0`.
514        pub connected: u8,
515        /// Keyboard indicator bitmask from the computer: [`INDICATOR_NUM_LOCK`],
516        /// [`INDICATOR_CAPS_LOCK`], [`INDICATOR_SCROLL_LOCK`].
517        pub indicators: u8,
518        pub reserved: [u8; 4],
519    }
520}
521
522define_command!(
523    GET_STATUS,
524    Read,
525    crate::kind::HUMAN_INTERFACE,
526    0x00,
527    VersionAbi,
528    StatusAbi
529);
530
531#[cfg(test)]
532mod tests {
533    use super::*;
534    use file_system::ControlDirectionFlags;
535
536    fn keyboard_message() -> Message {
537        Message::Keyboard {
538            modifiers: Modifiers::LEFT_CONTROL.union(Modifiers::LEFT_SHIFT),
539            keys: [keyboard::A, keyboard::ENTER, 0, 0, 0, 0],
540        }
541    }
542
543    #[test]
544    fn encodes_and_decodes_every_kind() {
545        let messages = [
546            keyboard_message(),
547            Message::Keyboard {
548                modifiers: Modifiers::empty(),
549                keys: [0; KEY_COUNT],
550            },
551            Message::Consumer {
552                usage: consumer::PLAY_PAUSE,
553            },
554            Message::Consumer { usage: 0 },
555            Message::Mouse {
556                buttons: MouseButtons::LEFT.union(MouseButtons::RIGHT),
557                x: -12,
558                y: 34,
559                wheel: -1,
560                pan: 2,
561            },
562            Message::Mouse {
563                buttons: MouseButtons::empty(),
564                x: 0,
565                y: 0,
566                wheel: 0,
567                pan: 0,
568            },
569            Message::System {
570                usage: system::POWER_DOWN,
571            },
572            Message::System { usage: 0 },
573        ];
574        for message in messages {
575            let encoded = message.encode();
576            assert_eq!(encoded.len(), MESSAGE_SIZE);
577            assert_eq!(Message::decode(&encoded), Ok(message));
578        }
579    }
580
581    #[test]
582    fn encodes_the_documented_wire_layout() {
583        assert_eq!(
584            keyboard_message().encode(),
585            [
586                KIND_KEYBOARD,
587                0b0000_0011,
588                keyboard::A,
589                keyboard::ENTER,
590                0,
591                0,
592                0,
593                0
594            ]
595        );
596        assert_eq!(
597            Message::Consumer {
598                usage: consumer::NEXT_TRACK
599            }
600            .encode(),
601            [KIND_CONSUMER, 0xB5, 0x00, 0, 0, 0, 0, 0]
602        );
603        assert_eq!(
604            Message::Mouse {
605                buttons: MouseButtons::MIDDLE,
606                x: -1,
607                y: 127,
608                wheel: -128,
609                pan: 5,
610            }
611            .encode(),
612            [KIND_MOUSE, 0b0000_0100, 0xFF, 0x7F, 0x80, 0x05, 0, 0]
613        );
614        assert_eq!(
615            Message::System {
616                usage: system::WAKE_UP
617            }
618            .encode(),
619            [KIND_SYSTEM, 0x83, 0, 0, 0, 0, 0, 0]
620        );
621    }
622
623    #[test]
624    fn decode_rejects_an_unknown_kind() {
625        for kind in [0u8, 5, 42, u8::MAX] {
626            let mut bytes = [0u8; MESSAGE_SIZE];
627            bytes[0] = kind;
628            assert_eq!(Message::decode(&bytes), Err(Error::InvalidArgument));
629        }
630    }
631
632    #[test]
633    fn decode_rejects_non_zero_reserved_bytes() {
634        let mut consumer = Message::Consumer { usage: 0x1234 }.encode();
635        consumer[3] = 0xAA;
636        assert_eq!(Message::decode(&consumer), Err(Error::InvalidArgument));
637
638        let mut mouse = Message::Mouse {
639            buttons: MouseButtons::empty(),
640            x: 0,
641            y: 0,
642            wheel: 0,
643            pan: 0,
644        }
645        .encode();
646        mouse[6] = 0x01;
647        assert_eq!(Message::decode(&mouse), Err(Error::InvalidArgument));
648
649        let mut system = Message::System { usage: 0x81 }.encode();
650        system[7] = 0xFF;
651        assert_eq!(Message::decode(&system), Err(Error::InvalidArgument));
652
653        // The keyboard message uses every byte, so nothing is reserved there.
654        let mut keyboard = keyboard_message().encode();
655        keyboard[7] = 0xFF;
656        assert!(Message::decode(&keyboard).is_ok());
657    }
658
659    #[test]
660    fn messages_iterator_checks_the_write_length() {
661        assert_eq!(Messages::new(&[]).unwrap().count(), 0);
662        let bytes = [0u8; 80];
663        for length in [1, 7, 9, 15, 17] {
664            assert_eq!(
665                Messages::new(&bytes[..length]).unwrap_err(),
666                Error::InvalidArgument
667            );
668        }
669        for length in [0, 8, 16, 80] {
670            assert!(Messages::new(&bytes[..length]).is_ok());
671        }
672    }
673
674    #[test]
675    fn messages_iterator_decodes_each_message_of_a_write() {
676        let mut write = [0u8; 3 * MESSAGE_SIZE];
677        write[..MESSAGE_SIZE].copy_from_slice(&keyboard_message().encode());
678        write[MESSAGE_SIZE..2 * MESSAGE_SIZE]
679            .copy_from_slice(&Message::Consumer { usage: 0 }.encode());
680        write[2 * MESSAGE_SIZE..].copy_from_slice(&[9u8; MESSAGE_SIZE]);
681        let mut messages = Messages::new(&write).unwrap();
682        assert_eq!(messages.len(), 3);
683        assert_eq!(messages.next(), Some(Ok(keyboard_message())));
684        assert_eq!(messages.next(), Some(Ok(Message::Consumer { usage: 0 })));
685        assert_eq!(messages.next(), Some(Err(Error::InvalidArgument)));
686        assert_eq!(messages.next(), None);
687    }
688
689    #[test]
690    fn modifiers_use_the_hid_standard_bit_order() {
691        assert_eq!(Modifiers::LEFT_CONTROL.bits(), 0x01);
692        assert_eq!(Modifiers::LEFT_SHIFT.bits(), 0x02);
693        assert_eq!(Modifiers::LEFT_ALT.bits(), 0x04);
694        assert_eq!(Modifiers::LEFT_GUI.bits(), 0x08);
695        assert_eq!(Modifiers::RIGHT_CONTROL.bits(), 0x10);
696        assert_eq!(Modifiers::RIGHT_SHIFT.bits(), 0x20);
697        assert_eq!(Modifiers::RIGHT_ALT.bits(), 0x40);
698        assert_eq!(Modifiers::RIGHT_GUI.bits(), 0x80);
699        assert_eq!(Modifiers::ALL.bits(), 0xFF);
700
701        let shortcut = Modifiers::LEFT_CONTROL | Modifiers::LEFT_SHIFT;
702        assert!(shortcut.contains(Modifiers::LEFT_CONTROL));
703        assert!(shortcut.contains(Modifiers::LEFT_SHIFT));
704        assert!(!shortcut.contains(Modifiers::LEFT_ALT));
705        assert!(shortcut.intersects(Modifiers::LEFT_SHIFT));
706        assert!(!shortcut.intersects(Modifiers::RIGHT_CONTROL));
707        let mut pressed = Modifiers::empty();
708        assert!(pressed.is_empty());
709        pressed.insert(Modifiers::RIGHT_GUI);
710        assert_eq!(pressed, Modifiers::RIGHT_GUI);
711        pressed.remove(Modifiers::RIGHT_GUI);
712        assert!(pressed.is_empty());
713        assert_eq!(
714            (Modifiers::LEFT_ALT & Modifiers::ALL).bits(),
715            Modifiers::LEFT_ALT.bits()
716        );
717    }
718
719    #[test]
720    fn mouse_buttons_use_left_right_middle_order() {
721        assert_eq!(MouseButtons::LEFT.bits(), 0x01);
722        assert_eq!(MouseButtons::RIGHT.bits(), 0x02);
723        assert_eq!(MouseButtons::MIDDLE.bits(), 0x04);
724        assert_eq!(MouseButtons::ALL.bits(), 0x07);
725        let both = MouseButtons::LEFT | MouseButtons::MIDDLE;
726        assert!(both.contains(MouseButtons::LEFT));
727        assert!(!both.contains(MouseButtons::RIGHT));
728        assert!(MouseButtons::empty().is_empty());
729    }
730
731    #[test]
732    fn usage_constants_match_the_hid_pages() {
733        assert_eq!(keyboard::A, 0x04);
734        assert_eq!(keyboard::Z, 0x1D);
735        assert_eq!(keyboard::NUMBER_1, 0x1E);
736        assert_eq!(keyboard::NUMBER_0, 0x27);
737        assert_eq!(keyboard::ENTER, 0x28);
738        assert_eq!(keyboard::ESCAPE, 0x29);
739        assert_eq!(keyboard::TAB, 0x2B);
740        assert_eq!(keyboard::SPACE, 0x2C);
741        assert_eq!(keyboard::F1, 0x3A);
742        assert_eq!(keyboard::F12, 0x45);
743        assert_eq!(keyboard::PRINT_SCREEN, 0x46);
744        assert_eq!(keyboard::INSERT, 0x49);
745        assert_eq!(keyboard::HOME, 0x4A);
746        assert_eq!(keyboard::PAGE_UP, 0x4B);
747        assert_eq!(keyboard::DELETE, 0x4C);
748        assert_eq!(keyboard::END, 0x4D);
749        assert_eq!(keyboard::PAGE_DOWN, 0x4E);
750        assert_eq!(keyboard::ARROW_RIGHT, 0x4F);
751        assert_eq!(keyboard::ARROW_LEFT, 0x50);
752        assert_eq!(keyboard::ARROW_DOWN, 0x51);
753        assert_eq!(keyboard::ARROW_UP, 0x52);
754        assert_eq!(keyboard::F13, 0x68);
755        assert_eq!(keyboard::F24, 0x73);
756
757        assert_eq!(consumer::PLAY_PAUSE, 0x00CD);
758        assert_eq!(consumer::NEXT_TRACK, 0x00B5);
759        assert_eq!(consumer::PREVIOUS_TRACK, 0x00B6);
760        assert_eq!(consumer::STOP, 0x00B7);
761        assert_eq!(consumer::VOLUME_UP, 0x00E9);
762        assert_eq!(consumer::VOLUME_DOWN, 0x00EA);
763        assert_eq!(consumer::MUTE, 0x00E2);
764
765        assert_eq!(system::POWER_DOWN, 0x81);
766        assert_eq!(system::SLEEP, 0x82);
767        assert_eq!(system::WAKE_UP, 0x83);
768
769        assert_eq!(INDICATOR_NUM_LOCK, 0x01);
770        assert_eq!(INDICATOR_CAPS_LOCK, 0x02);
771        assert_eq!(INDICATOR_SCROLL_LOCK, 0x04);
772    }
773
774    #[test]
775    fn status_command_uses_the_human_interface_kind_and_is_readable() {
776        let identifier = GET_STATUS::IDENTIFIER;
777        assert_eq!(identifier.get_kind(), crate::kind::HUMAN_INTERFACE);
778        assert_eq!(usize::from(identifier.get_number()), 0);
779        assert!(
780            identifier
781                .get_direction()
782                .contains(ControlDirectionFlags::Read)
783        );
784        assert!(
785            !identifier
786                .get_direction()
787                .contains(ControlDirectionFlags::Write)
788        );
789    }
790
791    #[test]
792    fn abi_structs_have_the_documented_layout() {
793        assert_eq!(size_of::<VersionAbi>(), 4);
794        assert_eq!(size_of::<StatusAbi>(), 8);
795        assert_eq!(
796            StatusAbi {
797                version: ABI_VERSION,
798                connected: 1,
799                indicators: INDICATOR_NUM_LOCK | INDICATOR_CAPS_LOCK,
800                reserved: [0; 4],
801            },
802            StatusAbi {
803                version: 1,
804                connected: 1,
805                indicators: 0b011,
806                reserved: [0; 4],
807            }
808        );
809    }
810}