]> Pileus Git - ~andy/gtk/blob - gdk/x11/gdkkeys-x11.c
Fix variable declaration not at start of block. (#120371, Damien Carbery)
[~andy/gtk] / gdk / x11 / gdkkeys-x11.c
1 /* GDK - The GIMP Drawing Kit
2  * Copyright (C) 2000 Red Hat, Inc.
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GTK+ Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
25  */
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <limits.h>
32 #include <errno.h>
33
34 #include "gdk.h"
35 #include "gdkx.h"
36
37 #include "gdkprivate-x11.h"
38 #include "gdkinternals.h"
39 #include "gdkdisplay-x11.h"
40 #include "gdkkeysyms.h"
41
42 #include "config.h"
43
44 #ifdef HAVE_XKB
45 #include <X11/XKBlib.h>
46
47 /* OSF-4.0 is apparently missing this macro
48  */
49 #  ifndef XkbKeySymEntry
50 #    define XkbKeySymEntry(d,k,sl,g) \
51         (XkbKeySym(d,k,((XkbKeyGroupsWidth(d,k)*(g))+(sl))))
52 #  endif
53 #endif /* HAVE_XKB */
54
55 typedef struct _GdkKeymapX11 GdkKeymapX11;
56
57 #define GDK_TYPE_KEYMAP_X11          (gdk_keymap_x11_get_type ())
58 #define GDK_KEYMAP_X11(object)       (G_TYPE_CHECK_INSTANCE_CAST ((object), GDK_TYPE_KEYMAP_X11, GdkKeymapX11))
59 #define GDK_IS_KEYMAP_X11(object)    (G_TYPE_CHECK_INSTANCE_TYPE ((object), GDK_TYPE_KEYMAP_X11))
60
61 struct _GdkKeymapX11
62 {
63   GdkKeymap     parent_instance;
64   
65   gint min_keycode;
66   gint max_keycode;
67   KeySym* keymap;
68   gint keysyms_per_keycode;
69   XModifierKeymap* mod_keymap;
70   guint lock_keysym;
71   GdkModifierType group_switch_mask;
72   GdkModifierType num_lock_mask;
73   gboolean sun_keypad;
74   PangoDirection current_direction;
75   gboolean have_direction;
76   guint current_serial;
77   
78 #ifdef HAVE_XKB
79   XkbDescPtr xkb_desc;
80 #endif
81 };
82
83 #define KEYMAP_USE_XKB(keymap) GDK_DISPLAY_X11 ((keymap)->display)->use_xkb
84 #define KEYMAP_XDISPLAY(keymap) GDK_DISPLAY_XDISPLAY ((keymap)->display)
85
86 static GType gdk_keymap_x11_get_type (void);
87 static void  gdk_keymap_x11_init     (GdkKeymapX11 *keymap);
88
89 static GType
90 gdk_keymap_x11_get_type (void)
91 {
92   static GType object_type = 0;
93
94   if (!object_type)
95     {
96       static const GTypeInfo object_info =
97         {
98           sizeof (GdkKeymapClass),
99           (GBaseInitFunc) NULL,
100           (GBaseFinalizeFunc) NULL,
101           (GClassInitFunc) NULL,
102           NULL,           /* class_finalize */
103           NULL,           /* class_data */
104           sizeof (GdkKeymapX11),
105           0,              /* n_preallocs */
106           (GInstanceInitFunc) gdk_keymap_x11_init,
107         };
108       
109       object_type = g_type_register_static (GDK_TYPE_KEYMAP,
110                                             "GdkKeymapX11",
111                                             &object_info, 0);
112     }
113   
114   return object_type;
115 }
116
117 static void
118 gdk_keymap_x11_init (GdkKeymapX11 *keymap)
119 {
120   keymap->min_keycode = 0;
121   keymap->max_keycode = 0;
122
123   keymap->keymap = NULL;
124   keymap->keysyms_per_keycode = 0;
125   keymap->mod_keymap = NULL;
126   
127   keymap->num_lock_mask = 0;
128   keymap->sun_keypad = FALSE;
129   keymap->group_switch_mask = 0;
130   keymap->lock_keysym = GDK_Caps_Lock;
131   keymap->have_direction = FALSE;
132   
133 #ifdef HAVE_XKB
134   keymap->xkb_desc = NULL;
135 #endif
136
137   keymap->current_serial = 0;
138 }
139
140 static inline void
141 update_keyrange (GdkKeymapX11 *keymap_x11)
142 {
143   if (keymap_x11->max_keycode == 0)
144     XDisplayKeycodes (KEYMAP_XDISPLAY (GDK_KEYMAP (keymap_x11)),
145                       &keymap_x11->min_keycode, &keymap_x11->max_keycode);
146 }
147
148 #ifdef HAVE_XKB
149
150 static XkbDescPtr
151 get_xkb (GdkKeymapX11 *keymap_x11)
152 {
153   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (GDK_KEYMAP (keymap_x11)->display);
154   Display *xdisplay = display_x11->xdisplay;
155   
156   update_keyrange (keymap_x11);
157   
158   if (keymap_x11->xkb_desc == NULL)
159     {
160       keymap_x11->xkb_desc = XkbGetMap (xdisplay, XkbKeySymsMask | XkbKeyTypesMask, XkbUseCoreKbd);
161       if (keymap_x11->xkb_desc == NULL)
162         g_error ("Failed to get keymap");
163
164       XkbGetNames (xdisplay, XkbGroupNamesMask, keymap_x11->xkb_desc);
165     }
166   else if (keymap_x11->current_serial != display_x11->keymap_serial)
167     {
168       XkbGetUpdatedMap (xdisplay, XkbKeySymsMask | XkbKeyTypesMask,
169                         keymap_x11->xkb_desc);
170       XkbGetNames (xdisplay, XkbGroupNamesMask, keymap_x11->xkb_desc);
171     }
172
173   keymap_x11->current_serial = display_x11->keymap_serial;
174
175   return keymap_x11->xkb_desc;
176 }
177 #endif /* HAVE_XKB */
178
179 /* Whether we were able to turn on detectable-autorepeat using
180  * XkbSetDetectableAutorepeat. If FALSE, we'll fall back
181  * to checking the next event with XPending().
182  */
183
184 /** 
185  * gdk_keymap_get_for_display:
186  * @display: the #GdkDisplay.
187  * @returns: the #GdkKeymap attached to @display.
188  *
189  * Returns the #GdkKeymap attached to @display.
190  *
191  * Since: 2.2
192  **/
193 GdkKeymap*
194 gdk_keymap_get_for_display (GdkDisplay *display)
195 {
196   GdkDisplayX11 *display_x11;
197   g_return_val_if_fail (GDK_IS_DISPLAY (display), NULL);
198   display_x11 = GDK_DISPLAY_X11 (display);
199   
200   if (!display_x11->keymap)
201     display_x11->keymap = g_object_new (gdk_keymap_x11_get_type (), NULL);
202
203   display_x11->keymap->display = display;
204
205   return display_x11->keymap;
206 }
207
208 /* Find the index of the group/level pair within the keysyms for a key.
209  */
210 #define KEYSYM_INDEX(keymap_impl, group, level) \
211   (2 * ((group) % (keymap_impl->keysyms_per_keycode / 2)) + (level))
212 #define KEYSYM_IS_KEYPAD(s) (((s) >= 0xff80 && (s) <= 0xffbd) || \
213                              ((s) >= 0x11000000 && (s) <= 0x1100ffff))
214
215 static void
216 update_keymaps (GdkKeymapX11 *keymap_x11)
217 {
218   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (GDK_KEYMAP (keymap_x11)->display);
219   Display *xdisplay = display_x11->xdisplay;
220   
221 #ifdef HAVE_XKB
222   g_assert (!KEYMAP_USE_XKB (GDK_KEYMAP (keymap_x11)));
223 #endif
224   
225   if (keymap_x11->keymap == NULL ||
226       keymap_x11->current_serial != display_x11->keymap_serial)
227     {
228       gint i;
229       gint map_size;
230       gint keycode;
231
232       keymap_x11->current_serial = display_x11->keymap_serial;
233       
234       update_keyrange (keymap_x11);
235       
236       if (keymap_x11->keymap)
237         XFree (keymap_x11->keymap);
238
239       if (keymap_x11->mod_keymap)
240         XFreeModifiermap (keymap_x11->mod_keymap);
241       
242       keymap_x11->keymap = XGetKeyboardMapping (xdisplay, keymap_x11->min_keycode,
243                                                 keymap_x11->max_keycode - keymap_x11->min_keycode + 1,
244                                                 &keymap_x11->keysyms_per_keycode);
245
246
247       /* GDK_ISO_Left_Tab, as usually configured through XKB, really messes
248        * up the whole idea of "consumed modifiers" because shift is consumed.
249        * However, <shift>Tab is not usually GDK_ISO_Left_Tab without XKB,
250        * we we fudge the map here.
251        */
252       keycode = keymap_x11->min_keycode;
253       while (keycode <= keymap_x11->max_keycode)
254         {
255           KeySym *syms = keymap_x11->keymap + (keycode - keymap_x11->min_keycode) * keymap_x11->keysyms_per_keycode;
256           /* Check both groups */
257           for (i = 0 ; i < 2 ; i++)
258             {
259               if (syms[KEYSYM_INDEX (keymap_x11, i, 0)] == GDK_Tab)
260                 syms[KEYSYM_INDEX (keymap_x11, i, 1)] = GDK_ISO_Left_Tab;
261             }
262
263           /*
264            * If there is one keysym and the key symbol has upper and lower
265            * case variants fudge the keymap
266            */
267           if (syms[KEYSYM_INDEX (keymap_x11, 0, 1)] == 0)
268             {
269               guint lower;
270               guint upper;
271
272               gdk_keyval_convert_case (syms[KEYSYM_INDEX (keymap_x11, 0, 0)], &lower, &upper);
273               if (lower != upper)
274                 {
275                   syms[KEYSYM_INDEX (keymap_x11, 0, 0)] = lower;
276                   syms[KEYSYM_INDEX (keymap_x11, 0, 1)] = upper;
277                 }
278             }
279       
280           
281           ++keycode;
282         }
283
284       keymap_x11->mod_keymap = XGetModifierMapping (xdisplay);
285
286       keymap_x11->lock_keysym = GDK_VoidSymbol;
287       keymap_x11->group_switch_mask = 0;
288       keymap_x11->num_lock_mask = 0;
289
290       /* There are 8 sets of modifiers, with each set containing
291        * max_keypermod keycodes.
292        */
293       map_size = 8 * keymap_x11->mod_keymap->max_keypermod;
294       for (i = 0; i < map_size; i++)
295         {
296           /* Get the key code at this point in the map. */
297           gint keycode = keymap_x11->mod_keymap->modifiermap[i];
298           gint j;
299           KeySym *syms;
300           guint mask;
301
302           /* Ignore invalid keycodes. */
303           if (keycode < keymap_x11->min_keycode ||
304               keycode > keymap_x11->max_keycode)
305             continue;
306
307           syms = keymap_x11->keymap + (keycode - keymap_x11->min_keycode) * keymap_x11->keysyms_per_keycode;
308
309           /* The fourth modifier, GDK_MOD1_MASK is 1 << 3.
310            * Each group of max_keypermod entries refers to the same modifier.
311            */
312           mask = 1 << (i / keymap_x11->mod_keymap->max_keypermod);
313
314           switch (mask)
315             {
316             case GDK_LOCK_MASK:
317               /* Get the Lock keysym.  If any keysym bound to the Lock modifier
318                * is Caps_Lock, we will interpret the modifier as Caps_Lock;
319                * otherwise, if any is bound to Shift_Lock, we will interpret
320                * the modifier as Shift_Lock. Otherwise, the lock modifier
321                * has no effect.
322                */
323               for (j = 0; j < keymap_x11->keysyms_per_keycode; j++)
324                 {
325                   if (syms[j] == GDK_Caps_Lock)
326                     keymap_x11->lock_keysym = GDK_Caps_Lock;
327                   else if (syms[j] == GDK_Shift_Lock &&
328                            keymap_x11->lock_keysym == GDK_VoidSymbol)
329                     keymap_x11->lock_keysym = GDK_Shift_Lock;
330                 }
331               break;
332
333             case GDK_CONTROL_MASK:
334             case GDK_SHIFT_MASK:
335             case GDK_MOD1_MASK:
336               /* Some keyboard maps are known to map Mode_Switch as an
337                * extra Mod1 key. In circumstances like that, it won't be
338                * used to switch groups.
339                */
340               break;
341
342             default:
343               /* Find the Mode_Switch and Num_Lock modifiers. */
344               for (j = 0; j < keymap_x11->keysyms_per_keycode; j++)
345                 {
346                   if (syms[j] == GDK_Mode_switch)
347                     {
348                       /* This modifier swaps groups */
349                       keymap_x11->group_switch_mask |= mask;
350                     }
351                   else if (syms[j] == GDK_Num_Lock)
352                     {
353                       /* This modifier is used for Num_Lock */
354                       keymap_x11->num_lock_mask |= mask;
355                     }
356                 }
357               break;
358             }
359         }
360
361       /* Hack: The Sun X server puts the keysym to use when the Num Lock
362        * modifier is on in the third element of the keysym array, instead
363        * of the second.
364        */
365       if ((strcmp (ServerVendor (xdisplay), "Sun Microsystems, Inc.") == 0) &&
366           (keymap_x11->keysyms_per_keycode > 2))
367         keymap_x11->sun_keypad = TRUE;
368       else
369         keymap_x11->sun_keypad = FALSE;
370     }
371 }
372
373 static const KeySym*
374 get_keymap (GdkKeymapX11 *keymap_x11)
375 {
376   update_keymaps (keymap_x11);
377   
378   return keymap_x11->keymap;
379 }
380
381 #if HAVE_XKB
382 static PangoDirection
383 get_direction (GdkKeymapX11 *keymap_x11)
384 {
385   XkbDescRec *xkb = get_xkb (keymap_x11);
386   const char *name;
387   XkbStateRec state_rec;
388   PangoDirection result;
389
390   GdkDisplay *display = GDK_KEYMAP (keymap_x11)->display;
391
392   XkbGetState (GDK_DISPLAY_XDISPLAY (display), XkbUseCoreKbd, &state_rec);
393   
394   if (xkb->names->groups[state_rec.locked_group] == None)
395     result = PANGO_DIRECTION_LTR;
396   else
397     {
398       name = gdk_x11_get_xatom_name_for_display (display, xkb->names->groups[state_rec.locked_group]);
399
400       if (g_ascii_strcasecmp (name, "arabic") == 0 ||
401           g_ascii_strcasecmp (name, "hebrew") == 0 ||
402           g_ascii_strcasecmp (name, "israelian") == 0)
403         result = PANGO_DIRECTION_RTL;
404       else
405         result = PANGO_DIRECTION_LTR;
406     }
407     
408   return result;
409 }
410
411 void
412 _gdk_keymap_state_changed (GdkDisplay *display)
413 {
414   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (display);
415   
416   if (display_x11->keymap)
417     {
418       GdkKeymapX11 *keymap_x11 = GDK_KEYMAP_X11 (display_x11->keymap);
419       
420       PangoDirection new_direction = get_direction (keymap_x11);
421       
422       if (!keymap_x11->have_direction || new_direction != keymap_x11->current_direction)
423         {
424           keymap_x11->have_direction = TRUE;
425           keymap_x11->current_direction = new_direction;
426           g_signal_emit_by_name (keymap_x11, "direction_changed");
427         }
428     }
429 }
430
431 #endif /* HAVE_XKB */
432
433 void
434 _gdk_keymap_keys_changed (GdkDisplay *display)
435 {
436   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (display);
437   
438   ++display_x11->keymap_serial;
439   
440   if (display_x11->keymap)
441     g_signal_emit_by_name (display_x11->keymap, "keys_changed", 0);
442 }
443
444 PangoDirection
445 gdk_keymap_get_direction (GdkKeymap *keymap)
446 {
447   if (!keymap)
448     {
449       keymap = gdk_keymap_get_for_display (gdk_display_get_default ());
450       GDK_NOTE (MULTIHEAD,
451                 g_message ("_multihead : reverting to default display keymap "
452                            "in gdk_keymap_get_direction"));
453     }
454   
455 #if HAVE_XKB
456   if (KEYMAP_USE_XKB (keymap))
457     {
458       GdkKeymapX11 *keymap_x11 = GDK_KEYMAP_X11 (keymap);
459       
460       if (!keymap_x11->have_direction)
461         {
462           keymap_x11->current_direction = get_direction (keymap_x11);
463           keymap_x11->have_direction = TRUE;
464         }
465   
466       return keymap_x11->current_direction;
467     }
468   else
469 #endif /* HAVE_XKB */
470     return PANGO_DIRECTION_LTR;
471 }
472
473 /**
474  * gdk_keymap_get_entries_for_keyval:
475  * @keymap: a #GdkKeymap, or %NULL to use the default keymap
476  * @keyval: a keyval, such as %GDK_a, %GDK_Up, %GDK_Return, etc.
477  * @keys: return location for an array of #GdkKeymapKey
478  * @n_keys: return location for number of elements in returned array
479  * 
480  * Obtains a list of keycode/group/level combinations that will
481  * generate @keyval. Groups and levels are two kinds of keyboard mode;
482  * in general, the level determines whether the top or bottom symbol
483  * on a key is used, and the group determines whether the left or
484  * right symbol is used. On US keyboards, the shift key changes the
485  * keyboard level, and there are no groups. A group switch key might
486  * convert a keyboard between Hebrew to English modes, for example.
487  * #GdkEventKey contains a %group field that indicates the active
488  * keyboard group. The level is computed from the modifier mask.
489  * The returned array should be freed
490  * with g_free().
491  *
492  * Return value: %TRUE if keys were found and returned
493  **/
494 gboolean
495 gdk_keymap_get_entries_for_keyval (GdkKeymap     *keymap,
496                                    guint          keyval,
497                                    GdkKeymapKey **keys,
498                                    gint          *n_keys)
499 {
500   GArray *retval;
501   GdkKeymapX11 *keymap_x11;
502
503   g_return_val_if_fail (keymap == NULL || GDK_IS_KEYMAP (keymap), FALSE);
504   g_return_val_if_fail (keys != NULL, FALSE);
505   g_return_val_if_fail (n_keys != NULL, FALSE);
506   g_return_val_if_fail (keyval != 0, FALSE);
507
508   if (!keymap)
509     {
510       keymap = gdk_keymap_get_for_display (gdk_display_get_default ());
511       GDK_NOTE (MULTIHEAD,
512                 g_message ("_multihead : reverting to default display keymap "
513                            "in gdk_keymap_get_entries_for_keyval\n"));
514     }
515
516   keymap_x11 = GDK_KEYMAP_X11 (keymap);
517   
518   retval = g_array_new (FALSE, FALSE, sizeof (GdkKeymapKey));
519
520 #ifdef HAVE_XKB
521   if (KEYMAP_USE_XKB (keymap))
522     {
523       /* See sec 15.3.4 in XKB docs */
524
525       XkbDescRec *xkb = get_xkb (keymap_x11);
526       gint keycode;
527       
528       keycode = keymap_x11->min_keycode;
529
530       while (keycode <= keymap_x11->max_keycode)
531         {
532           gint max_shift_levels = XkbKeyGroupsWidth (xkb, keycode); /* "key width" */
533           gint group = 0;
534           gint level = 0;
535           gint total_syms = XkbKeyNumSyms (xkb, keycode);
536           gint i = 0;
537           KeySym *entry;
538
539           /* entry is an array with all syms for group 0, all
540            * syms for group 1, etc. and for each group the
541            * shift level syms are in order
542            */
543           entry = XkbKeySymsPtr (xkb, keycode);
544
545           while (i < total_syms)
546             {
547               /* check out our cool loop invariant */
548               g_assert (i == (group * max_shift_levels + level));
549
550               if (entry[i] == keyval)
551                 {
552                   /* Found a match */
553                   GdkKeymapKey key;
554
555                   key.keycode = keycode;
556                   key.group = group;
557                   key.level = level;
558
559                   g_array_append_val (retval, key);
560
561                   g_assert (XkbKeySymEntry (xkb, keycode, level, group) == 
562                             keyval);
563                 }
564
565               ++level;
566
567               if (level == max_shift_levels)
568                 {
569                   level = 0;
570                   ++group;
571                 }
572
573               ++i;
574             }
575
576           ++keycode;
577         }
578     }
579   else
580 #endif
581     {
582       const KeySym *map = get_keymap (keymap_x11);
583       gint keycode;
584       
585       keycode = keymap_x11->min_keycode;
586       while (keycode <= keymap_x11->max_keycode)
587         {
588           const KeySym *syms = map + (keycode - keymap_x11->min_keycode) * keymap_x11->keysyms_per_keycode;
589           gint i = 0;
590
591           while (i < keymap_x11->keysyms_per_keycode)
592             {
593               if (syms[i] == keyval)
594                 {
595                   /* found a match */
596                   GdkKeymapKey key;
597
598                   key.keycode = keycode;
599
600                   /* The "classic" non-XKB keymap has 2 levels per group */
601                   key.group = i / 2;
602                   key.level = i % 2;
603
604                   g_array_append_val (retval, key);
605                 }
606               
607               ++i;
608             }
609           
610           ++keycode;
611         }
612     }
613
614   if (retval->len > 0)
615     {
616       *keys = (GdkKeymapKey*) retval->data;
617       *n_keys = retval->len;
618     }
619   else
620     {
621       *keys = NULL;
622       *n_keys = 0;
623     }
624       
625   g_array_free (retval, retval->len > 0 ? FALSE : TRUE);
626
627   return *n_keys > 0;
628 }
629
630 /**
631  * gdk_keymap_get_entries_for_keycode:
632  * @keymap: a #GdkKeymap or %NULL to use the default keymap
633  * @hardware_keycode: a keycode
634  * @keys: return location for array of #GdkKeymapKey, or NULL
635  * @keyvals: return location for array of keyvals, or NULL
636  * @n_entries: length of @keys and @keyvals
637  *
638  * Returns the keyvals bound to @hardware_keycode.
639  * The Nth #GdkKeymapKey in @keys is bound to the Nth
640  * keyval in @keyvals. Free the returned arrays with g_free().
641  * When a keycode is pressed by the user, the keyval from
642  * this list of entries is selected by considering the effective
643  * keyboard group and level. See gdk_keymap_translate_keyboard_state().
644  *
645  * Returns: %TRUE if there were any entries
646  **/
647 gboolean
648 gdk_keymap_get_entries_for_keycode (GdkKeymap     *keymap,
649                                     guint          hardware_keycode,
650                                     GdkKeymapKey **keys,
651                                     guint        **keyvals,
652                                     gint          *n_entries)
653 {
654   GdkKeymapX11 *keymap_x11;
655   
656   GArray *key_array;
657   GArray *keyval_array;
658
659   g_return_val_if_fail (keymap == NULL || GDK_IS_KEYMAP (keymap), FALSE);
660   g_return_val_if_fail (n_entries != NULL, FALSE);
661
662   if (!keymap)
663     {
664       keymap = gdk_keymap_get_for_display (gdk_display_get_default ());
665       GDK_NOTE (MULTIHEAD,
666                 g_message ("_multihead : reverting to default display keymap "
667                            "in gdk_keymap_get_entries_for_keycode\n"));
668     }
669
670   keymap_x11 = GDK_KEYMAP_X11 (keymap);
671
672   update_keyrange (keymap_x11);
673
674   if (hardware_keycode < keymap_x11->min_keycode ||
675       hardware_keycode > keymap_x11->max_keycode)
676     {
677       if (keys)
678         *keys = NULL;
679       if (keyvals)
680         *keyvals = NULL;
681
682       *n_entries = 0;
683       return FALSE;
684     }
685   
686   if (keys)
687     key_array = g_array_new (FALSE, FALSE, sizeof (GdkKeymapKey));
688   else
689     key_array = NULL;
690   
691   if (keyvals)
692     keyval_array = g_array_new (FALSE, FALSE, sizeof (guint));
693   else
694     keyval_array = NULL;
695   
696 #ifdef HAVE_XKB
697   if (KEYMAP_USE_XKB (keymap))
698     {
699       /* See sec 15.3.4 in XKB docs */
700
701       XkbDescRec *xkb = get_xkb (keymap_x11);
702       gint max_shift_levels;
703       gint group = 0;
704       gint level = 0;
705       gint total_syms;
706       gint i = 0;
707       KeySym *entry;
708       
709       max_shift_levels = XkbKeyGroupsWidth (xkb, hardware_keycode); /* "key width" */
710       total_syms = XkbKeyNumSyms (xkb, hardware_keycode);
711
712       /* entry is an array with all syms for group 0, all
713        * syms for group 1, etc. and for each group the
714        * shift level syms are in order
715        */
716       entry = XkbKeySymsPtr (xkb, hardware_keycode);
717
718       while (i < total_syms)
719         {          
720           /* check out our cool loop invariant */          
721           g_assert (i == (group * max_shift_levels + level));
722
723           if (key_array)
724             {
725               GdkKeymapKey key;
726               
727               key.keycode = hardware_keycode;
728               key.group = group;
729               key.level = level;
730               
731               g_array_append_val (key_array, key);
732             }
733
734           if (keyval_array)
735             g_array_append_val (keyval_array, entry[i]);
736           
737           ++level;
738           
739           if (level == max_shift_levels)
740             {
741               level = 0;
742               ++group;
743             }
744           
745           ++i;
746         }
747     }
748   else
749 #endif
750     {
751       const KeySym *map = get_keymap (keymap_x11);
752       const KeySym *syms;
753       gint i = 0;
754
755       syms = map + (hardware_keycode - keymap_x11->min_keycode) * keymap_x11->keysyms_per_keycode;
756
757       while (i < keymap_x11->keysyms_per_keycode)
758         {
759           if (key_array)
760             {
761               GdkKeymapKey key;
762           
763               key.keycode = hardware_keycode;
764               
765               /* The "classic" non-XKB keymap has 2 levels per group */
766               key.group = i / 2;
767               key.level = i % 2;
768               
769               g_array_append_val (key_array, key);
770             }
771
772           if (keyval_array)
773             g_array_append_val (keyval_array, syms[i]);
774           
775           ++i;
776         }
777     }
778   
779   if ((key_array && key_array->len > 0) ||
780       (keyval_array && keyval_array->len > 0))
781     {
782       if (keys)
783         *keys = (GdkKeymapKey*) key_array->data;
784
785       if (keyvals)
786         *keyvals = (guint*) keyval_array->data;
787
788       if (key_array)
789         *n_entries = key_array->len;
790       else
791         *n_entries = keyval_array->len;
792     }
793   else
794     {
795       if (keys)
796         *keys = NULL;
797
798       if (keyvals)
799         *keyvals = NULL;
800       
801       *n_entries = 0;
802     }
803
804   if (key_array)
805     g_array_free (key_array, key_array->len > 0 ? FALSE : TRUE);
806   if (keyval_array)
807     g_array_free (keyval_array, keyval_array->len > 0 ? FALSE : TRUE);
808
809   return *n_entries > 0;
810 }
811
812
813 /**
814  * gdk_keymap_lookup_key:
815  * @keymap: a #GdkKeymap or %NULL to use the default keymap
816  * @key: a #GdkKeymapKey with keycode, group, and level initialized
817  * 
818  * Looks up the keyval mapped to a keycode/group/level triplet.
819  * If no keyval is bound to @key, returns 0. For normal user input,
820  * you want to use gdk_keymap_translate_keyboard_state() instead of
821  * this function, since the effective group/level may not be
822  * the same as the current keyboard state.
823  * 
824  * Return value: a keyval, or 0 if none was mapped to the given @key
825  **/
826 guint
827 gdk_keymap_lookup_key (GdkKeymap          *keymap,
828                        const GdkKeymapKey *key)
829 {
830   GdkKeymapX11 *keymap_x11;
831   
832   g_return_val_if_fail (keymap == NULL || GDK_IS_KEYMAP (keymap), 0);
833   g_return_val_if_fail (key != NULL, 0);
834   g_return_val_if_fail (key->group < 4, 0);
835   
836   if (!keymap)
837     {
838       keymap = gdk_keymap_get_for_display (gdk_display_get_default ());
839       GDK_NOTE (MULTIHEAD,
840                 g_message ("_multihead : reverting to default display keymap "
841                            "in gdk_keymap_lookup_key\n"));
842     }
843
844   keymap_x11 = GDK_KEYMAP_X11 (keymap);
845   
846 #ifdef HAVE_XKB
847   if (KEYMAP_USE_XKB (keymap))
848     {
849       XkbDescRec *xkb = get_xkb (keymap_x11);
850       
851       return XkbKeySymEntry (xkb, key->keycode, key->level, key->group);
852     }
853   else
854 #endif
855     {
856       const KeySym *map = get_keymap (keymap_x11);
857       const KeySym *syms = map + (key->keycode - keymap_x11->min_keycode) * keymap_x11->keysyms_per_keycode;
858       return syms [KEYSYM_INDEX (keymap_x11, key->group, key->level)];
859     }
860 }
861
862 #ifdef HAVE_XKB
863 /* This is copied straight from XFree86 Xlib, to:
864  *  - add the group and level return.
865  *  - change the interpretation of mods_rtrn as described
866  *    in the docs for gdk_keymap_translate_keyboard_state()
867  * It's unchanged for ease of diff against the Xlib sources; don't
868  * reformat it.
869  */
870 static Bool
871 MyEnhancedXkbTranslateKeyCode(register XkbDescPtr     xkb,
872                               KeyCode                 key,
873                               register unsigned int   mods,
874                               unsigned int *          mods_rtrn,
875                               KeySym *                keysym_rtrn,
876                               unsigned int *          group_rtrn,
877                               unsigned int *          level_rtrn)
878 {
879     XkbKeyTypeRec *type;
880     int col,nKeyGroups;
881     unsigned preserve,effectiveGroup;
882     KeySym *syms;
883
884     if (mods_rtrn!=NULL)
885         *mods_rtrn = 0;
886
887     nKeyGroups= XkbKeyNumGroups(xkb,key);
888     if ((!XkbKeycodeInRange(xkb,key))||(nKeyGroups==0)) {
889         if (keysym_rtrn!=NULL)
890             *keysym_rtrn = NoSymbol;
891         return False;
892     }
893
894     syms = XkbKeySymsPtr(xkb,key);
895
896     /* find the offset of the effective group */
897     col = 0;
898     effectiveGroup= XkbGroupForCoreState(mods);
899     if ( effectiveGroup>=nKeyGroups ) {
900         unsigned groupInfo= XkbKeyGroupInfo(xkb,key);
901         switch (XkbOutOfRangeGroupAction(groupInfo)) {
902             default:
903                 effectiveGroup %= nKeyGroups;
904                 break;
905             case XkbClampIntoRange:
906                 effectiveGroup = nKeyGroups-1;
907                 break;
908             case XkbRedirectIntoRange:
909                 effectiveGroup = XkbOutOfRangeGroupNumber(groupInfo);
910                 if (effectiveGroup>=nKeyGroups)
911                     effectiveGroup= 0;
912                 break;
913         }
914     }
915     col= effectiveGroup*XkbKeyGroupsWidth(xkb,key);
916     type = XkbKeyKeyType(xkb,key,effectiveGroup);
917
918     preserve= 0;
919     if (type->map) { /* find the column (shift level) within the group */
920         register int i;
921         register XkbKTMapEntryPtr entry;
922         /* ---- Begin section modified for GDK  ---- */
923         int found = 0;
924         
925         for (i=0,entry=type->map;i<type->map_count;i++,entry++) {
926             if (mods_rtrn) {
927                 int bits = 0;
928                 unsigned long tmp = entry->mods.mask;
929                 while (tmp) {
930                     if ((tmp & 1) == 1)
931                         bits++;
932                     tmp >>= 1;
933                 }
934                 /* We always add one-modifiers levels to mods_rtrn since
935                  * they can't wipe out bits in the state unless the
936                  * level would be triggered. But return other modifiers
937                  * 
938                  */
939                 if (bits == 1 || (mods&type->mods.mask)==entry->mods.mask)
940                     *mods_rtrn |= entry->mods.mask;
941             }
942             
943             if (!found&&entry->active&&((mods&type->mods.mask)==entry->mods.mask)) {
944                 col+= entry->level;
945                 if (type->preserve)
946                     preserve= type->preserve[i].mask;
947
948                 if (level_rtrn)
949                   *level_rtrn = entry->level;
950                 
951                 found = 1;
952             }
953         }
954         /* ---- End section modified for GDK ---- */
955     }
956
957     if (keysym_rtrn!=NULL)
958         *keysym_rtrn= syms[col];
959     if (mods_rtrn) {
960         /* ---- Begin section modified for GDK  ---- */
961         *mods_rtrn &= ~preserve;
962         /* ---- End section modified for GDK ---- */
963         
964         /* ---- Begin stuff GDK comments out of the original Xlib version ---- */
965         /* This is commented out because xkb_info is a private struct */
966
967 #if 0
968         /* The Motif VTS doesn't get the help callback called if help
969          * is bound to Shift+<whatever>, and it appears as though it 
970          * is XkbTranslateKeyCode that is causing the problem.  The 
971          * core X version of XTranslateKey always OR's in ShiftMask 
972          * and LockMask for mods_rtrn, so this "fix" keeps this behavior 
973          * and solves the VTS problem.
974          */
975         if ((xkb->dpy)&&(xkb->dpy->xkb_info)&&
976             (xkb->dpy->xkb_info->xlib_ctrls&XkbLC_AlwaysConsumeShiftAndLock)) {            *mods_rtrn|= (ShiftMask|LockMask);
977         }
978 #endif
979         
980         /* ---- End stuff GDK comments out of the original Xlib version ---- */
981     }
982
983     /* ---- Begin stuff GDK adds to the original Xlib version ---- */
984
985     if (group_rtrn)
986       *group_rtrn = effectiveGroup;
987     
988     /* ---- End stuff GDK adds to the original Xlib version ---- */
989     
990     return (syms[col]!=NoSymbol);
991 }
992 #endif /* HAVE_XKB */
993
994 /* Translates from keycode/state to keysymbol using the traditional interpretation
995  * of the keyboard map. See section 12.7 of the Xlib reference manual
996  */
997 static guint
998 translate_keysym (GdkKeymapX11   *keymap_x11,
999                   guint           hardware_keycode,
1000                   gint            group,
1001                   GdkModifierType state,
1002                   guint          *effective_group,
1003                   guint          *effective_level)
1004 {
1005   const KeySym *map = get_keymap (keymap_x11);
1006   const KeySym *syms = map + (hardware_keycode - keymap_x11->min_keycode) * keymap_x11->keysyms_per_keycode;
1007
1008 #define SYM(k,g,l) syms[KEYSYM_INDEX (k,g,l)]
1009
1010   GdkModifierType shift_modifiers;
1011   gint shift_level;
1012   guint tmp_keyval;
1013   gint num_lock_index;
1014
1015   shift_modifiers = GDK_SHIFT_MASK;
1016   if (keymap_x11->lock_keysym == GDK_Shift_Lock)
1017     shift_modifiers |= GDK_LOCK_MASK;
1018
1019   /* Fall back to the first group if the passed in group is empty
1020    */
1021   if (!(SYM (keymap_x11, group, 0) || SYM (keymap_x11, group, 1)) &&
1022       (SYM (keymap_x11, 0, 0) || SYM (keymap_x11, 0, 1)))
1023     group = 0;
1024
1025   /* Hack: On Sun, the Num Lock modifier uses the third element in the
1026    * keysym array, and Mode_Switch does not apply for a keypad key.
1027    */
1028   if (keymap_x11->sun_keypad)
1029     {
1030       num_lock_index = 2;
1031       
1032       if (group != 0)
1033         {
1034           gint i;
1035           
1036           for (i = 0; i < keymap_x11->keysyms_per_keycode; i++)
1037             if (KEYSYM_IS_KEYPAD (SYM (keymap_x11, 0, i)))
1038               group = 0;
1039         }
1040     }
1041   else
1042     num_lock_index = 1;
1043
1044   if ((state & keymap_x11->num_lock_mask) &&
1045       KEYSYM_IS_KEYPAD (SYM (keymap_x11, group, num_lock_index)))
1046     {
1047       /* Shift, Shift_Lock cancel Num_Lock
1048        */
1049       shift_level = (state & shift_modifiers) ? 0 : num_lock_index;
1050       if (!SYM (keymap_x11, group, shift_level) && SYM (keymap_x11, group, 0))
1051         shift_level = 0;
1052
1053        tmp_keyval = SYM (keymap_x11, group, shift_level);
1054     }
1055   else
1056     {
1057       /* Fall back to the the first level if no symbol for the level
1058        * we were passed.
1059        */
1060       shift_level = (state & shift_modifiers) ? 1 : 0;
1061       if (!SYM (keymap_x11, group, shift_level) && SYM (keymap_x11, group, 0))
1062         shift_level = 0;
1063   
1064       tmp_keyval = SYM (keymap_x11, group, shift_level);
1065       
1066       if (keymap_x11->lock_keysym == GDK_Caps_Lock && (state & GDK_LOCK_MASK) != 0)
1067         {
1068           guint upper = gdk_keyval_to_upper (tmp_keyval);
1069           if (upper != tmp_keyval)
1070             tmp_keyval = upper;
1071         }
1072     }
1073
1074   if (effective_group)
1075     *effective_group = group;
1076       
1077   if (effective_level)
1078     *effective_level = shift_level;
1079
1080   return tmp_keyval;
1081   
1082 #undef SYM
1083 }
1084
1085 /**
1086  * gdk_keymap_translate_keyboard_state:
1087  * @keymap: a #GdkKeymap, or %NULL to use the default
1088  * @hardware_keycode: a keycode
1089  * @state: a modifier state 
1090  * @group: active keyboard group
1091  * @keyval: return location for keyval
1092  * @effective_group: return location for effective group
1093  * @level: return location for level
1094  * @consumed_modifiers: return location for modifiers that were used to determine the group or level
1095  * 
1096  *
1097  * Translates the contents of a #GdkEventKey into a keyval, effective
1098  * group, and level. Modifiers that affected the translation and
1099  * are thus unavailable for application use are returned in
1100  * @consumed_modifiers.  See gdk_keyval_get_keys() for an explanation of
1101  * groups and levels.  The @effective_group is the group that was
1102  * actually used for the translation; some keys such as Enter are not
1103  * affected by the active keyboard group. The @level is derived from
1104  * @state. For convenience, #GdkEventKey already contains the translated
1105  * keyval, so this function isn't as useful as you might think.
1106  *
1107  * <note><para>
1108  * @consumed_modifiers gives modifiers that should be masked out
1109  * from @state when comparing this key press to a hot key. For
1110  * instance, on a US keyboard, the <literal>plus</literal>
1111  * symbol is shifted, so when comparing a key press to a
1112  * <literal>&lt;Control&gt;plus</literal> accelerator &lt;Shift&gt; should
1113  * be masked out.
1114  * </para>
1115  * <informalexample><programlisting>
1116  * &sol;* We want to ignore irrelevant modifiers like ScrollLock *&sol;
1117  * #define ALL_ACCELS_MASK (GDK_CONTROL_MASK | GDK_SHIFT_MASK | GDK_MOD1_MASK)
1118  * gdk_keymap_translate_keyboard_state (keymap, event->hardware_keycode,
1119  *                                      event->state, event->group,
1120  *                                      &keyval, NULL, NULL, &consumed);
1121  * if (keyval == GDK_PLUS &&
1122  *     (event->state & ~consumed & ALL_ACCELS_MASK) == GDK_CONTROL_MASK)
1123  *   &sol;* Control was pressed *&sol;
1124  * </programlisting></informalexample>
1125  * <para>
1126  * An older interpretation @consumed_modifiers was that it contained
1127  * all modifiers that might affect the translation of the key;
1128  * this allowed accelerators to be stored with irrelevant consumed
1129  * modifiers, by doing:</para>
1130  * <informalexample><programlisting>
1131  * &sol;* XXX Don't do this XXX *&sol;
1132  * if (keyval == accel_keyval &&
1133  *     (event->state & ~consumed & ALL_ACCELS_MASK) == (accel_mods & ~consumed))
1134  *   &sol;* Accelerator was pressed *&sol;
1135  * </programlisting></informalexample>
1136  * <para>
1137  * However, this did not work if multi-modifier combinations were
1138  * used in the keymap, since, for instance, <literal>&lt;Control&gt;</literal>
1139  * would be masked out even if only <literal>&lt;Control&gt;&lt;Alt&gt;</literal>
1140  * was used in the keymap. To support this usage as well as well as
1141  * possible, all <emphasis>single modifier</emphasis> combinations
1142  * that could affect the key for any combination of modifiers will
1143  * be returned in @consumed_modifiers; multi-modifier combinations
1144  * are returned only when actually found in @state. When you store
1145  * accelerators, you should always store them with consumed modifiers
1146  * removed. Store <literal>&lt;Control&gt;plus</literal>,
1147  * not <literal>&lt;Control&gt;&lt;Shift&gt;plus</literal>,
1148  * </para></note>
1149  * 
1150  * Return value: %TRUE if there was a keyval bound to the keycode/state/group
1151  **/
1152 gboolean
1153 gdk_keymap_translate_keyboard_state (GdkKeymap       *keymap,
1154                                      guint            hardware_keycode,
1155                                      GdkModifierType  state,
1156                                      gint             group,
1157                                      guint           *keyval,
1158                                      gint            *effective_group,
1159                                      gint            *level,
1160                                      GdkModifierType *consumed_modifiers)
1161 {
1162   GdkKeymapX11 *keymap_x11;
1163   KeySym tmp_keyval = NoSymbol;
1164   guint tmp_modifiers;
1165
1166   g_return_val_if_fail (keymap == NULL || GDK_IS_KEYMAP (keymap), FALSE);
1167   g_return_val_if_fail (group < 4, FALSE);
1168   
1169   keymap_x11 = GDK_KEYMAP_X11 (keymap);
1170
1171   if (keyval)
1172     *keyval = NoSymbol;
1173   if (effective_group)
1174     *effective_group = 0;
1175   if (level)
1176     *level = 0;
1177   if (consumed_modifiers)
1178     *consumed_modifiers = 0;
1179
1180   update_keyrange (keymap_x11);
1181   
1182   if (hardware_keycode < keymap_x11->min_keycode ||
1183       hardware_keycode > keymap_x11->max_keycode)
1184     return FALSE;
1185   
1186 #ifdef HAVE_XKB
1187   if (KEYMAP_USE_XKB (keymap))
1188     {
1189       XkbDescRec *xkb = get_xkb (keymap_x11);
1190
1191       /* replace bits 13 and 14 with the provided group */
1192       state &= ~(1 << 13 | 1 << 14);
1193       state |= group << 13;
1194       
1195       MyEnhancedXkbTranslateKeyCode (xkb,
1196                                      hardware_keycode,
1197                                      state,
1198                                      &tmp_modifiers,
1199                                      &tmp_keyval,
1200                                      effective_group,
1201                                      level);
1202
1203       if (state & ~tmp_modifiers & LockMask)
1204         tmp_keyval = gdk_keyval_to_upper (tmp_keyval);
1205
1206       /* We need to augment the consumed modifiers with LockMask, since
1207        * we handle that ourselves, and also with the group bits
1208        */
1209       tmp_modifiers |= LockMask | 1 << 13 | 1 << 14;
1210     }
1211   else
1212 #endif
1213     {
1214       GdkModifierType bit;
1215       
1216       tmp_modifiers = 0;
1217
1218       /* We see what modifiers matter by trying the translation with
1219        * and without each possible modifier
1220        */
1221       for (bit = GDK_SHIFT_MASK; bit < GDK_BUTTON1_MASK; bit <<= 1)
1222         {
1223           /* Handling of the group here is a bit funky; a traditional
1224            * X keyboard map can have more than two groups, but no way
1225            * of accessing the extra groups is defined. We allow a
1226            * caller to pass in any group to this function, but we 
1227            * only can represent switching between group 0 and 1 in
1228            * consumed modifiers.
1229            */
1230           if (translate_keysym (keymap_x11, hardware_keycode,
1231                                 (bit == keymap_x11->group_switch_mask) ? 0 : group,
1232                                 state & ~bit,
1233                                 NULL, NULL) !=
1234               translate_keysym (keymap_x11, hardware_keycode,
1235                                 (bit == keymap_x11->group_switch_mask) ? 1 : group,
1236                                 state | bit,
1237                                 NULL, NULL))
1238             tmp_modifiers |= bit;
1239         }
1240       
1241       tmp_keyval = translate_keysym (keymap_x11, hardware_keycode,
1242                                      group, state,
1243                                      level, effective_group);
1244     }
1245
1246   if (consumed_modifiers)
1247     *consumed_modifiers = tmp_modifiers;
1248                                 
1249   if (keyval)
1250     *keyval = tmp_keyval;
1251
1252   return tmp_keyval != NoSymbol;
1253 }
1254
1255
1256 /* Key handling not part of the keymap */
1257
1258 gchar*
1259 gdk_keyval_name (guint        keyval)
1260 {
1261   switch (keyval)
1262     {
1263     case GDK_Page_Up:
1264       return "Page_Up";
1265     case GDK_Page_Down:
1266       return "Page_Down";
1267     case GDK_KP_Page_Up:
1268       return "KP_Page_Up";
1269     case GDK_KP_Page_Down:
1270       return "KP_Page_Down";
1271     }
1272   
1273   return XKeysymToString (keyval);
1274 }
1275
1276 guint
1277 gdk_keyval_from_name (const gchar *keyval_name)
1278 {
1279   g_return_val_if_fail (keyval_name != NULL, 0);
1280   
1281   return XStringToKeysym (keyval_name);
1282 }
1283
1284 #ifdef HAVE_XCONVERTCASE
1285 void
1286 gdk_keyval_convert_case (guint symbol,
1287                          guint *lower,
1288                          guint *upper)
1289 {
1290   KeySym xlower = 0;
1291   KeySym xupper = 0;
1292
1293   /* Check for directly encoded 24-bit UCS characters: */
1294   if ((symbol & 0xff000000) == 0x01000000)
1295     {
1296       if (lower)
1297         *lower = gdk_unicode_to_keyval (g_unichar_tolower (symbol & 0x00ffffff));
1298       if (upper)
1299         *upper = gdk_unicode_to_keyval (g_unichar_toupper (symbol & 0x00ffffff));
1300       return;
1301     }
1302   
1303   if (symbol)
1304     XConvertCase (symbol, &xlower, &xupper);
1305
1306   if (lower)
1307     *lower = xlower;
1308   if (upper)
1309     *upper = xupper;
1310 }  
1311 #endif /* HAVE_XCONVERTCASE */
1312
1313 gint
1314 _gdk_x11_get_group_for_state (GdkDisplay      *display,
1315                               GdkModifierType  state)
1316 {
1317   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (display);
1318   
1319 #ifdef HAVE_XKB
1320   if (display_x11->use_xkb)
1321     {
1322       return XkbGroupForCoreState (state);
1323     }
1324   else
1325 #endif
1326     {
1327       GdkKeymapX11 *keymap_impl = GDK_KEYMAP_X11 (gdk_keymap_get_for_display (display));
1328       update_keymaps (keymap_impl);
1329       return (state & keymap_impl->group_switch_mask) ? 1 : 0;
1330     }
1331 }