mouse_codes/types/
button.rs1use std::fmt;
2use std::str::FromStr;
3
4use crate::error::MouseParseError;
5use crate::mapping::standard::parse_button_from_str;
6use crate::types::{CodeMapper, Platform};
7
8#[cfg(feature = "phf")]
9use phf::PhfHash;
10#[cfg(feature = "phf")]
11use phf_shared::PhfBorrow;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16pub enum Button {
17 Left,
19 Right,
21 Middle,
23 X1,
25 X2,
27 Extra3,
29 Extra4,
31 Extra5,
33 Extra6,
35 Extra7,
37 Extra8,
39 #[cfg(feature = "extended")]
40 Extra9,
42 #[cfg(feature = "extended")]
43 Extra10,
45}
46
47impl Button {
48 pub fn as_str(&self) -> &'static str {
50 match self {
51 Button::Left => "Left",
52 Button::Right => "Right",
53 Button::Middle => "Middle",
54 Button::X1 => "X1",
55 Button::X2 => "X2",
56 Button::Extra3 => "Extra3",
57 Button::Extra4 => "Extra4",
58 Button::Extra5 => "Extra5",
59 Button::Extra6 => "Extra6",
60 Button::Extra7 => "Extra7",
61 Button::Extra8 => "Extra8",
62 #[cfg(feature = "extended")]
63 Button::Extra9 => "Extra9",
64 #[cfg(feature = "extended")]
65 Button::Extra10 => "Extra10",
66 }
67 }
68
69 pub fn to_code(&self, platform: Platform) -> usize {
71 <Self as CodeMapper>::to_code(self, platform)
72 }
73
74 pub fn from_code(code: usize, platform: Platform) -> Option<Self> {
76 <Self as CodeMapper>::from_code(code, platform)
77 }
78
79 pub fn to_current_platform_code(&self) -> usize {
81 self.to_code(Platform::current())
82 }
83
84 pub fn from_current_platform_code(code: usize) -> Option<Self> {
86 Self::from_code(code, Platform::current())
87 }
88
89 pub fn matches_code(&self, code: usize, platform: Platform) -> bool {
91 Self::from_code(code, platform) == Some(*self)
92 }
93
94 pub fn matches_current_platform_code(&self, code: usize) -> bool {
96 self.matches_code(code, Platform::current())
97 }
98}
99
100impl FromStr for Button {
101 type Err = MouseParseError;
102
103 fn from_str(s: &str) -> Result<Self, Self::Err> {
104 parse_button_from_str(s)
105 }
106}
107
108#[cfg(feature = "phf")]
109impl PhfHash for Button {
110 fn phf_hash<H: std::hash::Hasher>(&self, state: &mut H) {
111 self.as_str().phf_hash(state);
112 }
113}
114
115#[cfg(feature = "phf")]
116impl PhfBorrow<Button> for Button {
117 fn borrow(&self) -> &Button {
118 self
119 }
120}
121
122#[cfg(feature = "phf")]
124impl PhfBorrow<Button> for &Button {
125 fn borrow(&self) -> &Button {
126 self
127 }
128}
129
130impl fmt::Display for Button {
131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132 write!(f, "{}", self.as_str())
133 }
134}