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
// MIT/Apache2 License

//! A library for converting keycodes to key symbols.

#![allow(non_upper_case_globals)]
#![forbid(unsafe_code, future_incompatible, rust_2018_idioms)]
#![no_std]

use breadx::{
    display::Cookie,
    prelude::*,
    protocol::xproto::{GetKeyboardMappingReply, Keycode, Keysym, Setup},
    Error, Result,
};
use keysyms::*;

const NO_SYMBOL: Keysym = 0;

#[path = "automatically_generated.rs"]
pub mod keysyms;

/// Keeps track of the keyboard state for the X11 display.
pub struct KeyboardState {
    innards: Innards,
}

enum Innards {
    /// The keyboard state hasn't been resolved.
    Unresolved(Cookie<GetKeyboardMappingReply>),
    /// The keyboard state has been resolved.
    Resolved(GetKeyboardMappingReply),
}

impl KeyboardState {
    /// Create a new `KeyboardState` associated with the given connection.
    pub fn new(dpy: &mut impl Display) -> Result<Self> {
        // open up the cookie
        let min_keycode = dpy.setup().min_keycode;
        let max_keycode = dpy.setup().max_keycode;
        let cookie = dpy.get_keyboard_mapping(min_keycode, max_keycode - min_keycode + 1)?;

        Ok(Self {
            innards: Innards::Unresolved(cookie),
        })
    }

    /// Create a new `KeyboardState`, async redox.
    #[cfg(feature = "async")]
    pub async fn new_async(dpy: &mut impl AsyncDisplay) -> Result<Self> {
        let min_keycode = dpy.setup().min_keycode;
        let max_keycode = dpy.setup().max_keycode;
        let cookie = dpy
            .get_keyboard_mapping(min_keycode, max_keycode - min_keycode + 1)
            .await?;

        Ok(Self {
            innards: Innards::Unresolved(cookie),
        })
    }

    /// Get the resolved keyboard mapping.
    fn resolve(&mut self, dpy: &mut impl Display) -> Result<&mut GetKeyboardMappingReply> {
        match self.innards {
            Innards::Unresolved(ref cookie) => {
                let reply = dpy.wait_for_reply(*cookie)?;
                self.innards = Innards::Resolved(reply);
                match &mut self.innards {
                    Innards::Resolved(reply) => Ok(reply),
                    _ => unreachable!(),
                }
            }
            Innards::Resolved(ref mut reply) => Ok(reply),
        }
    }

    #[cfg(feature = "async")]
    async fn resolve_async(
        &mut self,
        dpy: &mut impl AsyncDisplay,
    ) -> Result<&mut GetKeyboardMappingReply> {
        match self.innards {
            Innards::Unresolved(ref cookie) => {
                let reply = dpy.wait_for_reply(*cookie).await?;
                self.innards = Innards::Resolved(reply);
                match &mut self.innards {
                    Innards::Resolved(reply) => Ok(reply),
                    _ => unreachable!(),
                }
            }
            Innards::Resolved(ref mut reply) => Ok(reply),
        }
    }

    /// Refresh the keyboard mapping associated with this type.
    pub fn refresh(&mut self, dpy: &mut impl Display) -> Result<()> {
        let min_keycode = dpy.setup().min_keycode;
        let max_keycode = dpy.setup().max_keycode;

        // open up the cookie
        let cookie = dpy.get_keyboard_mapping(min_keycode, max_keycode - min_keycode + 1)?;

        self.innards = Innards::Unresolved(cookie);
        Ok(())
    }

    /// Refresh the keyboard mapping associated with this type, async redox.
    #[cfg(feature = "async")]
    pub async fn refresh_async(&mut self, dpy: &mut impl AsyncDisplay) -> Result<()> {
        let min_keycode = dpy.setup().min_keycode;
        let max_keycode = dpy.setup().max_keycode;

        // open up the cookie
        let cookie = dpy
            .get_keyboard_mapping(min_keycode, max_keycode - min_keycode + 1)
            .await?;

        self.innards = Innards::Unresolved(cookie);
        Ok(())
    }

    /// Get the keyboard symbol associated with the keycode and the
    /// column.
    pub fn symbol(
        &mut self,
        dpy: &mut impl Display,
        keycode: Keycode,
        column: u8,
    ) -> Result<Keysym> {
        let reply = self.resolve(dpy)?;
        get_symbol(dpy.setup(), reply, keycode, column)
    }

    /// Get the keyboard symbol associated with the keycode and the
    /// column, async redox.
    #[cfg(feature = "async")]
    pub async fn symbol_async(
        &mut self,
        dpy: &mut impl AsyncDisplay,
        keycode: Keycode,
        column: u8,
    ) -> Result<Keysym> {
        let reply = self.resolve_async(dpy).await?;
        get_symbol(dpy.setup(), reply, keycode, column)
    }
}

fn get_symbol(
    setup: &Setup,
    mapping: &GetKeyboardMappingReply,
    keycode: Keycode,
    mut column: u8,
) -> Result<Keysym> {
    // this is mostly a port of the logic from xcb keysyms
    let mut per = mapping.keysyms_per_keycode;
    if column >= per && column > 3 {
        return Err(Error::make_msg("Invalid column"));
    }

    // get the array of keysyms
    let start = (keycode - setup.min_keycode) as usize * per as usize;
    let end = start + per as usize;
    let keysyms = &mapping.keysyms[start..end];

    // get the alternate keysym if needed
    if column < 4 {
        if column > 1 {
            while per > 2 && keysyms[per as usize - 1] == NO_SYMBOL {
                per -= 1;
            }

            if per < 3 {
                column -= 2;
            }
        }

        if per <= column | 1 || keysyms[column as usize | 1] == NO_SYMBOL {
            // convert to upper/lower case
            let (upper, lower) = convert_case(keysyms[column as usize & !1]);
            if column & 1 == 0 {
                return Ok(lower);
            } else {
                return Ok(upper);
            }
        }
    }

    Ok(keysyms[column as usize])
}

/// Tell whether a keysym is a keypad key.
pub fn is_keypad_key(keysym: Keysym) -> bool {
    matches!(keysym, KEY_KP_Space..=KEY_KP_Equal)
}

/// Tell whether a keysym is a private keypad key.
pub fn is_private_keypad_key(keysym: Keysym) -> bool {
    matches!(keysym, 0x11000000..=0x1100FFFF)
}

/// Tell whether a keysym is a cursor key.
pub fn is_cursor_key(keysym: Keysym) -> bool {
    matches!(keysym, KEY_Home..=KEY_Select)
}

/// Tell whether a keysym is a PF key.
pub fn is_pf_key(keysym: Keysym) -> bool {
    matches!(keysym, KEY_KP_F1..=KEY_KP_F4)
}

/// Tell whether a keysym is a function key.
pub fn is_function_key(keysym: Keysym) -> bool {
    matches!(keysym, KEY_F1..=KEY_F35)
}

/// Tell whether a key is a miscellaneous function key.
pub fn is_misc_function_key(keysym: Keysym) -> bool {
    matches!(keysym, KEY_Select..=KEY_Break)
}

/// Tell whether a key is a modifier key.
pub fn is_modifier_key(keysym: Keysym) -> bool {
    matches!(
        keysym,
        KEY_Shift_L..=KEY_Hyper_R
         | KEY_ISO_Lock..=KEY_ISO_Level5_Lock
         | KEY_Mode_switch
         | KEY_Num_Lock
    )
}

/// Convert a keysym to its uppercase/lowercase equivalents.
fn convert_case(keysym: Keysym) -> (Keysym, Keysym) {
    // by default, they're both the regular keysym
    let (mut upper, mut lower) = (keysym, keysym);

    // tell which language it belongs to
    #[allow(non_upper_case_globals)]
    match keysym {
        KEY_A..=KEY_Z => lower += KEY_a - KEY_A,
        KEY_a..=KEY_z => upper -= KEY_a - KEY_A,
        KEY_Agrave..=KEY_Odiaeresis => lower += KEY_agrave - KEY_Agrave,
        KEY_agrave..=KEY_odiaeresis => upper -= KEY_agrave - KEY_Agrave,
        KEY_Ooblique..=KEY_Thorn => lower += KEY_oslash - KEY_Ooblique,
        KEY_oslash..=KEY_thorn => upper -= KEY_oslash - KEY_Ooblique,
        KEY_Aogonek => lower = KEY_aogonek,
        KEY_aogonek => upper = KEY_Aogonek,
        KEY_Lstroke..=KEY_Sacute => lower += KEY_lstroke - KEY_Lstroke,
        KEY_lstroke..=KEY_sacute => upper -= KEY_lstroke - KEY_Lstroke,
        KEY_Scaron..=KEY_Zacute => lower += KEY_scaron - KEY_Scaron,
        KEY_scaron..=KEY_zacute => upper -= KEY_scaron - KEY_Scaron,
        KEY_Zcaron..=KEY_Zabovedot => lower += KEY_zcaron - KEY_Zcaron,
        KEY_zcaron..=KEY_zabovedot => upper -= KEY_zcaron - KEY_Zcaron,
        KEY_Racute..=KEY_Tcedilla => lower += KEY_racute - KEY_Racute,
        KEY_racute..=KEY_tcedilla => upper -= KEY_racute - KEY_Racute,
        KEY_Hstroke..=KEY_Hcircumflex => lower += KEY_hstroke - KEY_Hstroke,
        KEY_hstroke..=KEY_hcircumflex => upper -= KEY_hstroke - KEY_Hstroke,
        KEY_Gbreve..=KEY_Jcircumflex => lower += KEY_gbreve - KEY_Gbreve,
        KEY_gbreve..=KEY_jcircumflex => upper -= KEY_gbreve - KEY_Gbreve,
        KEY_Cabovedot..=KEY_Scircumflex => lower += KEY_cabovedot - KEY_Cabovedot,
        KEY_cabovedot..=KEY_scircumflex => upper -= KEY_cabovedot - KEY_Cabovedot,
        KEY_Rcedilla..=KEY_Tslash => lower += KEY_rcedilla - KEY_Rcedilla,
        KEY_rcedilla..=KEY_tslash => upper -= KEY_rcedilla - KEY_Rcedilla,
        KEY_ENG => lower = KEY_eng,
        KEY_eng => upper = KEY_ENG,
        KEY_Amacron..=KEY_Umacron => lower += KEY_amacron - KEY_Amacron,
        KEY_amacron..=KEY_umacron => upper -= KEY_amacron - KEY_Amacron,
        KEY_Serbian_DJE..=KEY_Serbian_DZE => lower -= KEY_Serbian_DJE - KEY_Serbian_dje,
        KEY_Serbian_dje..=KEY_Serbian_dze => upper += KEY_Serbian_DJE - KEY_Serbian_dje,
        KEY_Cyrillic_YU..=KEY_Cyrillic_HARDSIGN => lower -= KEY_Cyrillic_YU - KEY_Cyrillic_yu,
        KEY_Cyrillic_yu..=KEY_Cyrillic_hardsign => upper += KEY_Cyrillic_YU - KEY_Cyrillic_yu,
        KEY_Greek_ALPHAaccent..=KEY_Greek_OMEGAaccent => {
            lower += KEY_Greek_alphaaccent - KEY_Greek_ALPHAaccent
        }
        KEY_Greek_alphaaccent..=KEY_Greek_omegaaccent
            if !matches!(
                keysym,
                KEY_Greek_iotaaccentdieresis | KEY_Greek_upsilonaccentdieresis
            ) =>
        {
            upper -= KEY_Greek_alphaaccent - KEY_Greek_ALPHAaccent
        }
        KEY_Greek_ALPHA..=KEY_Greek_OMEGA => lower += KEY_Greek_alpha - KEY_Greek_ALPHA,
        KEY_Greek_alpha..=KEY_Greek_omega if !matches!(keysym, KEY_Greek_finalsmallsigma) => {
            upper -= KEY_Greek_alpha - KEY_Greek_ALPHA
        }
        KEY_Armenian_AYB..=KEY_Armenian_fe => {
            lower |= 1;
            upper &= !1;
        }
        _ => {}
    }

    (upper, lower)
}