]> Pileus Git - ~andy/gtk/blob - gdk/x11/gdkkeys-x11.c
Make gdk_keymap_translate_keyboard_state() handle NULL keymaps. (#139715,
[~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 <config.h>
28
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <unistd.h>
33 #include <limits.h>
34 #include <errno.h>
35
36 #include "gdk.h"
37 #include "gdkx.h"
38
39 #include "gdkprivate-x11.h"
40 #include "gdkinternals.h"
41 #include "gdkdisplay-x11.h"
42 #include "gdkkeysyms.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 #define GET_EFFECTIVE_KEYMAP(keymap) get_effective_keymap ((keymap), G_STRFUNC)
382
383 GdkKeymap *
384 get_effective_keymap (GdkKeymap  *keymap,
385                       const char *function)
386 {
387   if (!keymap)
388     {
389       GDK_NOTE (MULTIHEAD,
390                 g_message ("reverting to default display keymap in %s",
391                            function));
392       return gdk_keymap_get_default ();
393     }
394
395   return keymap;
396 }
397
398 #if HAVE_XKB
399 static PangoDirection
400 get_direction (GdkKeymapX11 *keymap_x11)
401 {
402   XkbDescRec *xkb = get_xkb (keymap_x11);
403   const char *name;
404   XkbStateRec state_rec;
405   PangoDirection result;
406
407   GdkDisplay *display = GDK_KEYMAP (keymap_x11)->display;
408
409   XkbGetState (GDK_DISPLAY_XDISPLAY (display), XkbUseCoreKbd, &state_rec);
410   
411   if (xkb->names->groups[state_rec.locked_group] == None)
412     result = PANGO_DIRECTION_LTR;
413   else
414     {
415       name = gdk_x11_get_xatom_name_for_display (display, xkb->names->groups[state_rec.locked_group]);
416
417       if (g_ascii_strcasecmp (name, "arabic") == 0 ||
418           g_ascii_strcasecmp (name, "hebrew") == 0 ||
419           g_ascii_strcasecmp (name, "israelian") == 0)
420         result = PANGO_DIRECTION_RTL;
421       else
422         result = PANGO_DIRECTION_LTR;
423     }
424     
425   return result;
426 }
427
428 void
429 _gdk_keymap_state_changed (GdkDisplay *display)
430 {
431   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (display);
432   
433   if (display_x11->keymap)
434     {
435       GdkKeymapX11 *keymap_x11 = GDK_KEYMAP_X11 (display_x11->keymap);
436       
437       PangoDirection new_direction = get_direction (keymap_x11);
438       
439       if (!keymap_x11->have_direction || new_direction != keymap_x11->current_direction)
440         {
441           keymap_x11->have_direction = TRUE;
442           keymap_x11->current_direction = new_direction;
443           g_signal_emit_by_name (keymap_x11, "direction_changed");
444         }
445     }
446 }
447
448 #endif /* HAVE_XKB */
449
450 void
451 _gdk_keymap_keys_changed (GdkDisplay *display)
452 {
453   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (display);
454   
455   ++display_x11->keymap_serial;
456   
457   if (display_x11->keymap)
458     g_signal_emit_by_name (display_x11->keymap, "keys_changed", 0);
459 }
460
461 PangoDirection
462 gdk_keymap_get_direction (GdkKeymap *keymap)
463 {
464   keymap = GET_EFFECTIVE_KEYMAP (keymap);
465   
466 #if HAVE_XKB
467   if (KEYMAP_USE_XKB (keymap))
468     {
469       GdkKeymapX11 *keymap_x11 = GDK_KEYMAP_X11 (keymap);
470       
471       if (!keymap_x11->have_direction)
472         {
473           keymap_x11->current_direction = get_direction (keymap_x11);
474           keymap_x11->have_direction = TRUE;
475         }
476   
477       return keymap_x11->current_direction;
478     }
479   else
480 #endif /* HAVE_XKB */
481     return PANGO_DIRECTION_LTR;
482 }
483
484 /**
485  * gdk_keymap_get_entries_for_keyval:
486  * @keymap: a #GdkKeymap, or %NULL to use the default keymap
487  * @keyval: a keyval, such as %GDK_a, %GDK_Up, %GDK_Return, etc.
488  * @keys: return location for an array of #GdkKeymapKey
489  * @n_keys: return location for number of elements in returned array
490  * 
491  * Obtains a list of keycode/group/level combinations that will
492  * generate @keyval. Groups and levels are two kinds of keyboard mode;
493  * in general, the level determines whether the top or bottom symbol
494  * on a key is used, and the group determines whether the left or
495  * right symbol is used. On US keyboards, the shift key changes the
496  * keyboard level, and there are no groups. A group switch key might
497  * convert a keyboard between Hebrew to English modes, for example.
498  * #GdkEventKey contains a %group field that indicates the active
499  * keyboard group. The level is computed from the modifier mask.
500  * The returned array should be freed
501  * with g_free().
502  *
503  * Return value: %TRUE if keys were found and returned
504  **/
505 gboolean
506 gdk_keymap_get_entries_for_keyval (GdkKeymap     *keymap,
507                                    guint          keyval,
508                                    GdkKeymapKey **keys,
509                                    gint          *n_keys)
510 {
511   GArray *retval;
512   GdkKeymapX11 *keymap_x11;
513
514   g_return_val_if_fail (keymap == NULL || GDK_IS_KEYMAP (keymap), FALSE);
515   g_return_val_if_fail (keys != NULL, FALSE);
516   g_return_val_if_fail (n_keys != NULL, FALSE);
517   g_return_val_if_fail (keyval != 0, FALSE);
518
519   keymap = GET_EFFECTIVE_KEYMAP (keymap);
520   keymap_x11 = GDK_KEYMAP_X11 (keymap);
521   
522   retval = g_array_new (FALSE, FALSE, sizeof (GdkKeymapKey));
523
524 #ifdef HAVE_XKB
525   if (KEYMAP_USE_XKB (keymap))
526     {
527       /* See sec 15.3.4 in XKB docs */
528
529       XkbDescRec *xkb = get_xkb (keymap_x11);
530       gint keycode;
531       
532       keycode = keymap_x11->min_keycode;
533
534       while (keycode <= keymap_x11->max_keycode)
535         {
536           gint max_shift_levels = XkbKeyGroupsWidth (xkb, keycode); /* "key width" */
537           gint group = 0;
538           gint level = 0;
539           gint total_syms = XkbKeyNumSyms (xkb, keycode);
540           gint i = 0;
541           KeySym *entry;
542
543           /* entry is an array with all syms for group 0, all
544            * syms for group 1, etc. and for each group the
545            * shift level syms are in order
546            */
547           entry = XkbKeySymsPtr (xkb, keycode);
548
549           while (i < total_syms)
550             {
551               /* check out our cool loop invariant */
552               g_assert (i == (group * max_shift_levels + level));
553
554               if (entry[i] == keyval)
555                 {
556                   /* Found a match */
557                   GdkKeymapKey key;
558
559                   key.keycode = keycode;
560                   key.group = group;
561                   key.level = level;
562
563                   g_array_append_val (retval, key);
564
565                   g_assert (XkbKeySymEntry (xkb, keycode, level, group) == 
566                             keyval);
567                 }
568
569               ++level;
570
571               if (level == max_shift_levels)
572                 {
573                   level = 0;
574                   ++group;
575                 }
576
577               ++i;
578             }
579
580           ++keycode;
581         }
582     }
583   else
584 #endif
585     {
586       const KeySym *map = get_keymap (keymap_x11);
587       gint keycode;
588       
589       keycode = keymap_x11->min_keycode;
590       while (keycode <= keymap_x11->max_keycode)
591         {
592           const KeySym *syms = map + (keycode - keymap_x11->min_keycode) * keymap_x11->keysyms_per_keycode;
593           gint i = 0;
594
595           while (i < keymap_x11->keysyms_per_keycode)
596             {
597               if (syms[i] == keyval)
598                 {
599                   /* found a match */
600                   GdkKeymapKey key;
601
602                   key.keycode = keycode;
603
604                   /* The "classic" non-XKB keymap has 2 levels per group */
605                   key.group = i / 2;
606                   key.level = i % 2;
607
608                   g_array_append_val (retval, key);
609                 }
610               
611               ++i;
612             }
613           
614           ++keycode;
615         }
616     }
617
618   if (retval->len > 0)
619     {
620       *keys = (GdkKeymapKey*) retval->data;
621       *n_keys = retval->len;
622     }
623   else
624     {
625       *keys = NULL;
626       *n_keys = 0;
627     }
628       
629   g_array_free (retval, retval->len > 0 ? FALSE : TRUE);
630
631   return *n_keys > 0;
632 }
633
634 /**
635  * gdk_keymap_get_entries_for_keycode:
636  * @keymap: a #GdkKeymap or %NULL to use the default keymap
637  * @hardware_keycode: a keycode
638  * @keys: return location for array of #GdkKeymapKey, or NULL
639  * @keyvals: return location for array of keyvals, or NULL
640  * @n_entries: length of @keys and @keyvals
641  *
642  * Returns the keyvals bound to @hardware_keycode.
643  * The Nth #GdkKeymapKey in @keys is bound to the Nth
644  * keyval in @keyvals. Free the returned arrays with g_free().
645  * When a keycode is pressed by the user, the keyval from
646  * this list of entries is selected by considering the effective
647  * keyboard group and level. See gdk_keymap_translate_keyboard_state().
648  *
649  * Returns: %TRUE if there were any entries
650  **/
651 gboolean
652 gdk_keymap_get_entries_for_keycode (GdkKeymap     *keymap,
653                                     guint          hardware_keycode,
654                                     GdkKeymapKey **keys,
655                                     guint        **keyvals,
656                                     gint          *n_entries)
657 {
658   GdkKeymapX11 *keymap_x11;
659   
660   GArray *key_array;
661   GArray *keyval_array;
662
663   g_return_val_if_fail (keymap == NULL || GDK_IS_KEYMAP (keymap), FALSE);
664   g_return_val_if_fail (n_entries != NULL, FALSE);
665
666   keymap = GET_EFFECTIVE_KEYMAP (keymap);
667   keymap_x11 = GDK_KEYMAP_X11 (keymap);
668
669   update_keyrange (keymap_x11);
670
671   if (hardware_keycode < keymap_x11->min_keycode ||
672       hardware_keycode > keymap_x11->max_keycode)
673     {
674       if (keys)
675         *keys = NULL;
676       if (keyvals)
677         *keyvals = NULL;
678
679       *n_entries = 0;
680       return FALSE;
681     }
682   
683   if (keys)
684     key_array = g_array_new (FALSE, FALSE, sizeof (GdkKeymapKey));
685   else
686     key_array = NULL;
687   
688   if (keyvals)
689     keyval_array = g_array_new (FALSE, FALSE, sizeof (guint));
690   else
691     keyval_array = NULL;
692   
693 #ifdef HAVE_XKB
694   if (KEYMAP_USE_XKB (keymap))
695     {
696       /* See sec 15.3.4 in XKB docs */
697
698       XkbDescRec *xkb = get_xkb (keymap_x11);
699       gint max_shift_levels;
700       gint group = 0;
701       gint level = 0;
702       gint total_syms;
703       gint i = 0;
704       KeySym *entry;
705       
706       max_shift_levels = XkbKeyGroupsWidth (xkb, hardware_keycode); /* "key width" */
707       total_syms = XkbKeyNumSyms (xkb, hardware_keycode);
708
709       /* entry is an array with all syms for group 0, all
710        * syms for group 1, etc. and for each group the
711        * shift level syms are in order
712        */
713       entry = XkbKeySymsPtr (xkb, hardware_keycode);
714
715       while (i < total_syms)
716         {          
717           /* check out our cool loop invariant */          
718           g_assert (i == (group * max_shift_levels + level));
719
720           if (key_array)
721             {
722               GdkKeymapKey key;
723               
724               key.keycode = hardware_keycode;
725               key.group = group;
726               key.level = level;
727               
728               g_array_append_val (key_array, key);
729             }
730
731           if (keyval_array)
732             g_array_append_val (keyval_array, entry[i]);
733           
734           ++level;
735           
736           if (level == max_shift_levels)
737             {
738               level = 0;
739               ++group;
740             }
741           
742           ++i;
743         }
744     }
745   else
746 #endif
747     {
748       const KeySym *map = get_keymap (keymap_x11);
749       const KeySym *syms;
750       gint i = 0;
751
752       syms = map + (hardware_keycode - keymap_x11->min_keycode) * keymap_x11->keysyms_per_keycode;
753
754       while (i < keymap_x11->keysyms_per_keycode)
755         {
756           if (key_array)
757             {
758               GdkKeymapKey key;
759           
760               key.keycode = hardware_keycode;
761               
762               /* The "classic" non-XKB keymap has 2 levels per group */
763               key.group = i / 2;
764               key.level = i % 2;
765               
766               g_array_append_val (key_array, key);
767             }
768
769           if (keyval_array)
770             g_array_append_val (keyval_array, syms[i]);
771           
772           ++i;
773         }
774     }
775   
776   if ((key_array && key_array->len > 0) ||
777       (keyval_array && keyval_array->len > 0))
778     {
779       if (keys)
780         *keys = (GdkKeymapKey*) key_array->data;
781
782       if (keyvals)
783         *keyvals = (guint*) keyval_array->data;
784
785       if (key_array)
786         *n_entries = key_array->len;
787       else
788         *n_entries = keyval_array->len;
789     }
790   else
791     {
792       if (keys)
793         *keys = NULL;
794
795       if (keyvals)
796         *keyvals = NULL;
797       
798       *n_entries = 0;
799     }
800
801   if (key_array)
802     g_array_free (key_array, key_array->len > 0 ? FALSE : TRUE);
803   if (keyval_array)
804     g_array_free (keyval_array, keyval_array->len > 0 ? FALSE : TRUE);
805
806   return *n_entries > 0;
807 }
808
809
810 /**
811  * gdk_keymap_lookup_key:
812  * @keymap: a #GdkKeymap or %NULL to use the default keymap
813  * @key: a #GdkKeymapKey with keycode, group, and level initialized
814  * 
815  * Looks up the keyval mapped to a keycode/group/level triplet.
816  * If no keyval is bound to @key, returns 0. For normal user input,
817  * you want to use gdk_keymap_translate_keyboard_state() instead of
818  * this function, since the effective group/level may not be
819  * the same as the current keyboard state.
820  * 
821  * Return value: a keyval, or 0 if none was mapped to the given @key
822  **/
823 guint
824 gdk_keymap_lookup_key (GdkKeymap          *keymap,
825                        const GdkKeymapKey *key)
826 {
827   GdkKeymapX11 *keymap_x11;
828   
829   g_return_val_if_fail (keymap == NULL || GDK_IS_KEYMAP (keymap), 0);
830   g_return_val_if_fail (key != NULL, 0);
831   g_return_val_if_fail (key->group < 4, 0);
832
833   keymap = GET_EFFECTIVE_KEYMAP (keymap);
834   keymap_x11 = GDK_KEYMAP_X11 (keymap);
835   
836 #ifdef HAVE_XKB
837   if (KEYMAP_USE_XKB (keymap))
838     {
839       XkbDescRec *xkb = get_xkb (keymap_x11);
840       
841       return XkbKeySymEntry (xkb, key->keycode, key->level, key->group);
842     }
843   else
844 #endif
845     {
846       const KeySym *map = get_keymap (keymap_x11);
847       const KeySym *syms = map + (key->keycode - keymap_x11->min_keycode) * keymap_x11->keysyms_per_keycode;
848       return syms [KEYSYM_INDEX (keymap_x11, key->group, key->level)];
849     }
850 }
851
852 #ifdef HAVE_XKB
853 /* This is copied straight from XFree86 Xlib, to:
854  *  - add the group and level return.
855  *  - change the interpretation of mods_rtrn as described
856  *    in the docs for gdk_keymap_translate_keyboard_state()
857  * It's unchanged for ease of diff against the Xlib sources; don't
858  * reformat it.
859  */
860 static Bool
861 MyEnhancedXkbTranslateKeyCode(register XkbDescPtr     xkb,
862                               KeyCode                 key,
863                               register unsigned int   mods,
864                               unsigned int *          mods_rtrn,
865                               KeySym *                keysym_rtrn,
866                               unsigned int *          group_rtrn,
867                               unsigned int *          level_rtrn)
868 {
869     XkbKeyTypeRec *type;
870     int col,nKeyGroups;
871     unsigned preserve,effectiveGroup;
872     KeySym *syms;
873
874     if (mods_rtrn!=NULL)
875         *mods_rtrn = 0;
876
877     nKeyGroups= XkbKeyNumGroups(xkb,key);
878     if ((!XkbKeycodeInRange(xkb,key))||(nKeyGroups==0)) {
879         if (keysym_rtrn!=NULL)
880             *keysym_rtrn = NoSymbol;
881         return False;
882     }
883
884     syms = XkbKeySymsPtr(xkb,key);
885
886     /* find the offset of the effective group */
887     col = 0;
888     effectiveGroup= XkbGroupForCoreState(mods);
889     if ( effectiveGroup>=nKeyGroups ) {
890         unsigned groupInfo= XkbKeyGroupInfo(xkb,key);
891         switch (XkbOutOfRangeGroupAction(groupInfo)) {
892             default:
893                 effectiveGroup %= nKeyGroups;
894                 break;
895             case XkbClampIntoRange:
896                 effectiveGroup = nKeyGroups-1;
897                 break;
898             case XkbRedirectIntoRange:
899                 effectiveGroup = XkbOutOfRangeGroupNumber(groupInfo);
900                 if (effectiveGroup>=nKeyGroups)
901                     effectiveGroup= 0;
902                 break;
903         }
904     }
905     col= effectiveGroup*XkbKeyGroupsWidth(xkb,key);
906     type = XkbKeyKeyType(xkb,key,effectiveGroup);
907
908     preserve= 0;
909     if (type->map) { /* find the column (shift level) within the group */
910         register int i;
911         register XkbKTMapEntryPtr entry;
912         /* ---- Begin section modified for GDK  ---- */
913         int found = 0;
914         
915         for (i=0,entry=type->map;i<type->map_count;i++,entry++) {
916             if (mods_rtrn) {
917                 int bits = 0;
918                 unsigned long tmp = entry->mods.mask;
919                 while (tmp) {
920                     if ((tmp & 1) == 1)
921                         bits++;
922                     tmp >>= 1;
923                 }
924                 /* We always add one-modifiers levels to mods_rtrn since
925                  * they can't wipe out bits in the state unless the
926                  * level would be triggered. But return other modifiers
927                  * 
928                  */
929                 if (bits == 1 || (mods&type->mods.mask)==entry->mods.mask)
930                     *mods_rtrn |= entry->mods.mask;
931             }
932             
933             if (!found&&entry->active&&((mods&type->mods.mask)==entry->mods.mask)) {
934                 col+= entry->level;
935                 if (type->preserve)
936                     preserve= type->preserve[i].mask;
937
938                 if (level_rtrn)
939                   *level_rtrn = entry->level;
940                 
941                 found = 1;
942             }
943         }
944         /* ---- End section modified for GDK ---- */
945     }
946
947     if (keysym_rtrn!=NULL)
948         *keysym_rtrn= syms[col];
949     if (mods_rtrn) {
950         /* ---- Begin section modified for GDK  ---- */
951         *mods_rtrn &= ~preserve;
952         /* ---- End section modified for GDK ---- */
953         
954         /* ---- Begin stuff GDK comments out of the original Xlib version ---- */
955         /* This is commented out because xkb_info is a private struct */
956
957 #if 0
958         /* The Motif VTS doesn't get the help callback called if help
959          * is bound to Shift+<whatever>, and it appears as though it 
960          * is XkbTranslateKeyCode that is causing the problem.  The 
961          * core X version of XTranslateKey always OR's in ShiftMask 
962          * and LockMask for mods_rtrn, so this "fix" keeps this behavior 
963          * and solves the VTS problem.
964          */
965         if ((xkb->dpy)&&(xkb->dpy->xkb_info)&&
966             (xkb->dpy->xkb_info->xlib_ctrls&XkbLC_AlwaysConsumeShiftAndLock)) {            *mods_rtrn|= (ShiftMask|LockMask);
967         }
968 #endif
969         
970         /* ---- End stuff GDK comments out of the original Xlib version ---- */
971     }
972
973     /* ---- Begin stuff GDK adds to the original Xlib version ---- */
974
975     if (group_rtrn)
976       *group_rtrn = effectiveGroup;
977     
978     /* ---- End stuff GDK adds to the original Xlib version ---- */
979     
980     return (syms[col]!=NoSymbol);
981 }
982 #endif /* HAVE_XKB */
983
984 /* Translates from keycode/state to keysymbol using the traditional interpretation
985  * of the keyboard map. See section 12.7 of the Xlib reference manual
986  */
987 static guint
988 translate_keysym (GdkKeymapX11   *keymap_x11,
989                   guint           hardware_keycode,
990                   gint            group,
991                   GdkModifierType state,
992                   guint          *effective_group,
993                   guint          *effective_level)
994 {
995   const KeySym *map = get_keymap (keymap_x11);
996   const KeySym *syms = map + (hardware_keycode - keymap_x11->min_keycode) * keymap_x11->keysyms_per_keycode;
997
998 #define SYM(k,g,l) syms[KEYSYM_INDEX (k,g,l)]
999
1000   GdkModifierType shift_modifiers;
1001   gint shift_level;
1002   guint tmp_keyval;
1003   gint num_lock_index;
1004
1005   shift_modifiers = GDK_SHIFT_MASK;
1006   if (keymap_x11->lock_keysym == GDK_Shift_Lock)
1007     shift_modifiers |= GDK_LOCK_MASK;
1008
1009   /* Fall back to the first group if the passed in group is empty
1010    */
1011   if (!(SYM (keymap_x11, group, 0) || SYM (keymap_x11, group, 1)) &&
1012       (SYM (keymap_x11, 0, 0) || SYM (keymap_x11, 0, 1)))
1013     group = 0;
1014
1015   /* Hack: On Sun, the Num Lock modifier uses the third element in the
1016    * keysym array, and Mode_Switch does not apply for a keypad key.
1017    */
1018   if (keymap_x11->sun_keypad)
1019     {
1020       num_lock_index = 2;
1021       
1022       if (group != 0)
1023         {
1024           gint i;
1025           
1026           for (i = 0; i < keymap_x11->keysyms_per_keycode; i++)
1027             if (KEYSYM_IS_KEYPAD (SYM (keymap_x11, 0, i)))
1028               group = 0;
1029         }
1030     }
1031   else
1032     num_lock_index = 1;
1033
1034   if ((state & keymap_x11->num_lock_mask) &&
1035       KEYSYM_IS_KEYPAD (SYM (keymap_x11, group, num_lock_index)))
1036     {
1037       /* Shift, Shift_Lock cancel Num_Lock
1038        */
1039       shift_level = (state & shift_modifiers) ? 0 : num_lock_index;
1040       if (!SYM (keymap_x11, group, shift_level) && SYM (keymap_x11, group, 0))
1041         shift_level = 0;
1042
1043        tmp_keyval = SYM (keymap_x11, group, shift_level);
1044     }
1045   else
1046     {
1047       /* Fall back to the the first level if no symbol for the level
1048        * we were passed.
1049        */
1050       shift_level = (state & shift_modifiers) ? 1 : 0;
1051       if (!SYM (keymap_x11, group, shift_level) && SYM (keymap_x11, group, 0))
1052         shift_level = 0;
1053   
1054       tmp_keyval = SYM (keymap_x11, group, shift_level);
1055       
1056       if (keymap_x11->lock_keysym == GDK_Caps_Lock && (state & GDK_LOCK_MASK) != 0)
1057         {
1058           guint upper = gdk_keyval_to_upper (tmp_keyval);
1059           if (upper != tmp_keyval)
1060             tmp_keyval = upper;
1061         }
1062     }
1063
1064   if (effective_group)
1065     *effective_group = group;
1066       
1067   if (effective_level)
1068     *effective_level = shift_level;
1069
1070   return tmp_keyval;
1071   
1072 #undef SYM
1073 }
1074
1075 /**
1076  * gdk_keymap_translate_keyboard_state:
1077  * @keymap: a #GdkKeymap, or %NULL to use the default
1078  * @hardware_keycode: a keycode
1079  * @state: a modifier state 
1080  * @group: active keyboard group
1081  * @keyval: return location for keyval
1082  * @effective_group: return location for effective group
1083  * @level: return location for level
1084  * @consumed_modifiers: return location for modifiers that were used to determine the group or level
1085  * 
1086  *
1087  * Translates the contents of a #GdkEventKey into a keyval, effective
1088  * group, and level. Modifiers that affected the translation and
1089  * are thus unavailable for application use are returned in
1090  * @consumed_modifiers.  See gdk_keyval_get_keys() for an explanation of
1091  * groups and levels.  The @effective_group is the group that was
1092  * actually used for the translation; some keys such as Enter are not
1093  * affected by the active keyboard group. The @level is derived from
1094  * @state. For convenience, #GdkEventKey already contains the translated
1095  * keyval, so this function isn't as useful as you might think.
1096  *
1097  * <note><para>
1098  * @consumed_modifiers gives modifiers that should be masked out
1099  * from @state when comparing this key press to a hot key. For
1100  * instance, on a US keyboard, the <literal>plus</literal>
1101  * symbol is shifted, so when comparing a key press to a
1102  * <literal>&lt;Control&gt;plus</literal> accelerator &lt;Shift&gt; should
1103  * be masked out.
1104  * </para>
1105  * <informalexample><programlisting>
1106  * &sol;* We want to ignore irrelevant modifiers like ScrollLock *&sol;
1107  * &num;define ALL_ACCELS_MASK (GDK_CONTROL_MASK | GDK_SHIFT_MASK | GDK_MOD1_MASK)
1108  * gdk_keymap_translate_keyboard_state (keymap, event->hardware_keycode,
1109  *                                      event->state, event->group,
1110  *                                      &amp;keyval, NULL, NULL, &amp;consumed);
1111  * if (keyval == GDK_PLUS &&
1112  *     (event->state &amp; ~consumed &amp; ALL_ACCELS_MASK) == GDK_CONTROL_MASK)
1113  *   &sol;* Control was pressed *&sol;
1114  * </programlisting></informalexample>
1115  * <para>
1116  * An older interpretation @consumed_modifiers was that it contained
1117  * all modifiers that might affect the translation of the key;
1118  * this allowed accelerators to be stored with irrelevant consumed
1119  * modifiers, by doing:</para>
1120  * <informalexample><programlisting>
1121  * &sol;* XXX Don't do this XXX *&sol;
1122  * if (keyval == accel_keyval &&
1123  *     (event->state &amp; ~consumed &amp; ALL_ACCELS_MASK) == (accel_mods &amp; ~consumed))
1124  *   &sol;* Accelerator was pressed *&sol;
1125  * </programlisting></informalexample>
1126  * <para>
1127  * However, this did not work if multi-modifier combinations were
1128  * used in the keymap, since, for instance, <literal>&lt;Control&gt;</literal>
1129  * would be masked out even if only <literal>&lt;Control&gt;&lt;Alt&gt;</literal>
1130  * was used in the keymap. To support this usage as well as well as
1131  * possible, all <emphasis>single modifier</emphasis> combinations
1132  * that could affect the key for any combination of modifiers will
1133  * be returned in @consumed_modifiers; multi-modifier combinations
1134  * are returned only when actually found in @state. When you store
1135  * accelerators, you should always store them with consumed modifiers
1136  * removed. Store <literal>&lt;Control&gt;plus</literal>,
1137  * not <literal>&lt;Control&gt;&lt;Shift&gt;plus</literal>,
1138  * </para></note>
1139  * 
1140  * Return value: %TRUE if there was a keyval bound to the keycode/state/group
1141  **/
1142 gboolean
1143 gdk_keymap_translate_keyboard_state (GdkKeymap       *keymap,
1144                                      guint            hardware_keycode,
1145                                      GdkModifierType  state,
1146                                      gint             group,
1147                                      guint           *keyval,
1148                                      gint            *effective_group,
1149                                      gint            *level,
1150                                      GdkModifierType *consumed_modifiers)
1151 {
1152   GdkKeymapX11 *keymap_x11;
1153   KeySym tmp_keyval = NoSymbol;
1154   guint tmp_modifiers;
1155
1156   g_return_val_if_fail (keymap == NULL || GDK_IS_KEYMAP (keymap), FALSE);
1157   g_return_val_if_fail (group < 4, FALSE);
1158
1159   keymap = GET_EFFECTIVE_KEYMAP (keymap);  
1160   keymap_x11 = GDK_KEYMAP_X11 (keymap);
1161
1162   if (keyval)
1163     *keyval = NoSymbol;
1164   if (effective_group)
1165     *effective_group = 0;
1166   if (level)
1167     *level = 0;
1168   if (consumed_modifiers)
1169     *consumed_modifiers = 0;
1170
1171   update_keyrange (keymap_x11);
1172   
1173   if (hardware_keycode < keymap_x11->min_keycode ||
1174       hardware_keycode > keymap_x11->max_keycode)
1175     return FALSE;
1176   
1177 #ifdef HAVE_XKB
1178   if (KEYMAP_USE_XKB (keymap))
1179     {
1180       XkbDescRec *xkb = get_xkb (keymap_x11);
1181
1182       /* replace bits 13 and 14 with the provided group */
1183       state &= ~(1 << 13 | 1 << 14);
1184       state |= group << 13;
1185       
1186       MyEnhancedXkbTranslateKeyCode (xkb,
1187                                      hardware_keycode,
1188                                      state,
1189                                      &tmp_modifiers,
1190                                      &tmp_keyval,
1191                                      effective_group,
1192                                      level);
1193
1194       if (state & ~tmp_modifiers & LockMask)
1195         tmp_keyval = gdk_keyval_to_upper (tmp_keyval);
1196
1197       /* We need to augment the consumed modifiers with LockMask, since
1198        * we handle that ourselves, and also with the group bits
1199        */
1200       tmp_modifiers |= LockMask | 1 << 13 | 1 << 14;
1201     }
1202   else
1203 #endif
1204     {
1205       GdkModifierType bit;
1206       
1207       tmp_modifiers = 0;
1208
1209       /* We see what modifiers matter by trying the translation with
1210        * and without each possible modifier
1211        */
1212       for (bit = GDK_SHIFT_MASK; bit < GDK_BUTTON1_MASK; bit <<= 1)
1213         {
1214           /* Handling of the group here is a bit funky; a traditional
1215            * X keyboard map can have more than two groups, but no way
1216            * of accessing the extra groups is defined. We allow a
1217            * caller to pass in any group to this function, but we 
1218            * only can represent switching between group 0 and 1 in
1219            * consumed modifiers.
1220            */
1221           if (translate_keysym (keymap_x11, hardware_keycode,
1222                                 (bit == keymap_x11->group_switch_mask) ? 0 : group,
1223                                 state & ~bit,
1224                                 NULL, NULL) !=
1225               translate_keysym (keymap_x11, hardware_keycode,
1226                                 (bit == keymap_x11->group_switch_mask) ? 1 : group,
1227                                 state | bit,
1228                                 NULL, NULL))
1229             tmp_modifiers |= bit;
1230         }
1231       
1232       tmp_keyval = translate_keysym (keymap_x11, hardware_keycode,
1233                                      group, state,
1234                                      level, effective_group);
1235     }
1236
1237   if (consumed_modifiers)
1238     *consumed_modifiers = tmp_modifiers;
1239                                 
1240   if (keyval)
1241     *keyval = tmp_keyval;
1242
1243   return tmp_keyval != NoSymbol;
1244 }
1245
1246
1247 /* Key handling not part of the keymap */
1248
1249 gchar*
1250 gdk_keyval_name (guint        keyval)
1251 {
1252   switch (keyval)
1253     {
1254     case GDK_Page_Up:
1255       return "Page_Up";
1256     case GDK_Page_Down:
1257       return "Page_Down";
1258     case GDK_KP_Page_Up:
1259       return "KP_Page_Up";
1260     case GDK_KP_Page_Down:
1261       return "KP_Page_Down";
1262     }
1263   
1264   return XKeysymToString (keyval);
1265 }
1266
1267 guint
1268 gdk_keyval_from_name (const gchar *keyval_name)
1269 {
1270   g_return_val_if_fail (keyval_name != NULL, 0);
1271   
1272   return XStringToKeysym (keyval_name);
1273 }
1274
1275 #ifdef HAVE_XCONVERTCASE
1276 void
1277 gdk_keyval_convert_case (guint symbol,
1278                          guint *lower,
1279                          guint *upper)
1280 {
1281   KeySym xlower = 0;
1282   KeySym xupper = 0;
1283
1284   /* Check for directly encoded 24-bit UCS characters: */
1285   if ((symbol & 0xff000000) == 0x01000000)
1286     {
1287       if (lower)
1288         *lower = gdk_unicode_to_keyval (g_unichar_tolower (symbol & 0x00ffffff));
1289       if (upper)
1290         *upper = gdk_unicode_to_keyval (g_unichar_toupper (symbol & 0x00ffffff));
1291       return;
1292     }
1293   
1294   if (symbol)
1295     XConvertCase (symbol, &xlower, &xupper);
1296
1297   if (lower)
1298     *lower = xlower;
1299   if (upper)
1300     *upper = xupper;
1301 }  
1302 #endif /* HAVE_XCONVERTCASE */
1303
1304 gint
1305 _gdk_x11_get_group_for_state (GdkDisplay      *display,
1306                               GdkModifierType  state)
1307 {
1308   GdkDisplayX11 *display_x11 = GDK_DISPLAY_X11 (display);
1309   
1310 #ifdef HAVE_XKB
1311   if (display_x11->use_xkb)
1312     {
1313       return XkbGroupForCoreState (state);
1314     }
1315   else
1316 #endif
1317     {
1318       GdkKeymapX11 *keymap_impl = GDK_KEYMAP_X11 (gdk_keymap_get_for_display (display));
1319       update_keymaps (keymap_impl);
1320       return (state & keymap_impl->group_switch_mask) ? 1 : 0;
1321     }
1322 }