//! Input and gamepad packets (`docs/PROTOCOL.md` section 4). //! //! An `INPUT_DATA` message is `0x0206 (LE) ‖ length (LE) ‖ size (BE) ‖ input type (LE) ‖ data`; see the field //! tables and the test vectors in PROTOCOL.md. [`encode_input`] produces the whole message, ready for the control //! frame; [`parse_input`] is its inverse (for round-trip tests, fuzzing and the Lumen host). pub mod gamepad; pub use gamepad::{ButtonFlags, ControllerCapabilities, ControllerKind, GamepadState}; /// Maximum size of one `INPUT_DATA` message, in bytes. pub const MAX_INPUT_MESSAGE_BYTES: usize = 1024; /// Bytes before the input data (message header 4 + size 4 + input type 4). pub const INPUT_HEADER_LEN: usize = 12; /// Input type codes (little-endian on the wire). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[repr(u32)] pub enum InputType { /// Key pressed. KeyDown = 0x0000_0003, /// Key released. KeyUp = 0x0000_0004, /// Absolute mouse position. MouseMoveAbs = 0x0000_0005, /// Relative mouse move. MouseMoveRel = 0x0000_0007, /// Mouse button pressed. MouseButtonDown = 0x0000_0008, /// Mouse button released. MouseButtonUp = 0x0000_0009, /// Vertical scroll. MouseScroll = 0x0000_000A, /// Gamepad state. ControllerMulti = 0x0000_000C, /// Haptics (layout UNKNOWN U21). Haptics = 0x0000_000D, /// UTF-8 text (layout UNKNOWN U21). Utf8Text = 0x0000_0017, /// Horizontal scroll. MouseHScroll = 0x5500_0001, /// Touch (layout UNKNOWN U21). Touch = 0x5500_0002, /// Pen (layout UNKNOWN U21). Pen = 0x5500_0003, /// A controller was plugged in. ControllerArrival = 0x5500_0004, /// Controller touchpad (layout UNKNOWN U21). ControllerTouch = 0x5500_0005, /// Controller motion sensors (layout UNKNOWN U21). ControllerMotion = 0x5500_0006, /// Controller battery (layout UNKNOWN U21). ControllerBattery = 0x5500_0007, } impl InputType { const ALL: [Self; 17] = [ Self::KeyDown, Self::KeyUp, Self::MouseMoveAbs, Self::MouseMoveRel, Self::MouseButtonDown, Self::MouseButtonUp, Self::MouseScroll, Self::ControllerMulti, Self::Haptics, Self::Utf8Text, Self::MouseHScroll, Self::Touch, Self::Pen, Self::ControllerArrival, Self::ControllerTouch, Self::ControllerMotion, Self::ControllerBattery, ]; } impl TryFrom for InputType { type Error = crate::Error; /// # Errors /// [`crate::Error::UnexpectedValue`] for an unknown code. fn try_from(code: u32) -> crate::Result { Self::ALL .into_iter() .find(|t| *t as u32 == code) .ok_or(crate::Error::UnexpectedValue { what: "input type", value: code.into() }) } } /// Mouse buttons. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[repr(u8)] pub enum MouseButton { /// Left. Left = 1, /// Middle. Middle = 2, /// Right. Right = 3, /// Side (back). Side = 4, /// Extra (forward). Extra = 5, } /// One input event with a known layout. #[derive(Clone, Debug, PartialEq, Eq)] pub enum InputEvent { /// Relative mouse move. MouseMoveRel { /// Horizontal delta. dx: i16, /// Vertical delta. dy: i16, }, /// Absolute mouse position within the client's viewport (the LG Magic Remote pointer). MouseMoveAbs { /// X in the viewport. x: i16, /// Y in the viewport. y: i16, /// Viewport width as the client reports it. width: u16, /// Viewport height as the client reports it. height: u16, }, /// Mouse button. MouseButton { /// Pressed (true) or released. pressed: bool, /// Which button. button: MouseButton, }, /// Keyboard key. Key { /// Pressed (true) or released. pressed: bool, /// `flags` byte (bit meanings UNKNOWN U20). flags: u8, /// Key code, Windows virtual-key style in the low byte (high byte UNKNOWN U20). key_code: u16, /// `modifiers` byte (bit meanings UNKNOWN U20). modifiers: u8, }, /// Vertical scroll (positive = up), in wheel units (120 = one notch). Scroll { /// Amount. amount: i16, }, /// Horizontal scroll. HScroll { /// Amount. amount: i16, }, /// Full gamepad state. Gamepad(GamepadState), /// A controller appeared. ControllerArrival { /// Controller number. controller: u8, /// What it is. kind: ControllerKind, /// What it can do. capabilities: ControllerCapabilities, /// Which buttons it has. supported_buttons: ButtonFlags, }, } /// `0x0206 LE ‖ length LE ‖ size BE ‖ input type LE ‖ data`. fn frame(input_type: InputType, data: &[u8]) -> crate::Result> { let size = 4 + data.len(); crate::util::cap("input message", MAX_INPUT_MESSAGE_BYTES, 8 + size)?; let mut m = Vec::with_capacity(8 + size); m.extend_from_slice(&0x0206u16.to_le_bytes()); m.extend_from_slice(&u16::try_from(4 + size).unwrap_or(u16::MAX).to_le_bytes()); m.extend_from_slice(&u32::try_from(size).unwrap_or(u32::MAX).to_be_bytes()); m.extend_from_slice(&(input_type as u32).to_le_bytes()); m.extend_from_slice(data); Ok(m) } fn check_controller(controller: u8) -> crate::Result<()> { if controller > gamepad::MAX_CONTROLLER_NUMBER { return Err(crate::Error::UnexpectedValue { what: "controller number", value: controller.into() }); } Ok(()) } /// Serializes an event into a whole `INPUT_DATA` message. /// /// # Errors /// [`crate::Error::UnexpectedValue`] for a controller number above 15. pub fn encode_input(event: &InputEvent) -> crate::Result> { match *event { InputEvent::MouseMoveRel { dx, dy } => { frame(InputType::MouseMoveRel, &[dx.to_be_bytes(), dy.to_be_bytes()].concat()) } InputEvent::MouseMoveAbs { x, y, width, height } => frame( InputType::MouseMoveAbs, &[x.to_be_bytes(), y.to_be_bytes(), [0, 0], width.to_be_bytes(), height.to_be_bytes()].concat(), ), InputEvent::MouseButton { pressed, button } => { frame(if pressed { InputType::MouseButtonDown } else { InputType::MouseButtonUp }, &[button as u8]) } InputEvent::Key { pressed, flags, key_code, modifiers } => { let [lo, hi] = key_code.to_le_bytes(); frame(if pressed { InputType::KeyDown } else { InputType::KeyUp }, &[flags, lo, hi, modifiers, 0, 0]) } InputEvent::Scroll { amount } => { let [a, b] = amount.to_be_bytes(); frame(InputType::MouseScroll, &[a, b, a, b, 0, 0]) } InputEvent::HScroll { amount } => frame(InputType::MouseHScroll, &amount.to_be_bytes()), InputEvent::Gamepad(g) => { check_controller(g.controller)?; let mut d = Vec::with_capacity(gamepad::CONTROLLER_MULTI_DATA_LEN); d.extend_from_slice(&0x001Au16.to_le_bytes()); d.extend_from_slice(&u16::from(g.controller).to_le_bytes()); d.extend_from_slice(&g.active_mask.to_le_bytes()); d.extend_from_slice(&0x0014u16.to_le_bytes()); d.extend_from_slice(&((g.buttons.0 & 0xFFFF) as u16).to_le_bytes()); d.push(g.left_trigger); d.push(g.right_trigger); for v in [g.left_stick_x, g.left_stick_y, g.right_stick_x, g.right_stick_y] { d.extend_from_slice(&v.to_le_bytes()); } d.extend_from_slice(&0x009Cu16.to_le_bytes()); d.extend_from_slice(&((g.buttons.0 >> 16) as u16).to_le_bytes()); d.extend_from_slice(&0x0055u16.to_le_bytes()); frame(InputType::ControllerMulti, &d) } InputEvent::ControllerArrival { controller, kind, capabilities, supported_buttons } => { check_controller(controller)?; let mut d = vec![controller, kind as u8, capabilities.0]; d.extend_from_slice(&supported_buttons.0.to_le_bytes()); frame(InputType::ControllerArrival, &d) } } } /// Parses a whole `INPUT_DATA` message (inverse of [`encode_input`]). Bytes the layout fixes at zero or at a /// copy (scroll `amount2`, key padding) are not checked; the `CONTROLLER_MULTI` constants are. /// /// # Errors /// [`crate::Error::TooLarge`] over [`MAX_INPUT_MESSAGE_BYTES`], [`crate::Error::Truncated`] under /// [`INPUT_HEADER_LEN`], [`crate::Error::Malformed`] when the type, length or size field does not match, the data /// length is wrong for the type, or a constant differs; [`crate::Error::UnexpectedValue`] for an unknown type, a /// button, controller number or controller kind out of range; [`crate::Error::Unsupported`] for a type whose /// layout is UNKNOWN. pub fn parse_input(message: &[u8]) -> crate::Result { use crate::util::{byte, i16_from, malformed, u16_le, u32_be, u32_le}; const W: &str = "input message"; crate::util::cap(W, MAX_INPUT_MESSAGE_BYTES, message.len())?; crate::util::need(W, INPUT_HEADER_LEN, message.len())?; if u16_le(W, message, 0)? != 0x0206 { return Err(malformed("input message type")); } if usize::from(u16_le(W, message, 2)?) != message.len() - 4 { return Err(malformed("input message length")); } if usize::try_from(u32_be(W, message, 4)?).ok() != Some(message.len() - 8) { return Err(malformed("input message size")); } let input_type = InputType::try_from(u32_le(W, message, 8)?)?; let d = message.get(INPUT_HEADER_LEN..).unwrap_or(&[]); let want = |len: usize| if d.len() == len { Ok(()) } else { Err(malformed("input data length")) }; let be = |at: usize| crate::util::u16_be(W, d, at); let le = |at: usize| u16_le(W, d, at); Ok(match input_type { InputType::MouseMoveRel => { want(4)?; InputEvent::MouseMoveRel { dx: i16_from(be(0)?), dy: i16_from(be(2)?) } } InputType::MouseMoveAbs => { want(10)?; InputEvent::MouseMoveAbs { x: i16_from(be(0)?), y: i16_from(be(2)?), width: be(6)?, height: be(8)? } } InputType::MouseButtonDown | InputType::MouseButtonUp => { want(1)?; let button = match byte(W, d, 0)? { 1 => MouseButton::Left, 2 => MouseButton::Middle, 3 => MouseButton::Right, 4 => MouseButton::Side, 5 => MouseButton::Extra, other => return Err(crate::Error::UnexpectedValue { what: "mouse button", value: other.into() }), }; InputEvent::MouseButton { pressed: input_type == InputType::MouseButtonDown, button } } InputType::KeyDown | InputType::KeyUp => { want(6)?; InputEvent::Key { pressed: input_type == InputType::KeyDown, flags: byte(W, d, 0)?, key_code: le(1)?, modifiers: byte(W, d, 3)?, } } InputType::MouseScroll => { want(6)?; InputEvent::Scroll { amount: i16_from(be(0)?) } } InputType::MouseHScroll => { want(2)?; InputEvent::HScroll { amount: i16_from(be(0)?) } } InputType::ControllerMulti => { want(gamepad::CONTROLLER_MULTI_DATA_LEN)?; if le(0)? != 0x001A || le(6)? != 0x0014 || le(20)? != 0x009C || le(24)? != 0x0055 { return Err(malformed("controller state constant")); } let controller = le(2)?; let controller = u8::try_from(controller) .ok() .filter(|c| *c <= gamepad::MAX_CONTROLLER_NUMBER) .ok_or(crate::Error::UnexpectedValue { what: "controller number", value: controller.into() })?; InputEvent::Gamepad(GamepadState { controller, active_mask: le(4)?, buttons: ButtonFlags(u32::from(le(8)?) | (u32::from(le(22)?) << 16)), left_trigger: byte(W, d, 10)?, right_trigger: byte(W, d, 11)?, left_stick_x: i16_from(le(12)?), left_stick_y: i16_from(le(14)?), right_stick_x: i16_from(le(16)?), right_stick_y: i16_from(le(18)?), }) } InputType::ControllerArrival => { want(7)?; let controller = byte(W, d, 0)?; check_controller(controller)?; let kind = match byte(W, d, 1)? { 0 => ControllerKind::Unknown, 1 => ControllerKind::Xbox, 2 => ControllerKind::PlayStation, 3 => ControllerKind::Nintendo, other => return Err(crate::Error::UnexpectedValue { what: "controller kind", value: other.into() }), }; InputEvent::ControllerArrival { controller, kind, capabilities: ControllerCapabilities(byte(W, d, 2)?), supported_buttons: ButtonFlags(u32_le(W, d, 3)?), } } InputType::Haptics | InputType::Utf8Text | InputType::Touch | InputType::Pen | InputType::ControllerTouch | InputType::ControllerMotion | InputType::ControllerBattery => { return Err(crate::Error::Unsupported { what: "an input type whose layout is UNKNOWN (U21)" }); } }) }