rich_sdl2_rust/event/joystick/
hat.rs

1//! Hats for a physical joystick.
2
3use bitflags::bitflags;
4use std::os::raw::c_int;
5
6use crate::bind;
7
8use super::{InputIndex, Joystick};
9
10bitflags! {
11    /// A direction of pov hat, representing with a bit flag.
12    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13    pub struct PovHat : u8 {
14        /// It is not tilted.
15        const CENTERED = 0;
16        /// It is on the up.
17        const UP = 1 << 0;
18        /// It is on the right.
19        const RIGHT = 1 << 1;
20        /// It is on the down.
21        const DOWN = 1 << 2;
22        /// It is on the left.
23        const LEFT = 1 << 3;
24        /// It is on the up and right.
25        const RIGHT_UP = Self::RIGHT.bits() | Self::UP.bits();
26        /// It is on the down and right.
27        const RIGHT_DOWN = Self::RIGHT.bits() | Self::DOWN.bits();
28        /// It is on the up and left.
29        const LEFT_UP = Self::LEFT.bits() | Self::UP.bits();
30        /// It is on the down and left.
31        const LEFT_DOWN = Self::LEFT.bits() | Self::DOWN.bits();
32    }
33}
34
35/// A hat on a physical joystick.
36#[derive(Debug)]
37pub struct Hat<'joystick> {
38    index: c_int,
39    joystick: &'joystick Joystick,
40}
41
42impl<'joystick> Hat<'joystick> {
43    pub(super) fn new(index: InputIndex, joystick: &'joystick Joystick) -> Self {
44        Self {
45            index: index.0,
46            joystick,
47        }
48    }
49
50    /// Returns the pov hat state of the joystick.
51    #[must_use]
52    pub fn state(&self) -> PovHat {
53        let raw = unsafe { bind::SDL_JoystickGetHat(self.joystick.ptr.as_ptr(), self.index) };
54        PovHat::from_bits(raw).expect("hat state must be valid")
55    }
56}
57
58/// A set of `Hat` for a physical joystick.
59#[derive(Debug)]
60pub struct Hats<'joystick>(pub Vec<Hat<'joystick>>);
61
62impl<'joystick> Hats<'joystick> {
63    pub(super) fn new(joystick: &'joystick Joystick) -> Self {
64        let num_hats = unsafe { bind::SDL_JoystickNumHats(joystick.ptr.as_ptr()) };
65        let hats = (0..num_hats).map(|index| Hat { index, joystick }).collect();
66        Self(hats)
67    }
68}