gtkkeyhash.c 15.9 KB
Newer Older
1 2
/* gtkkeyhash.c: Keymap aware matching of key bindings
 *
Cody Russell's avatar
Cody Russell committed
3
 * GTK - The GIMP Toolkit
4 5 6 7 8 9 10 11 12 13 14 15 16
 * Copyright (C) 2002, Red Hat Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
Javier Jardon's avatar
Javier Jardon committed
17
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
18
 */
19

20
#include "config.h"
21

22 23
#include "gtkdebug.h"
#include "gtkkeyhash.h"
24
#include "gtkprivate.h"
25 26 27 28 29 30 31 32

typedef struct _GtkKeyHashEntry GtkKeyHashEntry;

struct _GtkKeyHashEntry
{
  guint keyval;
  GdkModifierType modifiers;
  gpointer value;
33 34 35 36 37

  /* Set as a side effect of generating key_hash->keycode_hash
   */
  GdkKeymapKey *keys;		
  gint n_keys;
38 39 40 41 42 43 44
};

struct _GtkKeyHash
{
  GdkKeymap *keymap;
  GHashTable *keycode_hash;
  GHashTable *reverse_hash;
45
  GList *entries_list;
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
  GDestroyNotify destroy_notify;
};

static void
key_hash_clear_keycode (gpointer key,
			gpointer value,
			gpointer data)
{
  GSList *keys = value;
  g_slist_free (keys);
}

static void
key_hash_insert_entry (GtkKeyHash      *key_hash,
		       GtkKeyHashEntry *entry)
{
  gint i;

64
  g_free (entry->keys);
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
  gdk_keymap_get_entries_for_keyval (key_hash->keymap,
				     entry->keyval,
				     &entry->keys, &entry->n_keys);
  
  for (i = 0; i < entry->n_keys; i++)
    {
      GSList *old_keys = g_hash_table_lookup (key_hash->keycode_hash,
					      GUINT_TO_POINTER (entry->keys[i].keycode));
      old_keys = g_slist_prepend (old_keys, entry);
      g_hash_table_insert (key_hash->keycode_hash,
			   GUINT_TO_POINTER (entry->keys[i].keycode),
			   old_keys);
    }
}

80 81
static GHashTable *
key_hash_get_keycode_hash (GtkKeyHash *key_hash)
82
{
83 84 85 86 87 88 89 90 91 92 93 94 95
  if (!key_hash->keycode_hash)
    {
      GList *tmp_list;
  
      key_hash->keycode_hash = g_hash_table_new (g_direct_hash, NULL);
      
      /* Preserve the original insertion order
       */
      for (tmp_list = g_list_last (key_hash->entries_list);
	   tmp_list;
	   tmp_list = tmp_list->prev)
	key_hash_insert_entry (key_hash, tmp_list->data);
    }
96

97
  return key_hash->keycode_hash;
98 99 100
}

static void
101 102
key_hash_keys_changed (GdkKeymap  *keymap,
		       GtkKeyHash *key_hash)
103
{
104
  /* The keymap changed, so we have to regenerate the keycode hash
105
   */
106 107 108 109 110 111
  if (key_hash->keycode_hash)
    {
      g_hash_table_foreach (key_hash->keycode_hash, key_hash_clear_keycode, NULL);
      g_hash_table_destroy (key_hash->keycode_hash);
      key_hash->keycode_hash = NULL;
    }
112 113 114 115 116 117 118 119 120 121
}

/**
 * _gtk_key_hash_new:
 * @keymap: a #GdkKeymap
 * @item_destroy_notify: function to be called when items are removed
 *   from the hash or %NULL.
 * 
 * Create a new key hash object for doing binding resolution. 
 * 
122
 * Returns: the newly created object. Free with _gtk_key_hash_free().
123 124 125 126 127 128 129 130
 **/
GtkKeyHash *
_gtk_key_hash_new (GdkKeymap      *keymap,
		   GDestroyNotify  item_destroy_notify)
{
  GtkKeyHash *key_hash = g_new (GtkKeyHash, 1);

  key_hash->keymap = keymap;
131
  g_signal_connect (keymap, "keys-changed",
132
		    G_CALLBACK (key_hash_keys_changed), key_hash);
133

134 135
  key_hash->entries_list = NULL;
  key_hash->keycode_hash = NULL;
136 137 138 139 140 141 142 143 144 145 146 147 148 149
  key_hash->reverse_hash = g_hash_table_new (g_direct_hash, NULL);
  key_hash->destroy_notify = item_destroy_notify;

  return key_hash;
}

static void
key_hash_free_entry (GtkKeyHash      *key_hash,
		     GtkKeyHashEntry *entry)
{
  if (key_hash->destroy_notify)
    (*key_hash->destroy_notify) (entry->value);
  
  g_free (entry->keys);
150
  g_slice_free (GtkKeyHashEntry, entry);
151 152 153
}

static void
154
key_hash_free_entry_foreach (gpointer value,
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
			     gpointer data)
{
  GtkKeyHashEntry *entry = value;
  GtkKeyHash *key_hash = data;

  key_hash_free_entry (key_hash, entry);
}

/**
 * gtk_key_hash_free:
 * @key_hash: a #GtkKeyHash
 * 
 * Destroys a key hash created with gtk_key_hash_new()
 **/
void
_gtk_key_hash_free (GtkKeyHash *key_hash)
{
  g_signal_handlers_disconnect_by_func (key_hash->keymap,
Manish Singh's avatar
Manish Singh committed
173 174
					key_hash_keys_changed,
					key_hash);
175

176 177 178 179 180 181
  if (key_hash->keycode_hash)
    {
      g_hash_table_foreach (key_hash->keycode_hash, key_hash_clear_keycode, NULL);
      g_hash_table_destroy (key_hash->keycode_hash);
    }
  
182 183
  g_hash_table_destroy (key_hash->reverse_hash);

184 185 186
  g_list_foreach (key_hash->entries_list, key_hash_free_entry_foreach, key_hash);
  g_list_free (key_hash->entries_list);
  
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
  g_free (key_hash);
}

/**
 * _gtk_key_hash_add_entry:
 * @key_hash: a #GtkKeyHash
 * @keyval: key symbol for this binding
 * @modifiers: modifiers for this binding
 * @value: value to insert in the key hash
 * 
 * Inserts a pair of key symbol and modifier mask into the key hash. 
 **/
void
_gtk_key_hash_add_entry (GtkKeyHash      *key_hash,
			 guint            keyval,
			 GdkModifierType  modifiers,
			 gpointer         value)
{
205
  GtkKeyHashEntry *entry = g_slice_new (GtkKeyHashEntry);
206 207 208 209

  entry->value = value;
  entry->keyval = keyval;
  entry->modifiers = modifiers;
210
  entry->keys = NULL;
211

212 213 214 215 216
  key_hash->entries_list = g_list_prepend (key_hash->entries_list, entry);
  g_hash_table_insert (key_hash->reverse_hash, value, key_hash->entries_list);

  if (key_hash->keycode_hash)
    key_hash_insert_entry (key_hash, entry);
217 218 219 220 221 222 223 224 225 226 227 228 229 230
}

/**
 * _gtk_key_hash_remove_entry:
 * @key_hash: a #GtkKeyHash
 * @value: value previously added with _gtk_key_hash_add_entry()
 * 
 * Removes a value previously added to the key hash with
 * _gtk_key_hash_add_entry().
 **/
void
_gtk_key_hash_remove_entry (GtkKeyHash *key_hash,
			    gpointer    value)
{
231 232 233
  GList *entry_node = g_hash_table_lookup (key_hash->reverse_hash, value);
  
  if (entry_node)
234
    {
235
      GtkKeyHashEntry *entry = entry_node->data;
236

237
      if (key_hash->keycode_hash)
238
	{
239 240 241
	  gint i;
	  
	  for (i = 0; i < entry->n_keys; i++)
242
	    {
243 244 245 246 247 248 249 250 251 252 253 254 255 256
	      GSList *old_keys = g_hash_table_lookup (key_hash->keycode_hash,
						      GUINT_TO_POINTER (entry->keys[i].keycode));
	      
	      GSList *new_keys = g_slist_remove (old_keys, entry);
	      if (new_keys != old_keys)
		{
		  if (new_keys)
		    g_hash_table_insert (key_hash->keycode_hash,
					 GUINT_TO_POINTER (entry->keys[i].keycode),
					 new_keys);
		  else
		    g_hash_table_remove (key_hash->keycode_hash,
					 GUINT_TO_POINTER (entry->keys[i].keycode));
		}
257 258
	    }
	}
259 260 261
	  
      g_hash_table_remove (key_hash->reverse_hash, entry_node);
      key_hash->entries_list = g_list_delete_link (key_hash->entries_list, entry_node);
262 263 264 265 266

      key_hash_free_entry (key_hash, entry);
    }
}

267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
static gint
lookup_result_compare (gconstpointer a,
		       gconstpointer b)
{
  const GtkKeyHashEntry *entry_a = a;
  const GtkKeyHashEntry *entry_b = b;
  guint modifiers;

  gint n_bits_a = 0;
  gint n_bits_b = 0;

  modifiers = entry_a->modifiers;
  while (modifiers)
    {
      if (modifiers & 1)
	n_bits_a++;
      modifiers >>= 1;
    }

  modifiers = entry_b->modifiers;
  while (modifiers)
    {
      if (modifiers & 1)
	n_bits_b++;
      modifiers >>= 1;
    }

  return n_bits_a < n_bits_b ? -1 : (n_bits_a == n_bits_b ? 0 : 1);
  
}

/* Sort a list of results so that matches with less modifiers come
 * before matches with more modifiers
 */
static GSList *
sort_lookup_results (GSList *slist)
{
  return g_slist_sort (slist, lookup_result_compare);
}

307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
static gint
lookup_result_compare_by_keyval (gconstpointer a,
		                 gconstpointer b)
{
  const GtkKeyHashEntry *entry_a = a;
  const GtkKeyHashEntry *entry_b = b;

  if (entry_a->keyval < entry_b->keyval)
	return -1;
  else if (entry_a->keyval > entry_b->keyval)
	return 1;
  else
	return 0;
}

static GSList *
sort_lookup_results_by_keyval (GSList *slist)
{
  return g_slist_sort (slist, lookup_result_compare_by_keyval);
}

/* Return true if keyval is defined in keyboard group
 */
static gboolean 
keyval_in_group (GdkKeymap  *keymap,
                 guint      keyval,
                 gint       group)
{                 
  GtkKeyHashEntry entry;
  gint i;

  gdk_keymap_get_entries_for_keyval (keymap,
				     keyval,
				     &entry.keys, &entry.n_keys);

  for (i = 0; i < entry.n_keys; i++)
    {
      if (entry.keys[i].group == group)
        {
          g_free (entry.keys);
          return TRUE;
        }
    }

  g_free (entry.keys);
  return FALSE;
}

355 356 357 358 359
/**
 * _gtk_key_hash_lookup:
 * @key_hash: a #GtkKeyHash
 * @hardware_keycode: hardware keycode field from a #GdkEventKey
 * @state: state field from a #GdkEventKey
360 361
 * @mask: mask of modifiers to consider when matching against the
 *        modifiers in entries.
362 363 364
 * @group: group field from a #GdkEventKey
 * 
 * Looks up the best matching entry or entries in the hash table for
365 366
 * a given event. The results are sorted so that entries with less
 * modifiers come before entries with more modifiers.
367
 * 
368 369 370 371 372
 * The matches returned by this function can be exact (i.e. keycode, level
 * and group all match) or fuzzy (i.e. keycode and level match, but group
 * does not). As long there are any exact matches, only exact matches
 * are returned. If there are no exact matches, fuzzy matches will be
 * returned, as long as they are not shadowing a possible exact match.
373
 * This means that fuzzy matches won’t be considered if their keyval is 
374 375
 * present in the current group.
 * 
376
 * Returns: A newly-allocated #GSList of matching entries.
377 378
 *     Free with g_slist_free() when no longer needed.
 */
379 380 381 382
GSList *
_gtk_key_hash_lookup (GtkKeyHash      *key_hash,
		      guint16          hardware_keycode,
		      GdkModifierType  state,
383
		      GdkModifierType  mask,
384 385
		      gint             group)
{
386 387
  GHashTable *keycode_hash = key_hash_get_keycode_hash (key_hash);
  GSList *keys = g_hash_table_lookup (keycode_hash, GUINT_TO_POINTER ((guint)hardware_keycode));
388
  GSList *results = NULL;
389
  GSList *l;
390 391 392 393
  gboolean have_exact = FALSE;
  guint keyval;
  gint effective_group;
  gint level;
394
  GdkModifierType modifiers;
395
  GdkModifierType consumed_modifiers;
396
  GdkModifierType shift_group_mask;
397
  gboolean group_mod_is_accel_mod = FALSE;
398 399
  const GdkModifierType xmods = GDK_MOD2_MASK|GDK_MOD3_MASK|GDK_MOD4_MASK|GDK_MOD5_MASK;
  const GdkModifierType vmods = GDK_SUPER_MASK|GDK_HYPER_MASK|GDK_META_MASK;
400

401 402 403
  /* We don't want Caps_Lock to affect keybinding lookups.
   */
  state &= ~GDK_LOCK_MASK;
404

405 406 407 408
  _gtk_translate_keyboard_accel_state (key_hash->keymap,
                                       hardware_keycode, state, mask, group,
                                       &keyval,
                                       &effective_group, &level, &consumed_modifiers);
409

410 411 412
  /* if the group-toggling modifier is part of the default accel mod
   * mask, and it is active, disable it for matching
   */
413 414 415
  shift_group_mask = gdk_keymap_get_modifier_mask (key_hash->keymap,
                                                   GDK_MODIFIER_INTENT_SHIFT_GROUP);
  if (mask & shift_group_mask)
416 417 418
    group_mod_is_accel_mod = TRUE;

  gdk_keymap_map_virtual_modifiers (key_hash->keymap, &mask);
419
  gdk_keymap_add_virtual_modifiers (key_hash->keymap, &state);
420 421 422 423 424 425 426 427 428 429 430 431

  GTK_NOTE (KEYBINDINGS,
	    g_message ("Looking up keycode = %u, modifiers = 0x%04x,\n"
		       "    keyval = %u, group = %d, level = %d, consumed_modifiers = 0x%04x",
		       hardware_keycode, state, keyval, effective_group, level, consumed_modifiers));

  if (keys)
    {
      GSList *tmp_list = keys;
      while (tmp_list)
	{
	  GtkKeyHashEntry *entry = tmp_list->data;
432 433 434

	  /* If the virtual Super, Hyper or Meta modifiers are present,
	   * they will also be mapped to some of the Mod2 - Mod5 modifiers,
435
	   * so we compare them twice, ignoring either set.
436 437 438 439
	   * We accept combinations involving virtual modifiers only if they
	   * are mapped to separate modifiers; i.e. if Super and Hyper are
	   * both mapped to Mod4, then pressing a key that is mapped to Mod4
	   * will not match a Super+Hyper entry.
440
	   */
441 442 443 444
          modifiers = entry->modifiers;
          if (gdk_keymap_map_virtual_modifiers (key_hash->keymap, &modifiers) &&
	      ((modifiers & ~consumed_modifiers & mask & ~vmods) == (state & ~consumed_modifiers & mask & ~vmods) ||
	       (modifiers & ~consumed_modifiers & mask & ~xmods) == (state & ~consumed_modifiers & mask & ~xmods)))
445 446 447
	    {
	      gint i;

448 449 450 451 452
	      if (keyval == entry->keyval && /* Exact match */
                  /* but also match for group if it is an accel mod, because
                   * otherwise we can get multiple exact matches, some being
                   * bogus */
                  (!group_mod_is_accel_mod ||
453
                   (state & shift_group_mask) == (entry->modifiers & shift_group_mask)))
454

455 456 457 458
		{
		  GTK_NOTE (KEYBINDINGS,
			    g_message ("  found exact match, keyval = %u, modifiers = 0x%04x",
				       entry->keyval, entry->modifiers));
459

460 461 462 463 464 465 466
		  if (!have_exact)
		    {
		      g_slist_free (results);
		      results = NULL;
		    }

		  have_exact = TRUE;
467
		  results = g_slist_prepend (results, entry);
468 469 470 471 472 473
		}

	      if (!have_exact)
		{
		  for (i = 0; i < entry->n_keys; i++)
		    {
474 475 476 477 478
                      if (entry->keys[i].keycode == hardware_keycode &&
                          entry->keys[i].level == level &&
                           /* Only match for group if it's an accel mod */
                          (!group_mod_is_accel_mod ||
                           entry->keys[i].group == effective_group))
479 480 481 482
			{
			  GTK_NOTE (KEYBINDINGS,
				    g_message ("  found group = %d, level = %d",
					       entry->keys[i].group, entry->keys[i].level));
483
			  results = g_slist_prepend (results, entry);
484 485 486 487 488 489 490 491 492 493
			  break;
			}
		    }
		}
	    }

	  tmp_list = tmp_list->next;
	}
    }

494 495 496 497 498 499
  if (!have_exact && results) 
    {
      /* If there are fuzzy matches, check that the current group doesn't also 
       * define these keyvals; if yes, discard results because a widget up in 
       * the stack may have an exact match and we don't want to 'steal' it.
       */
500
      guint oldkeyval = 0;
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
      GtkKeyHashEntry *keyhashentry;

      results = sort_lookup_results_by_keyval (results);
      for (l = results; l; l = l->next)
        {
          keyhashentry = l->data;
          if (l == results || oldkeyval != keyhashentry->keyval)
            {
              oldkeyval = keyhashentry->keyval;
              if (keyval_in_group (key_hash->keymap, oldkeyval, group))
                {
       	          g_slist_free (results);
       	          return NULL;
                }
            }
        }
    }
    
519 520 521 522 523
  results = sort_lookup_results (results);
  for (l = results; l; l = l->next)
    l->data = ((GtkKeyHashEntry *)l->data)->value;

  return results;
524 525 526 527 528 529 530 531
}

/**
 * _gtk_key_hash_lookup_keyval:
 * @key_hash: a #GtkKeyHash
 * @event: a #GtkEvent
 * 
 * Looks up the best matching entry or entries in the hash table for a
532
 * given keyval/modifiers pair. It’s better to use
533
 * _gtk_key_hash_lookup() if you have the original #GdkEventKey
534 535
 * available.  The results are sorted so that entries with less
 * modifiers come before entries with more modifiers.
536
 * 
537
 * Returns: A #GSList of all matching entries.
538 539 540 541 542 543 544 545 546
 **/
GSList *
_gtk_key_hash_lookup_keyval (GtkKeyHash     *key_hash,
			     guint           keyval,
			     GdkModifierType modifiers)
{
  GdkKeymapKey *keys;
  gint n_keys;
  GSList *results = NULL;
547
  GSList *l;
548 549 550 551

  if (!keyval)			/* Key without symbol */
    return NULL;

552
  /* Find some random keycode for this keyval
553 554 555 556 557 558
   */
  gdk_keymap_get_entries_for_keyval (key_hash->keymap, keyval,
				     &keys, &n_keys);

  if (n_keys)
    {
559 560
      GHashTable *keycode_hash = key_hash_get_keycode_hash (key_hash);
      GSList *entries = g_hash_table_lookup (keycode_hash, GUINT_TO_POINTER (keys[0].keycode));
561 562 563 564 565 566

      while (entries)
	{
	  GtkKeyHashEntry *entry = entries->data;

	  if (entry->keyval == keyval && entry->modifiers == modifiers)
567
	    results = g_slist_prepend (results, entry);
568 569 570 571 572 573 574

	  entries = entries->next;
	}
    }

  g_free (keys);
	  
575 576 577 578 579
  results = sort_lookup_results (results);
  for (l = results; l; l = l->next)
    l->data = ((GtkKeyHashEntry *)l->data)->value;

  return results;
580
}