]> icculus.org git repositories - dana/openbox.git/blob - obt/keyboard.c
avoid ascii control characters in strings
[dana/openbox.git] / obt / keyboard.c
1 /* -*- indent-tabs-mode: nil; tab-width: 4; c-basic-offset: 4; -*-
2
3    obt/keyboard.c for the Openbox window manager
4    Copyright (c) 2007        Dana Jansens
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    See the COPYING file for a copy of the GNU General Public License.
17 */
18
19 #include "obt/display.h"
20 #include "obt/keyboard.h"
21
22 #include <X11/Xlib.h>
23 #include <X11/keysym.h>
24
25 struct _ObtIC
26 {
27     guint ref;
28     XIC xic;
29     Window client;
30     Window focus;
31 };
32
33 /* These masks are constants and the modifier keys are bound to them as
34    anyone sees fit:
35         ShiftMask (1<<0), LockMask (1<<1), ControlMask (1<<2), Mod1Mask (1<<3),
36         Mod2Mask (1<<4), Mod3Mask (1<<5), Mod4Mask (1<<6), Mod5Mask (1<<7)
37 */
38 #define NUM_MASKS 8
39 #define ALL_MASKS 0xff /* an or'ing of all 8 keyboard masks */
40
41 /* Get the bitflag for the n'th modifier mask */
42 #define nth_mask(n) (1 << n)
43
44 static void set_modkey_mask(guchar mask, KeySym sym);
45 static void xim_init(void);
46 void obt_keyboard_shutdown();
47 void obt_keyboard_context_renew(ObtIC *ic);
48
49 static XModifierKeymap *modmap;
50 static KeySym *keymap;
51 static gint min_keycode, max_keycode, keysyms_per_keycode;
52 /* This is a bitmask of the different masks for each modifier key */
53 static guchar modkeys_keys[OBT_KEYBOARD_NUM_MODKEYS];
54
55 static gboolean alt_l = FALSE;
56 static gboolean meta_l = FALSE;
57 static gboolean super_l = FALSE;
58 static gboolean hyper_l = FALSE;
59
60 static gboolean started = FALSE;
61
62 static XIM xim = NULL;
63 static XIMStyle xim_style = 0;
64 static GSList *xic_all = NULL;
65
66 void obt_keyboard_reload(void)
67 {
68     gint i, j, k;
69
70     if (started) obt_keyboard_shutdown(); /* free stuff */
71     started = TRUE;
72
73     xim_init();
74
75     /* reset the keys to not be bound to any masks */
76     for (i = 0; i < OBT_KEYBOARD_NUM_MODKEYS; ++i)
77         modkeys_keys[i] = 0;
78
79     modmap = XGetModifierMapping(obt_display);
80     /* note: modmap->max_keypermod can be 0 when there is no valid key layout
81        available */
82
83     XDisplayKeycodes(obt_display, &min_keycode, &max_keycode);
84     keymap = XGetKeyboardMapping(obt_display, min_keycode,
85                                  max_keycode - min_keycode + 1,
86                                  &keysyms_per_keycode);
87
88     alt_l = meta_l = super_l = hyper_l = FALSE;
89
90     /* go through each of the modifier masks (eg ShiftMask, CapsMask...) */
91     for (i = 0; i < NUM_MASKS; ++i) {
92         /* go through each keycode that is bound to the mask */
93         for (j = 0; j < modmap->max_keypermod; ++j) {
94             KeySym sym;
95             /* get a keycode that is bound to the mask (i) */
96             KeyCode keycode = modmap->modifiermap[i*modmap->max_keypermod + j];
97             if (keycode) {
98                 /* go through each keysym bound to the given keycode */
99                 for (k = 0; k < keysyms_per_keycode; ++k) {
100                     sym = keymap[(keycode-min_keycode) * keysyms_per_keycode +
101                                  k];
102                     if (sym != NoSymbol) {
103                         /* bind the key to the mask (e.g. Alt_L => Mod1Mask) */
104                         set_modkey_mask(nth_mask(i), sym);
105                     }
106                 }
107             }
108         }
109     }
110
111     /* CapsLock, Shift, and Control are special and hard-coded */
112     modkeys_keys[OBT_KEYBOARD_MODKEY_CAPSLOCK] = LockMask;
113     modkeys_keys[OBT_KEYBOARD_MODKEY_SHIFT] = ShiftMask;
114     modkeys_keys[OBT_KEYBOARD_MODKEY_CONTROL] = ControlMask;
115 }
116
117 void obt_keyboard_shutdown(void)
118 {
119     GSList *it;
120
121     XFreeModifiermap(modmap);
122     modmap = NULL;
123     XFree(keymap);
124     keymap = NULL;
125     for (it = xic_all; it; it = g_slist_next(it)) {
126         ObtIC* ic = it->data;
127         if (ic->xic) {
128             XDestroyIC(ic->xic);
129             ic->xic = NULL;
130         }
131     }
132     if (xim) XCloseIM(xim);
133     xim = NULL;
134     xim_style = 0;
135     started = FALSE;
136 }
137
138 void xim_init(void)
139 {
140     GSList *it;
141     gchar *aname, *aclass;
142
143     aname = g_strdup(g_get_prgname());
144     if (!aname) aname = g_strdup("obt");
145
146     aclass = g_strdup(aname);
147     if (g_ascii_islower(aclass[0]))
148         aclass[0] = g_ascii_toupper(aclass[0]);
149
150     g_print("Opening Input Method for %s %s\n", aname, aclass);
151     xim = XOpenIM(obt_display, NULL, aname, aclass);
152
153     if (!xim)
154         g_message("Failed to open an Input Method");
155     else {
156         XIMStyles *xim_styles = NULL;
157         char *r;
158
159         /* get the input method styles */
160         r = XGetIMValues(xim, XNQueryInputStyle, &xim_styles, NULL);
161         if (r || !xim_styles)
162             g_message("Input Method does not support any styles");
163         if (xim_styles) {
164             int i;
165
166             /* find a style that doesnt need preedit or status */
167             for (i = 0; i < xim_styles->count_styles; ++i) {
168                 if (xim_styles->supported_styles[i] == 
169                     (XIMPreeditNothing | XIMStatusNothing))
170                 {
171                     xim_style = xim_styles->supported_styles[i];
172                     break;
173                 }
174             }
175             XFree(xim_styles);
176         }
177
178         if (!xim_style) {
179             g_message("Input Method does not support a usable style");
180
181             XCloseIM(xim);
182             xim = NULL;
183         }
184     }
185
186     /* any existing contexts need to be recreated for the new input method */
187     for (it = xic_all; it; it = g_slist_next(it))
188         obt_keyboard_context_renew(it->data);
189
190     g_free(aclass);
191     g_free(aname);
192 }
193
194 ObtModkeysKey obt_keyboard_keyevent_to_modkey(XEvent *e)
195 {
196     KeySym sym;
197
198     g_return_val_if_fail(e->type == KeyPress || e->type == KeyRelease,
199                          OBT_KEYBOARD_MODKEY_NONE);
200
201     XLookupString(&e->xkey, NULL, 0, &sym, NULL);
202
203     switch (sym) {
204     case XK_Num_Lock: return OBT_KEYBOARD_MODKEY_NUMLOCK;
205     case XK_Scroll_Lock: return OBT_KEYBOARD_MODKEY_SCROLLLOCK;
206     case XK_Caps_Lock: return OBT_KEYBOARD_MODKEY_SHIFT;
207     case XK_Alt_L:
208     case XK_Alt_R: return OBT_KEYBOARD_MODKEY_ALT;
209     case XK_Super_L:
210     case XK_Super_R: return OBT_KEYBOARD_MODKEY_SUPER;
211     case XK_Hyper_L:
212     case XK_Hyper_R: return OBT_KEYBOARD_MODKEY_SUPER;
213     case XK_Meta_L:
214     case XK_Meta_R: return OBT_KEYBOARD_MODKEY_SUPER;
215     case XK_Control_L:
216     case XK_Control_R: return OBT_KEYBOARD_MODKEY_CONTROL;
217     case XK_Shift_L:
218     case XK_Shift_R: return OBT_KEYBOARD_MODKEY_SHIFT;
219     default: return OBT_KEYBOARD_MODKEY_NONE;
220     }
221 }
222
223 guint obt_keyboard_keyevent_to_modmask(XEvent *e)
224 {
225     g_return_val_if_fail(e->type == KeyPress || e->type == KeyRelease, 0);
226
227     return obt_keyboard_modkey_to_modmask(obt_keyboard_keyevent_to_modkey(e));
228 }
229
230 guint obt_keyboard_only_modmasks(guint mask)
231 {
232     mask &= ALL_MASKS;
233     /* strip off these lock keys. they shouldn't affect key bindings */
234     mask &= ~LockMask; /* use the LockMask, not what capslock is bound to,
235                           because you could bind it to something else and it
236                           should work as that modifier then. i think capslock
237                           is weird in xkb. */
238     mask &= ~obt_keyboard_modkey_to_modmask(OBT_KEYBOARD_MODKEY_NUMLOCK);
239     mask &= ~obt_keyboard_modkey_to_modmask(OBT_KEYBOARD_MODKEY_SCROLLLOCK);
240     return mask;
241 }
242
243 guint obt_keyboard_modkey_to_modmask(ObtModkeysKey key)
244 {
245     return modkeys_keys[key];
246 }
247
248 static void set_modkey_mask(guchar mask, KeySym sym)
249 {
250     /* find what key this is, and bind it to the mask */
251
252     if (sym == XK_Num_Lock)
253         modkeys_keys[OBT_KEYBOARD_MODKEY_NUMLOCK] |= mask;
254     else if (sym == XK_Scroll_Lock)
255         modkeys_keys[OBT_KEYBOARD_MODKEY_SCROLLLOCK] |= mask;
256
257     else if (sym == XK_Super_L && super_l)
258         modkeys_keys[OBT_KEYBOARD_MODKEY_SUPER] |= mask;
259     else if (sym == XK_Super_L && !super_l)
260         /* left takes precident over right, so erase any masks the right
261            key may have set */
262         modkeys_keys[OBT_KEYBOARD_MODKEY_SUPER] = mask, super_l = TRUE;
263     else if (sym == XK_Super_R && !super_l)
264         modkeys_keys[OBT_KEYBOARD_MODKEY_SUPER] |= mask;
265
266     else if (sym == XK_Hyper_L && hyper_l)
267         modkeys_keys[OBT_KEYBOARD_MODKEY_HYPER] |= mask;
268     else if (sym == XK_Hyper_L && !hyper_l)
269         modkeys_keys[OBT_KEYBOARD_MODKEY_HYPER] = mask, hyper_l = TRUE;
270     else if (sym == XK_Hyper_R && !hyper_l)
271         modkeys_keys[OBT_KEYBOARD_MODKEY_HYPER] |= mask;
272
273     else if (sym == XK_Alt_L && alt_l)
274         modkeys_keys[OBT_KEYBOARD_MODKEY_ALT] |= mask;
275     else if (sym == XK_Alt_L && !alt_l)
276         modkeys_keys[OBT_KEYBOARD_MODKEY_ALT] = mask, alt_l = TRUE;
277     else if (sym == XK_Alt_R && !alt_l)
278         modkeys_keys[OBT_KEYBOARD_MODKEY_ALT] |= mask;
279
280     else if (sym == XK_Meta_L && meta_l)
281         modkeys_keys[OBT_KEYBOARD_MODKEY_META] |= mask;
282     else if (sym == XK_Meta_L && !meta_l)
283         modkeys_keys[OBT_KEYBOARD_MODKEY_META] = mask, meta_l = TRUE;
284     else if (sym == XK_Meta_R && !meta_l)
285         modkeys_keys[OBT_KEYBOARD_MODKEY_META] |= mask;
286
287     /* CapsLock, Shift, and Control are special and hard-coded */
288 }
289
290 KeyCode* obt_keyboard_keysym_to_keycode(KeySym sym)
291 {
292     KeyCode *ret;
293     gint i, j, n;
294
295     ret = g_new(KeyCode, 1);
296     n = 0;
297     ret[n] = 0;
298
299     /* go through each keycode and look for the keysym */
300     for (i = min_keycode; i <= max_keycode; ++i)
301         for (j = 0; j < keysyms_per_keycode; ++j)
302             if (sym == keymap[(i-min_keycode) * keysyms_per_keycode + j]) {
303                 ret = g_renew(KeyCode, ret, ++n + 1);
304                 ret[n-1] = i;
305                 ret[n] = 0;
306             }
307     return ret;
308 }
309
310 gunichar obt_keyboard_keypress_to_unichar(ObtIC *ic, XEvent *ev)
311 {
312     gunichar unikey = 0;
313     KeySym sym;
314     Status status;
315     gchar *buf, fixbuf[4]; /* 4 is enough for a utf8 char */
316     gint len, bufsz;
317     gboolean got_string = FALSE;
318
319     g_return_val_if_fail(ev->type == KeyPress, 0);
320
321     if (!ic)
322         g_warning("Using obt_keyboard_keypress_to_unichar() without an "
323                   "Input Context.  No i18n support!");
324
325     if (ic && ic->xic) {
326         buf = fixbuf;
327         bufsz = sizeof(fixbuf);
328
329 #ifdef X_HAVE_UTF8_STRING
330         len = Xutf8LookupString(ic->xic, &ev->xkey, buf, bufsz, &sym, &status);
331 #else
332         len = XmbLookupString(ic->xic, &ev->xkey, buf, bufsz, &sym, &status);
333 #endif
334
335         if (status == XBufferOverflow) {
336             buf = g_new(char, len);
337             bufsz = len;
338
339 #ifdef X_HAVE_UTF8_STRING
340             len = Xutf8LookupString(ic->xic, &ev->xkey, buf, bufsz, &sym,
341                                     &status);
342 #else
343             len = XmbLookupString(ic->xic, &ev->xkey, buf, bufsz, &sym,
344                                   &status);
345 #endif
346         }
347
348         if ((status == XLookupChars || status == XLookupBoth)) {
349             if ((guchar)buf[0] >= 32) { /* not an ascii control character */
350 #ifndef X_HAVE_UTF8_STRING
351                 /* convert to utf8 */
352                 gchar *buf2 = buf;
353                 buf = g_locale_to_utf8(buf2, r, NULL, NULL, NULL);
354                 g_free(buf2);
355 #endif
356
357                 got_string = TRUE;
358             }
359         }
360         else if (status == XLookupKeySym)
361             /* this key doesn't have a text representation, it is a command
362                key of some sort */;
363         else
364             g_message("Bad keycode lookup. Keysym 0x%x Status: %s\n",
365                       (guint) sym,
366                       (status == XBufferOverflow ? "BufferOverflow" :
367                        status == XLookupNone ? "XLookupNone" :
368                        status == XLookupKeySym ? "XLookupKeySym" :
369                        "Unknown status"));
370     }
371     else {
372         buf = fixbuf;
373         bufsz = sizeof(fixbuf);
374         len = XLookupString(&ev->xkey, buf, bufsz, &sym, NULL);
375         if ((guchar)buf[0] >= 32) /* not an ascii control character */
376             got_string = TRUE;
377     }
378
379     if (got_string) {
380         gunichar u = g_utf8_get_char_validated(buf, len);
381         if (u && u != (gunichar)-1 && u != (gunichar)-2)
382             unikey = u;
383     }
384
385     if (buf != fixbuf) g_free(buf);
386
387     return unikey;
388 }
389
390 KeySym obt_keyboard_keypress_to_keysym(XEvent *ev)
391 {
392     KeySym sym;
393     gint r;
394
395     g_return_val_if_fail(ev->type == KeyPress, None);
396
397     sym = None;
398     r = XLookupString(&ev->xkey, NULL, 0, &sym, NULL);
399     return sym;
400 }
401
402 void obt_keyboard_context_renew(ObtIC *ic)
403 {
404     if (xim) {
405         ic->xic = XCreateIC(xim,
406                             XNInputStyle, xim_style,
407                             XNClientWindow, ic->client,
408                             XNFocusWindow, ic->focus,
409                             NULL);
410         if (!ic->xic)
411             g_message("Error creating Input Context for window 0x%x 0x%x\n",
412                       (guint)ic->client, (guint)ic->focus);
413     }
414 }
415
416 ObtIC* obt_keyboard_context_new(Window client, Window focus)
417 {
418     ObtIC *ic;
419
420     g_return_val_if_fail(client != None && focus != None, NULL);
421
422     ic = g_slice_new(ObtIC);
423     ic->ref = 1;
424     ic->client = client;
425     ic->focus = focus;
426     ic->xic = NULL;
427
428     obt_keyboard_context_renew(ic);
429     xic_all = g_slist_prepend(xic_all, ic);
430
431     return ic;
432 }
433
434 void obt_keyboard_context_ref(ObtIC *ic)
435 {
436     ++ic->ref;
437 }
438
439 void obt_keyboard_context_unref(ObtIC *ic)
440 {
441     if (--ic->ref < 1) {
442         xic_all = g_slist_remove(xic_all, ic);
443         XDestroyIC(ic->xic);
444         g_slice_free(ObtIC, ic);
445     }
446 }