state: check wrap_group_into_range() return value
[platform/upstream/libxkbcommon.git] / src / state.c
1 /************************************************************
2  * Copyright (c) 1993 by Silicon Graphics Computer Systems, Inc.
3  *
4  * Permission to use, copy, modify, and distribute this
5  * software and its documentation for any purpose and without
6  * fee is hereby granted, provided that the above copyright
7  * notice appear in all copies and that both that copyright
8  * notice and this permission notice appear in supporting
9  * documentation, and that the name of Silicon Graphics not be
10  * used in advertising or publicity pertaining to distribution
11  * of the software without specific prior written permission.
12  * Silicon Graphics makes no representation about the suitability
13  * of this software for any purpose. It is provided "as is"
14  * without any express or implied warranty.
15  *
16  * SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
17  * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
18  * AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
19  * GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
20  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
21  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
22  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION  WITH
23  * THE USE OR PERFORMANCE OF THIS SOFTWARE.
24  *
25  ********************************************************/
26
27 /*
28  * Copyright © 2012 Intel Corporation
29  * Copyright © 2012 Ran Benita <ran234@gmail.com>
30  *
31  * Permission is hereby granted, free of charge, to any person obtaining a
32  * copy of this software and associated documentation files (the "Software"),
33  * to deal in the Software without restriction, including without limitation
34  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
35  * and/or sell copies of the Software, and to permit persons to whom the
36  * Software is furnished to do so, subject to the following conditions:
37  *
38  * The above copyright notice and this permission notice (including the next
39  * paragraph) shall be included in all copies or substantial portions of the
40  * Software.
41  *
42  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
43  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
44  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
45  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
46  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
47  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
48  * DEALINGS IN THE SOFTWARE.
49  *
50  * Author: Daniel Stone <daniel@fooishbar.org>
51  */
52
53 /*
54  * This is a bastardised version of xkbActions.c from the X server which
55  * does not support, for the moment:
56  *   - AccessX sticky/debounce/etc (will come later)
57  *   - pointer keys (may come later)
58  *   - key redirects (unlikely)
59  *   - messages (very unlikely)
60  */
61
62 #include "keymap.h"
63 #include "keysym.h"
64
65 struct xkb_filter {
66     union xkb_action action;
67     const struct xkb_key *key;
68     uint32_t priv;
69     bool (*func)(struct xkb_state *state,
70                  struct xkb_filter *filter,
71                  const struct xkb_key *key,
72                  enum xkb_key_direction direction);
73     int refcnt;
74 };
75
76 struct state_components {
77     /* These may be negative, because of -1 group actions. */
78     int32_t base_group; /**< depressed */
79     int32_t latched_group;
80     int32_t locked_group;
81     xkb_layout_index_t group; /**< effective */
82
83     xkb_mod_mask_t base_mods; /**< depressed */
84     xkb_mod_mask_t latched_mods;
85     xkb_mod_mask_t locked_mods;
86     xkb_mod_mask_t mods; /**< effective */
87
88     xkb_led_mask_t leds;
89 };
90
91 struct xkb_state {
92     /*
93      * Before updating the state, we keep a copy of just this struct. This
94      * allows us to report which components of the state have changed.
95      */
96     struct state_components components;
97
98     /*
99      * At each event, we accumulate all the needed modifications to the base
100      * modifiers, and apply them at the end. These keep track of this state.
101      */
102     xkb_mod_mask_t set_mods;
103     xkb_mod_mask_t clear_mods;
104
105     /*
106      * We mustn't clear a base modifier if there's another depressed key
107      * which affects it, e.g. given this sequence
108      * < Left Shift down, Right Shift down, Left Shift Up >
109      * the modifier should still be set. This keeps the count.
110      */
111     int16_t mod_key_count[XKB_MAX_MODS];
112
113     int refcnt;
114     darray(struct xkb_filter) filters;
115     struct xkb_keymap *keymap;
116 };
117
118 static const struct xkb_key_type_entry *
119 get_entry_for_key_state(struct xkb_state *state, const struct xkb_key *key,
120                         xkb_layout_index_t group)
121 {
122     const struct xkb_key_type *type = key->groups[group].type;
123     xkb_mod_mask_t active_mods = state->components.mods & type->mods.mask;
124
125     for (unsigned i = 0; i < type->num_entries; i++) {
126         /*
127          * If the virtual modifiers are not bound to anything, we're
128          * supposed to skip the entry (xserver does this with cached
129          * entry->active field).
130          */
131         if (!type->entries[i].mods.mask)
132             continue;
133
134         if (type->entries[i].mods.mask == active_mods)
135             return &type->entries[i];
136     }
137
138     return NULL;
139 }
140
141 /**
142  * Returns the level to use for the given key and state, or
143  * XKB_LEVEL_INVALID.
144  */
145 XKB_EXPORT xkb_level_index_t
146 xkb_state_key_get_level(struct xkb_state *state, xkb_keycode_t kc,
147                         xkb_layout_index_t layout)
148 {
149     const struct xkb_key *key = XkbKey(state->keymap, kc);
150     const struct xkb_key_type_entry *entry;
151
152     if (!key || layout >= key->num_groups)
153         return XKB_LEVEL_INVALID;
154
155     /* If we don't find an explicit match the default is 0. */
156     entry = get_entry_for_key_state(state, key, layout);
157     if (!entry)
158         return 0;
159
160     return entry->level;
161 }
162
163 xkb_layout_index_t
164 wrap_group_into_range(int32_t group,
165                       xkb_layout_index_t num_groups,
166                       enum xkb_range_exceed_type out_of_range_group_action,
167                       xkb_layout_index_t out_of_range_group_number)
168 {
169     if (num_groups == 0)
170         return XKB_LAYOUT_INVALID;
171
172     if (group >= 0 && (xkb_layout_index_t) group < num_groups)
173         return group;
174
175     switch (out_of_range_group_action) {
176     case RANGE_REDIRECT:
177         if (out_of_range_group_number >= num_groups)
178             return 0;
179         return out_of_range_group_number;
180
181     case RANGE_SATURATE:
182         if (group < 0)
183             return 0;
184         else
185             return num_groups - 1;
186
187     case RANGE_WRAP:
188     default:
189         /*
190          * C99 says a negative dividend in a modulo operation always
191          * gives a negative result.
192          */
193         if (group < 0)
194             return ((int) num_groups + (group % (int) num_groups));
195         else
196             return group % num_groups;
197     }
198 }
199
200 /**
201  * Returns the layout to use for the given key and state, taking
202  * wrapping/clamping/etc into account, or XKB_LAYOUT_INVALID.
203  */
204 XKB_EXPORT xkb_layout_index_t
205 xkb_state_key_get_layout(struct xkb_state *state, xkb_keycode_t kc)
206 {
207     const struct xkb_key *key = XkbKey(state->keymap, kc);
208
209     if (!key)
210         return XKB_LAYOUT_INVALID;
211
212     return wrap_group_into_range(state->components.group, key->num_groups,
213                                  key->out_of_range_group_action,
214                                  key->out_of_range_group_number);
215 }
216
217 static const union xkb_action fake = { .type = ACTION_TYPE_NONE };
218
219 static const union xkb_action *
220 xkb_key_get_action(struct xkb_state *state, const struct xkb_key *key)
221 {
222     xkb_layout_index_t layout;
223     xkb_level_index_t level;
224
225     layout = xkb_state_key_get_layout(state, key->keycode);
226     if (layout == XKB_LAYOUT_INVALID)
227         return &fake;
228
229     level = xkb_state_key_get_level(state, key->keycode, layout);
230     if (level == XKB_LEVEL_INVALID)
231         return &fake;
232
233     return &key->groups[layout].levels[level].action;
234 }
235
236 static struct xkb_filter *
237 xkb_filter_new(struct xkb_state *state)
238 {
239     struct xkb_filter *filter = NULL, *iter;
240
241     darray_foreach(iter, state->filters) {
242         if (iter->func)
243             continue;
244         filter = iter;
245         break;
246     }
247
248     if (!filter) {
249         darray_resize0(state->filters, darray_size(state->filters) + 1);
250         filter = &darray_item(state->filters, darray_size(state->filters) -1);
251     }
252
253     filter->refcnt = 1;
254     return filter;
255 }
256
257 /***====================================================================***/
258
259 static bool
260 xkb_filter_group_set_func(struct xkb_state *state,
261                           struct xkb_filter *filter,
262                           const struct xkb_key *key,
263                           enum xkb_key_direction direction)
264 {
265     if (key != filter->key) {
266         filter->action.group.flags &= ~ACTION_LOCK_CLEAR;
267         return true;
268     }
269
270     if (direction == XKB_KEY_DOWN) {
271         filter->refcnt++;
272         return false;
273     }
274     else if (--filter->refcnt > 0) {
275         return false;
276     }
277
278     state->components.base_group = filter->priv;
279
280     if (filter->action.group.flags & ACTION_LOCK_CLEAR)
281         state->components.locked_group = 0;
282
283     filter->func = NULL;
284     return true;
285 }
286
287 static void
288 xkb_filter_group_set_new(struct xkb_state *state, struct xkb_filter *filter)
289 {
290     filter->priv = state->components.base_group;
291     if (filter->action.group.flags & ACTION_ABSOLUTE_SWITCH)
292         state->components.base_group = filter->action.group.group;
293     else
294         state->components.base_group += filter->action.group.group;
295 }
296
297 static bool
298 xkb_filter_group_lock_func(struct xkb_state *state,
299                            struct xkb_filter *filter,
300                            const struct xkb_key *key,
301                            enum xkb_key_direction direction)
302 {
303     if (key != filter->key)
304         return true;
305
306     if (direction == XKB_KEY_DOWN) {
307         filter->refcnt++;
308         return false;
309     }
310     if (--filter->refcnt > 0)
311         return false;
312
313     filter->func = NULL;
314     return true;
315 }
316
317 static void
318 xkb_filter_group_lock_new(struct xkb_state *state, struct xkb_filter *filter)
319 {
320     if (filter->action.group.flags & ACTION_ABSOLUTE_SWITCH)
321         state->components.locked_group = filter->action.group.group;
322     else
323         state->components.locked_group += filter->action.group.group;
324 }
325
326 static bool
327 xkb_filter_mod_set_func(struct xkb_state *state,
328                         struct xkb_filter *filter,
329                         const struct xkb_key *key,
330                         enum xkb_key_direction direction)
331 {
332     if (key != filter->key) {
333         filter->action.mods.flags &= ~ACTION_LOCK_CLEAR;
334         return true;
335     }
336
337     if (direction == XKB_KEY_DOWN) {
338         filter->refcnt++;
339         return false;
340     }
341     else if (--filter->refcnt > 0) {
342         return false;
343     }
344
345     state->clear_mods = filter->action.mods.mods.mask;
346     if (filter->action.mods.flags & ACTION_LOCK_CLEAR)
347         state->components.locked_mods &= ~filter->action.mods.mods.mask;
348
349     filter->func = NULL;
350     return true;
351 }
352
353 static void
354 xkb_filter_mod_set_new(struct xkb_state *state, struct xkb_filter *filter)
355 {
356     state->set_mods = filter->action.mods.mods.mask;
357 }
358
359 static bool
360 xkb_filter_mod_lock_func(struct xkb_state *state,
361                          struct xkb_filter *filter,
362                          const struct xkb_key *key,
363                          enum xkb_key_direction direction)
364 {
365     if (key != filter->key)
366         return true;
367
368     if (direction == XKB_KEY_DOWN) {
369         filter->refcnt++;
370         return false;
371     }
372     if (--filter->refcnt > 0)
373         return false;
374
375     state->clear_mods |= filter->action.mods.mods.mask;
376     if (!(filter->action.mods.flags & ACTION_LOCK_NO_UNLOCK))
377         state->components.locked_mods &= ~filter->priv;
378
379     filter->func = NULL;
380     return true;
381 }
382
383 static void
384 xkb_filter_mod_lock_new(struct xkb_state *state, struct xkb_filter *filter)
385 {
386     filter->priv = (state->components.locked_mods &
387                     filter->action.mods.mods.mask);
388     state->set_mods |= filter->action.mods.mods.mask;
389     if (!(filter->action.mods.flags & ACTION_LOCK_NO_LOCK))
390         state->components.locked_mods |= filter->action.mods.mods.mask;
391 }
392
393 enum xkb_key_latch_state {
394     NO_LATCH,
395     LATCH_KEY_DOWN,
396     LATCH_PENDING,
397 };
398
399 static bool
400 xkb_action_breaks_latch(const union xkb_action *action)
401 {
402     switch (action->type) {
403     case ACTION_TYPE_NONE:
404     case ACTION_TYPE_PTR_BUTTON:
405     case ACTION_TYPE_PTR_LOCK:
406     case ACTION_TYPE_CTRL_SET:
407     case ACTION_TYPE_CTRL_LOCK:
408     case ACTION_TYPE_SWITCH_VT:
409     case ACTION_TYPE_TERMINATE:
410         return true;
411     default:
412         return false;
413     }
414 }
415
416 static bool
417 xkb_filter_mod_latch_func(struct xkb_state *state,
418                           struct xkb_filter *filter,
419                           const struct xkb_key *key,
420                           enum xkb_key_direction direction)
421 {
422     enum xkb_key_latch_state latch = filter->priv;
423
424     if (direction == XKB_KEY_DOWN && latch == LATCH_PENDING) {
425         /* If this is a new keypress and we're awaiting our single latched
426          * keypress, then either break the latch if any random key is pressed,
427          * or promote it to a lock or plain base set if it's the same
428          * modifier. */
429         const union xkb_action *action = xkb_key_get_action(state, key);
430         if (action->type == ACTION_TYPE_MOD_LATCH &&
431             action->mods.flags == filter->action.mods.flags &&
432             action->mods.mods.mask == filter->action.mods.mods.mask) {
433             filter->action = *action;
434             if (filter->action.mods.flags & ACTION_LATCH_TO_LOCK) {
435                 filter->action.type = ACTION_TYPE_MOD_LOCK;
436                 filter->func = xkb_filter_mod_lock_func;
437                 state->components.locked_mods |= filter->action.mods.mods.mask;
438             }
439             else {
440                 filter->action.type = ACTION_TYPE_MOD_SET;
441                 filter->func = xkb_filter_mod_set_func;
442                 state->set_mods = filter->action.mods.mods.mask;
443             }
444             filter->key = key;
445             state->components.latched_mods &= ~filter->action.mods.mods.mask;
446             /* XXX beep beep! */
447             return false;
448         }
449         else if (xkb_action_breaks_latch(action)) {
450             /* XXX: This may be totally broken, we might need to break the
451              *      latch in the next run after this press? */
452             state->components.latched_mods &= ~filter->action.mods.mods.mask;
453             filter->func = NULL;
454             return true;
455         }
456     }
457     else if (direction == XKB_KEY_UP && key == filter->key) {
458         /* Our key got released.  If we've set it to clear locks, and we
459          * currently have the same modifiers locked, then release them and
460          * don't actually latch.  Else we've actually hit the latching
461          * stage, so set PENDING and move our modifier from base to
462          * latched. */
463         if (latch == NO_LATCH ||
464             ((filter->action.mods.flags & ACTION_LOCK_CLEAR) &&
465              (state->components.locked_mods & filter->action.mods.mods.mask) ==
466              filter->action.mods.mods.mask)) {
467             /* XXX: We might be a bit overenthusiastic about clearing
468              *      mods other filters have set here? */
469             if (latch == LATCH_PENDING)
470                 state->components.latched_mods &=
471                     ~filter->action.mods.mods.mask;
472             else
473                 state->clear_mods = filter->action.mods.mods.mask;
474             state->components.locked_mods &= ~filter->action.mods.mods.mask;
475             filter->func = NULL;
476         }
477         else {
478             latch = LATCH_PENDING;
479             state->clear_mods = filter->action.mods.mods.mask;
480             state->components.latched_mods |= filter->action.mods.mods.mask;
481             /* XXX beep beep! */
482         }
483     }
484     else if (direction == XKB_KEY_DOWN && latch == LATCH_KEY_DOWN) {
485         /* Someone's pressed another key while we've still got the latching
486          * key held down, so keep the base modifier state active (from
487          * xkb_filter_mod_latch_new), but don't trip the latch, just clear
488          * it as soon as the modifier gets released. */
489         latch = NO_LATCH;
490     }
491
492     filter->priv = latch;
493
494     return true;
495 }
496
497 static void
498 xkb_filter_mod_latch_new(struct xkb_state *state, struct xkb_filter *filter)
499 {
500     filter->priv = LATCH_KEY_DOWN;
501     state->set_mods = filter->action.mods.mods.mask;
502 }
503
504 static const struct {
505     void (*new)(struct xkb_state *state, struct xkb_filter *filter);
506     bool (*func)(struct xkb_state *state, struct xkb_filter *filter,
507                  const struct xkb_key *key, enum xkb_key_direction direction);
508 } filter_action_funcs[_ACTION_TYPE_NUM_ENTRIES] = {
509     [ACTION_TYPE_MOD_SET]    = { xkb_filter_mod_set_new,
510                                  xkb_filter_mod_set_func },
511     [ACTION_TYPE_MOD_LATCH]  = { xkb_filter_mod_latch_new,
512                                  xkb_filter_mod_latch_func },
513     [ACTION_TYPE_MOD_LOCK]   = { xkb_filter_mod_lock_new,
514                                  xkb_filter_mod_lock_func },
515     [ACTION_TYPE_GROUP_SET]  = { xkb_filter_group_set_new,
516                                  xkb_filter_group_set_func },
517     [ACTION_TYPE_GROUP_LOCK] = { xkb_filter_group_lock_new,
518                                  xkb_filter_group_lock_func },
519 };
520
521 /**
522  * Applies any relevant filters to the key, first from the list of filters
523  * that are currently active, then if no filter has claimed the key, possibly
524  * apply a new filter from the key action.
525  */
526 static void
527 xkb_filter_apply_all(struct xkb_state *state,
528                      const struct xkb_key *key,
529                      enum xkb_key_direction direction)
530 {
531     struct xkb_filter *filter;
532     const union xkb_action *action;
533     bool send = true;
534
535     /* First run through all the currently active filters and see if any of
536      * them have claimed this event. */
537     darray_foreach(filter, state->filters) {
538         if (!filter->func)
539             continue;
540         send = filter->func(state, filter, key, direction) && send;
541     }
542
543     if (!send || direction == XKB_KEY_UP)
544         return;
545
546     action = xkb_key_get_action(state, key);
547
548     /*
549      * It's possible for the keymap to set action->type explicitly, like so:
550      *     interpret XF86_Next_VMode {
551      *         action = Private(type=0x86, data="+VMode");
552      *     };
553      * We don't handle those.
554      */
555     if (action->type >= _ACTION_TYPE_NUM_ENTRIES)
556         return;
557
558     if (!filter_action_funcs[action->type].new)
559         return;
560
561     filter = xkb_filter_new(state);
562     if (!filter)
563         return; /* WSGO */
564
565     filter->key = key;
566     filter->func = filter_action_funcs[action->type].func;
567     filter->action = *action;
568     filter_action_funcs[action->type].new(state, filter);
569 }
570
571 XKB_EXPORT struct xkb_state *
572 xkb_state_new(struct xkb_keymap *keymap)
573 {
574     struct xkb_state *ret;
575
576     ret = calloc(sizeof(*ret), 1);
577     if (!ret)
578         return NULL;
579
580     ret->refcnt = 1;
581     ret->keymap = xkb_keymap_ref(keymap);
582
583     return ret;
584 }
585
586 XKB_EXPORT struct xkb_state *
587 xkb_state_ref(struct xkb_state *state)
588 {
589     state->refcnt++;
590     return state;
591 }
592
593 XKB_EXPORT void
594 xkb_state_unref(struct xkb_state *state)
595 {
596     if (!state || --state->refcnt > 0)
597         return;
598
599     xkb_keymap_unref(state->keymap);
600     darray_free(state->filters);
601     free(state);
602 }
603
604 XKB_EXPORT struct xkb_keymap *
605 xkb_state_get_keymap(struct xkb_state *state)
606 {
607     return state->keymap;
608 }
609
610 /**
611  * Update the LED state to match the rest of the xkb_state.
612  */
613 static void
614 xkb_state_led_update_all(struct xkb_state *state)
615 {
616     xkb_led_index_t idx;
617     const struct xkb_led *led;
618
619     state->components.leds = 0;
620
621     darray_enumerate(idx, led, state->keymap->leds) {
622         xkb_mod_mask_t mod_mask = 0;
623         xkb_layout_mask_t group_mask = 0;
624
625         if (led->which_mods != 0 && led->mods.mask != 0) {
626             if (led->which_mods & XKB_STATE_MODS_EFFECTIVE)
627                 mod_mask |= state->components.mods;
628             if (led->which_mods & XKB_STATE_MODS_DEPRESSED)
629                 mod_mask |= state->components.base_mods;
630             if (led->which_mods & XKB_STATE_MODS_LATCHED)
631                 mod_mask |= state->components.latched_mods;
632             if (led->which_mods & XKB_STATE_MODS_LOCKED)
633                 mod_mask |= state->components.locked_mods;
634
635             if (led->mods.mask & mod_mask) {
636                 state->components.leds |= (1u << idx);
637                 continue;
638             }
639         }
640
641         if (led->which_groups != 0 && led->groups != 0) {
642             if (led->which_groups & XKB_STATE_LAYOUT_EFFECTIVE)
643                 group_mask |= (1u << state->components.group);
644             if (led->which_groups & XKB_STATE_LAYOUT_DEPRESSED)
645                 group_mask |= (1u << state->components.base_group);
646             if (led->which_groups & XKB_STATE_LAYOUT_LATCHED)
647                 group_mask |= (1u << state->components.latched_group);
648             if (led->which_groups & XKB_STATE_LAYOUT_LOCKED)
649                 group_mask |= (1u << state->components.locked_group);
650
651             if (led->groups & group_mask) {
652                 state->components.leds |= (1u << idx);
653                 continue;
654             }
655         }
656
657         if (led->ctrls & state->keymap->enabled_ctrls) {
658             state->components.leds |= (1u << idx);
659             continue;
660         }
661     }
662 }
663
664 /**
665  * Calculates the derived state (effective mods/group and LEDs) from an
666  * up-to-date xkb_state.
667  */
668 static void
669 xkb_state_update_derived(struct xkb_state *state)
670 {
671     xkb_layout_index_t wrapped;
672
673     state->components.mods = (state->components.base_mods |
674                               state->components.latched_mods |
675                               state->components.locked_mods);
676
677     /* TODO: Use groups_wrap control instead of always RANGE_WRAP. */
678
679     wrapped = wrap_group_into_range(state->components.locked_group,
680                                     state->keymap->num_groups,
681                                     RANGE_WRAP, 0);
682     state->components.locked_group =
683         (wrapped == XKB_LAYOUT_INVALID ? 0 : wrapped);
684
685     wrapped = wrap_group_into_range(state->components.base_group +
686                                     state->components.latched_group +
687                                     state->components.locked_group,
688                                     state->keymap->num_groups,
689                                     RANGE_WRAP, 0);
690     state->components.group =
691         (wrapped == XKB_LAYOUT_INVALID ? 0 : wrapped);
692
693     xkb_state_led_update_all(state);
694 }
695
696 static enum xkb_state_component
697 get_state_component_changes(const struct state_components *a,
698                             const struct state_components *b)
699 {
700     xkb_mod_mask_t mask = 0;
701
702     if (a->group != b->group)
703         mask |= XKB_STATE_LAYOUT_EFFECTIVE;
704     if (a->base_group != b->base_group)
705         mask |= XKB_STATE_LAYOUT_DEPRESSED;
706     if (a->latched_group != b->latched_group)
707         mask |= XKB_STATE_LAYOUT_LATCHED;
708     if (a->locked_group != b->locked_group)
709         mask |= XKB_STATE_LAYOUT_LOCKED;
710     if (a->mods != b->mods)
711         mask |= XKB_STATE_MODS_EFFECTIVE;
712     if (a->base_mods != b->base_mods)
713         mask |= XKB_STATE_MODS_DEPRESSED;
714     if (a->latched_mods != b->latched_mods)
715         mask |= XKB_STATE_MODS_LATCHED;
716     if (a->locked_mods != b->locked_mods)
717         mask |= XKB_STATE_MODS_LOCKED;
718     if (a->leds != b->leds)
719         mask |= XKB_STATE_LEDS;
720
721     return mask;
722 }
723
724 /**
725  * Given a particular key event, updates the state structure to reflect the
726  * new modifiers.
727  */
728 XKB_EXPORT enum xkb_state_component
729 xkb_state_update_key(struct xkb_state *state, xkb_keycode_t kc,
730                      enum xkb_key_direction direction)
731 {
732     xkb_mod_index_t i;
733     xkb_mod_mask_t bit;
734     struct state_components prev_components;
735     const struct xkb_key *key = XkbKey(state->keymap, kc);
736
737     if (!key)
738         return 0;
739
740     prev_components = state->components;
741
742     state->set_mods = 0;
743     state->clear_mods = 0;
744
745     xkb_filter_apply_all(state, key, direction);
746
747     for (i = 0, bit = 1; state->set_mods; i++, bit <<= 1) {
748         if (state->set_mods & bit) {
749             state->mod_key_count[i]++;
750             state->components.base_mods |= bit;
751             state->set_mods &= ~bit;
752         }
753     }
754
755     for (i = 0, bit = 1; state->clear_mods; i++, bit <<= 1) {
756         if (state->clear_mods & bit) {
757             state->mod_key_count[i]--;
758             if (state->mod_key_count[i] <= 0) {
759                 state->components.base_mods &= ~bit;
760                 state->mod_key_count[i] = 0;
761             }
762             state->clear_mods &= ~bit;
763         }
764     }
765
766     xkb_state_update_derived(state);
767
768     return get_state_component_changes(&prev_components, &state->components);
769 }
770
771 /**
772  * Updates the state from a set of explicit masks as gained from
773  * xkb_state_serialize_mods and xkb_state_serialize_groups.  As noted in the
774  * documentation for these functions in xkbcommon.h, this round-trip is
775  * lossy, and should only be used to update a slave state mirroring the
776  * master, e.g. in a client/server window system.
777  */
778 XKB_EXPORT enum xkb_state_component
779 xkb_state_update_mask(struct xkb_state *state,
780                       xkb_mod_mask_t base_mods,
781                       xkb_mod_mask_t latched_mods,
782                       xkb_mod_mask_t locked_mods,
783                       xkb_layout_index_t base_group,
784                       xkb_layout_index_t latched_group,
785                       xkb_layout_index_t locked_group)
786 {
787     struct state_components prev_components;
788     xkb_mod_index_t num_mods;
789     xkb_mod_index_t idx;
790
791     prev_components = state->components;
792
793     state->components.base_mods = 0;
794     state->components.latched_mods = 0;
795     state->components.locked_mods = 0;
796     num_mods = xkb_keymap_num_mods(state->keymap);
797
798     for (idx = 0; idx < num_mods; idx++) {
799         xkb_mod_mask_t mod = (1u << idx);
800         if (base_mods & mod)
801             state->components.base_mods |= mod;
802         if (latched_mods & mod)
803             state->components.latched_mods |= mod;
804         if (locked_mods & mod)
805             state->components.locked_mods |= mod;
806     }
807
808     state->components.base_group = base_group;
809     state->components.latched_group = latched_group;
810     state->components.locked_group = locked_group;
811
812     xkb_state_update_derived(state);
813
814     return get_state_component_changes(&prev_components, &state->components);
815 }
816
817 /**
818  * Provides the symbols to use for the given key and state.  Returns the
819  * number of symbols pointed to in syms_out.
820  */
821 XKB_EXPORT int
822 xkb_state_key_get_syms(struct xkb_state *state, xkb_keycode_t kc,
823                        const xkb_keysym_t **syms_out)
824 {
825     xkb_layout_index_t layout;
826     xkb_level_index_t level;
827
828     layout = xkb_state_key_get_layout(state, kc);
829     if (layout == XKB_LAYOUT_INVALID)
830         goto err;
831
832     level = xkb_state_key_get_level(state, kc, layout);
833     if (level == XKB_LEVEL_INVALID)
834         goto err;
835
836     return xkb_keymap_key_get_syms_by_level(state->keymap, kc, layout, level,
837                                             syms_out);
838
839 err:
840     *syms_out = NULL;
841     return 0;
842 }
843
844 /**
845  * Provides either exactly one symbol, or XKB_KEY_NoSymbol.
846  */
847 XKB_EXPORT xkb_keysym_t
848 xkb_state_key_get_one_sym(struct xkb_state *state, xkb_keycode_t kc)
849 {
850     const xkb_keysym_t *syms;
851     xkb_keysym_t sym;
852     int num_syms;
853     xkb_mod_index_t caps;
854
855     num_syms = xkb_state_key_get_syms(state, kc, &syms);
856     if (num_syms != 1)
857         return XKB_KEY_NoSymbol;
858
859     sym = syms[0];
860
861     /*
862      * Perform capitalization transformation, see:
863      * http://www.x.org/releases/current/doc/kbproto/xkbproto.html#Interpreting_the_Lock_Modifier
864      */
865     caps = xkb_keymap_mod_get_index(state->keymap, XKB_MOD_NAME_CAPS);
866     if (xkb_state_mod_index_is_active(state, caps, XKB_STATE_MODS_EFFECTIVE) > 0 &&
867         xkb_state_mod_index_is_consumed(state, kc, caps) == 0)
868         sym = xkb_keysym_to_upper(sym);
869
870     return sym;
871 }
872
873 /**
874  * Serialises the requested modifier state into an xkb_mod_mask_t, with all
875  * the same disclaimers as in xkb_state_update_mask.
876  */
877 XKB_EXPORT xkb_mod_mask_t
878 xkb_state_serialize_mods(struct xkb_state *state,
879                          enum xkb_state_component type)
880 {
881     xkb_mod_mask_t ret = 0;
882
883     if (type & XKB_STATE_MODS_EFFECTIVE)
884         return state->components.mods;
885
886     if (type & XKB_STATE_MODS_DEPRESSED)
887         ret |= state->components.base_mods;
888     if (type & XKB_STATE_MODS_LATCHED)
889         ret |= state->components.latched_mods;
890     if (type & XKB_STATE_MODS_LOCKED)
891         ret |= state->components.locked_mods;
892
893     return ret;
894 }
895
896 /**
897  * Serialises the requested group state, with all the same disclaimers as
898  * in xkb_state_update_mask.
899  */
900 XKB_EXPORT xkb_layout_index_t
901 xkb_state_serialize_layout(struct xkb_state *state,
902                            enum xkb_state_component type)
903 {
904     xkb_layout_index_t ret = 0;
905
906     if (type & XKB_STATE_LAYOUT_EFFECTIVE)
907         return state->components.group;
908
909     if (type & XKB_STATE_LAYOUT_DEPRESSED)
910         ret += state->components.base_group;
911     if (type & XKB_STATE_LAYOUT_LATCHED)
912         ret += state->components.latched_group;
913     if (type & XKB_STATE_LAYOUT_LOCKED)
914         ret += state->components.locked_group;
915
916     return ret;
917 }
918
919 /**
920  * Returns 1 if the given modifier is active with the specified type(s), 0 if
921  * not, or -1 if the modifier is invalid.
922  */
923 XKB_EXPORT int
924 xkb_state_mod_index_is_active(struct xkb_state *state,
925                               xkb_mod_index_t idx,
926                               enum xkb_state_component type)
927 {
928     if (idx >= xkb_keymap_num_mods(state->keymap))
929         return -1;
930
931     return !!(xkb_state_serialize_mods(state, type) & (1u << idx));
932 }
933
934 /**
935  * Helper function for xkb_state_mod_indices_are_active and
936  * xkb_state_mod_names_are_active.
937  */
938 static int
939 match_mod_masks(struct xkb_state *state,
940                 enum xkb_state_component type,
941                 enum xkb_state_match match,
942                 xkb_mod_mask_t wanted)
943 {
944     xkb_mod_mask_t active = xkb_state_serialize_mods(state, type);
945
946     if (!(match & XKB_STATE_MATCH_NON_EXCLUSIVE) && (active & ~wanted))
947         return 0;
948
949     if (match & XKB_STATE_MATCH_ANY)
950         return !!(active & wanted);
951     else
952         return (active & wanted) == wanted;
953
954     return 0;
955 }
956
957 /**
958  * Returns 1 if the modifiers are active with the specified type(s), 0 if
959  * not, or -1 if any of the modifiers are invalid.
960  */
961 XKB_EXPORT int
962 xkb_state_mod_indices_are_active(struct xkb_state *state,
963                                  enum xkb_state_component type,
964                                  enum xkb_state_match match,
965                                  ...)
966 {
967     va_list ap;
968     xkb_mod_index_t idx = 0;
969     xkb_mod_mask_t wanted = 0;
970     int ret = 0;
971     xkb_mod_index_t num_mods = xkb_keymap_num_mods(state->keymap);
972
973     va_start(ap, match);
974     while (1) {
975         idx = va_arg(ap, xkb_mod_index_t);
976         if (idx == XKB_MOD_INVALID)
977             break;
978         if (idx >= num_mods) {
979             ret = -1;
980             break;
981         }
982         wanted |= (1u << idx);
983     }
984     va_end(ap);
985
986     if (ret == -1)
987         return ret;
988
989     return match_mod_masks(state, type, match, wanted);
990 }
991
992 /**
993  * Returns 1 if the given modifier is active with the specified type(s), 0 if
994  * not, or -1 if the modifier is invalid.
995  */
996 XKB_EXPORT int
997 xkb_state_mod_name_is_active(struct xkb_state *state, const char *name,
998                              enum xkb_state_component type)
999 {
1000     xkb_mod_index_t idx = xkb_keymap_mod_get_index(state->keymap, name);
1001
1002     if (idx == XKB_MOD_INVALID)
1003         return -1;
1004
1005     return xkb_state_mod_index_is_active(state, idx, type);
1006 }
1007
1008 /**
1009  * Returns 1 if the modifiers are active with the specified type(s), 0 if
1010  * not, or -1 if any of the modifiers are invalid.
1011  */
1012 XKB_EXPORT ATTR_NULL_SENTINEL int
1013 xkb_state_mod_names_are_active(struct xkb_state *state,
1014                                enum xkb_state_component type,
1015                                enum xkb_state_match match,
1016                                ...)
1017 {
1018     va_list ap;
1019     xkb_mod_index_t idx = 0;
1020     xkb_mod_mask_t wanted = 0;
1021     int ret = 0;
1022
1023     va_start(ap, match);
1024     while (1) {
1025         const char *str = va_arg(ap, const char *);
1026         if (str == NULL)
1027             break;
1028         idx = xkb_keymap_mod_get_index(state->keymap, str);
1029         if (idx == XKB_MOD_INVALID) {
1030             ret = -1;
1031             break;
1032         }
1033         wanted |= (1u << idx);
1034     }
1035     va_end(ap);
1036
1037     if (ret == -1)
1038         return ret;
1039
1040     return match_mod_masks(state, type, match, wanted);
1041 }
1042
1043 /**
1044  * Returns 1 if the given group is active with the specified type(s), 0 if
1045  * not, or -1 if the group is invalid.
1046  */
1047 XKB_EXPORT int
1048 xkb_state_layout_index_is_active(struct xkb_state *state,
1049                                 xkb_layout_index_t idx,
1050                                 enum xkb_state_component type)
1051 {
1052     int ret = 0;
1053
1054     if (idx >= state->keymap->num_groups)
1055         return -1;
1056
1057     if (type & XKB_STATE_LAYOUT_EFFECTIVE)
1058         ret |= (state->components.group == idx);
1059     if (type & XKB_STATE_LAYOUT_DEPRESSED)
1060         ret |= (state->components.base_group == (int32_t) idx);
1061     if (type & XKB_STATE_LAYOUT_LATCHED)
1062         ret |= (state->components.latched_group == (int32_t) idx);
1063     if (type & XKB_STATE_LAYOUT_LOCKED)
1064         ret |= (state->components.locked_group == (int32_t) idx);
1065
1066     return ret;
1067 }
1068
1069 /**
1070  * Returns 1 if the given modifier is active with the specified type(s), 0 if
1071  * not, or -1 if the modifier is invalid.
1072  */
1073 XKB_EXPORT int
1074 xkb_state_layout_name_is_active(struct xkb_state *state, const char *name,
1075                                 enum xkb_state_component type)
1076 {
1077     xkb_layout_index_t idx = xkb_keymap_layout_get_index(state->keymap, name);
1078
1079     if (idx == XKB_LAYOUT_INVALID)
1080         return -1;
1081
1082     return xkb_state_layout_index_is_active(state, idx, type);
1083 }
1084
1085 /**
1086  * Returns 1 if the given LED is active, 0 if not, or -1 if the LED is invalid.
1087  */
1088 XKB_EXPORT int
1089 xkb_state_led_index_is_active(struct xkb_state *state, xkb_led_index_t idx)
1090 {
1091     if (idx >= darray_size(state->keymap->leds) ||
1092         darray_item(state->keymap->leds, idx).name == XKB_ATOM_NONE)
1093         return -1;
1094
1095     return !!(state->components.leds & (1u << idx));
1096 }
1097
1098 /**
1099  * Returns 1 if the given LED is active, 0 if not, or -1 if the LED is invalid.
1100  */
1101 XKB_EXPORT int
1102 xkb_state_led_name_is_active(struct xkb_state *state, const char *name)
1103 {
1104     xkb_led_index_t idx = xkb_keymap_led_get_index(state->keymap, name);
1105
1106     if (idx == XKB_LED_INVALID)
1107         return -1;
1108
1109     return xkb_state_led_index_is_active(state, idx);
1110 }
1111
1112 static xkb_mod_mask_t
1113 key_get_consumed(struct xkb_state *state, const struct xkb_key *key)
1114 {
1115     const struct xkb_key_type_entry *entry;
1116     xkb_layout_index_t group;
1117
1118     group = xkb_state_key_get_layout(state, key->keycode);
1119     if (group == XKB_LAYOUT_INVALID)
1120         return 0;
1121
1122     entry = get_entry_for_key_state(state, key, group);
1123     if (!entry)
1124         return 0;
1125
1126     return entry->mods.mask & ~entry->preserve.mask;
1127 }
1128
1129 /**
1130  * Tests to see if a modifier is used up by our translation of a
1131  * keycode to keysyms, taking note of the current modifier state and
1132  * the appropriate key type's preserve information, if any. This allows
1133  * the user to mask out the modifier in later processing of the
1134  * modifiers, e.g. when implementing hot keys or accelerators.
1135  *
1136  * See also, for example:
1137  * - XkbTranslateKeyCode(3), mod_rtrn return value, from libX11.
1138  * - gdk_keymap_translate_keyboard_state, consumed_modifiers return value,
1139  *   from gtk+.
1140  */
1141 XKB_EXPORT int
1142 xkb_state_mod_index_is_consumed(struct xkb_state *state, xkb_keycode_t kc,
1143                                 xkb_mod_index_t idx)
1144 {
1145     const struct xkb_key *key = XkbKey(state->keymap, kc);
1146
1147     if (!key || idx >= xkb_keymap_num_mods(state->keymap))
1148         return -1;
1149
1150     return !!((1u << idx) & key_get_consumed(state, key));
1151 }
1152
1153 /**
1154  * Calculates which modifiers should be consumed during key processing,
1155  * and returns the mask with all these modifiers removed.  e.g. if
1156  * given a state of Alt and Shift active for a two-level alphabetic
1157  * key containing plus and equal on the first and second level
1158  * respectively, will return a mask of only Alt, as Shift has been
1159  * consumed by the type handling.
1160  */
1161 XKB_EXPORT xkb_mod_mask_t
1162 xkb_state_mod_mask_remove_consumed(struct xkb_state *state, xkb_keycode_t kc,
1163                                    xkb_mod_mask_t mask)
1164 {
1165     const struct xkb_key *key = XkbKey(state->keymap, kc);
1166
1167     if (!key)
1168         return 0;
1169
1170     return mask & ~key_get_consumed(state, key);
1171 }