]> git.sur5r.net Git - i3/i3/blob - libi3/get_mod_mask.c
3b6976ad6b0d1669149fed67533aa53d1b1d4b7c
[i3/i3] / libi3 / get_mod_mask.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  */
8 #include <stdint.h>
9 #include <stdlib.h>
10 #include <xcb/xcb.h>
11 #include <xcb/xcb_keysyms.h>
12
13 #include "libi3.h"
14
15 extern xcb_connection_t *conn;
16
17 /*
18  * All-in-one function which returns the modifier mask (XCB_MOD_MASK_*) for the
19  * given keysymbol, for example for XCB_NUM_LOCK (usually configured to mod2).
20  *
21  * This function initiates one round-trip. Use get_mod_mask_for() directly if
22  * you already have the modifier mapping and key symbols.
23  *
24  */
25 uint32_t aio_get_mod_mask_for(uint32_t keysym, xcb_key_symbols_t *symbols) {
26     xcb_get_modifier_mapping_cookie_t cookie;
27     xcb_get_modifier_mapping_reply_t *modmap_r;
28
29     xcb_flush(conn);
30
31     /* Get the current modifier mapping (this is blocking!) */
32     cookie = xcb_get_modifier_mapping(conn);
33     if (!(modmap_r = xcb_get_modifier_mapping_reply(conn, cookie, NULL)))
34         return 0;
35
36     uint32_t result = get_mod_mask_for(keysym, symbols, modmap_r);
37     free(modmap_r);
38     return result;
39 }
40
41 /*
42  * Returns the modifier mask (XCB_MOD_MASK_*) for the given keysymbol, for
43  * example for XCB_NUM_LOCK (usually configured to mod2).
44  *
45  * This function does not initiate any round-trips.
46  *
47  */
48 uint32_t get_mod_mask_for(uint32_t keysym,
49                           xcb_key_symbols_t *symbols,
50                           xcb_get_modifier_mapping_reply_t *modmap_reply) {
51     xcb_keycode_t *codes, *modmap;
52     xcb_keycode_t mod_code;
53
54     modmap = xcb_get_modifier_mapping_keycodes(modmap_reply);
55
56     /* Get the list of keycodes for the given symbol */
57     if (!(codes = xcb_key_symbols_get_keycode(symbols, keysym)))
58         return 0;
59
60     /* Loop through all modifiers (Mod1-Mod5, Shift, Control, Lock) */
61     for (int mod = 0; mod < 8; mod++)
62         for (int j = 0; j < modmap_reply->keycodes_per_modifier; j++) {
63             /* Store the current keycode (for modifier 'mod') */
64             mod_code = modmap[(mod * modmap_reply->keycodes_per_modifier) + j];
65             /* Check if that keycode is in the list of previously resolved
66              * keycodes for our symbol. If so, return the modifier mask. */
67             for (xcb_keycode_t *code = codes; *code; code++) {
68                 if (*code != mod_code)
69                     continue;
70
71                 free(codes);
72                 /* This corresponds to the XCB_MOD_MASK_* constants */
73                 return (1 << mod);
74             }
75         }
76
77     return 0;
78 }