Debian Codegraph @

src/state.c

raw
1 /*
2 * For HPND:
3 * Copyright (c) 1993 by Silicon Graphics Computer Systems, Inc.
4 *
5 * For MIT:
6 * Copyright © 2012 Intel Corporation
7 * Copyright © 2012 Ran Benita <[email protected]>
8 *
9 * SPDX-License-Identifier: HPND AND MIT
10 *
11 * Author: Daniel Stone <[email protected]>
12 */
13
14 /*
15 * This is a bastardised version of xkbActions.c from the X server which
16 * does not support, for the moment:
17 * - AccessX sticky/debounce/etc (will come later)
18 * - pointer keys (may come later)
19 * - key redirects (unlikely)
20 * - messages (very unlikely)
21 */
22
23 #include "config.h"
24
25 #include <assert.h>
26 #include <stdint.h>
27
28 #include "xkbcommon/xkbcommon.h"
29 #include "keymap.h"
30 #include "keysym.h"
31 #include "utf8.h"
32
33 struct xkb_filter {
34 union xkb_action action;
35 const struct xkb_key *key;
36 uint32_t priv;
37 bool (*func)(struct xkb_state *state,
38 struct xkb_filter *filter,
39 const struct xkb_key *key,
40 enum xkb_key_direction direction);
41 int refcnt;
42 };
43
44 struct state_components {
45 /* These may be negative, because of -1 group actions. */
46 int32_t base_group; /**< depressed */
47 int32_t latched_group;
48 int32_t locked_group;
49 xkb_layout_index_t group; /**< effective */
50
51 xkb_mod_mask_t base_mods; /**< depressed */
52 xkb_mod_mask_t latched_mods;
53 xkb_mod_mask_t locked_mods;
54 xkb_mod_mask_t mods; /**< effective */
55
56 xkb_led_mask_t leds;
57 };
58
59 struct xkb_state {
60 /*
61 * Before updating the state, we keep a copy of just this struct. This
62 * allows us to report which components of the state have changed.
63 */
64 struct state_components components;
65
66 /*
67 * At each event, we accumulate all the needed modifications to the base
68 * modifiers, and apply them at the end. These keep track of this state.
69 */
70 xkb_mod_mask_t set_mods;
71 xkb_mod_mask_t clear_mods;
72
73 /*
74 * We mustn't clear a base modifier if there's another depressed key
75 * which affects it, e.g. given this sequence
76 * < Left Shift down, Right Shift down, Left Shift Up >
77 * the modifier should still be set. This keeps the count.
78 */
79 int16_t mod_key_count[XKB_MAX_MODS];
80
81 int refcnt;
82 darray(struct xkb_filter) filters;
83 struct xkb_keymap *keymap;
84 };
85
86 static const struct xkb_key_type_entry *
87 get_entry_for_mods(const struct xkb_key_type *type, xkb_mod_mask_t mods)
88 {
89 for (darray_size_t i = 0; i < type->num_entries; i++)
90 if (entry_is_active(&type->entries[i]) &&
91 type->entries[i].mods.mask == mods)
92 return &type->entries[i];
93 return NULL;
94 }
95
96 static const struct xkb_key_type_entry *
97 get_entry_for_key_state(struct xkb_state *state, const struct xkb_key *key,
98 xkb_layout_index_t group)
99 {
100 const struct xkb_key_type* const type = key->groups[group].type;
101 xkb_mod_mask_t active_mods = state->components.mods & type->mods.mask;
102 return get_entry_for_mods(type, active_mods);
103 }
104
105 static inline xkb_level_index_t
106 state_key_get_level(struct xkb_state *state, const struct xkb_key *key,
107 xkb_layout_index_t layout)
108 {
109 if (layout >= key->num_groups)
110 return XKB_LEVEL_INVALID;
111
112 /* If we don't find an explicit match the default is 0. */
113 const struct xkb_key_type_entry* const entry =
114 get_entry_for_key_state(state, key, layout);
115
116 return (entry) ? entry->level : 0;
117 }
118
119 /**
120 * Returns the level to use for the given key and state, or
121 * XKB_LEVEL_INVALID.
122 */
123 xkb_level_index_t
124 xkb_state_key_get_level(struct xkb_state *state, xkb_keycode_t kc,
125 xkb_layout_index_t layout)
126 {
127 const struct xkb_key* const key = XkbKey(state->keymap, kc);
128
129 return (key)
130 ? state_key_get_level(state, key, layout)
131 : XKB_LEVEL_INVALID;
132 }
133
134 static inline xkb_layout_index_t
135 state_key_get_layout(struct xkb_state *state, const struct xkb_key *key)
136 {
137 static_assert(XKB_MAX_GROUPS < INT32_MAX, "Max groups don't fit");
138 return XkbWrapGroupIntoRange((int32_t) state->components.group,
139 key->num_groups,
140 key->out_of_range_group_action,
141 key->out_of_range_group_number);
142 }
143
144 /**
145 * Returns the layout to use for the given key and state, taking
146 * wrapping/clamping/etc into account, or XKB_LAYOUT_INVALID.
147 */
148 xkb_layout_index_t
149 xkb_state_key_get_layout(struct xkb_state *state, xkb_keycode_t kc)
150 {
151 const struct xkb_key* const key = XkbKey(state->keymap, kc);
152
153 if (!key)
154 return XKB_LAYOUT_INVALID;
155
156 return state_key_get_layout(state, key);
157 }
158
159 /* Empty action used for empty levels */
160 static const union xkb_action dummy_action = { .type = ACTION_TYPE_NONE };
161
162 static xkb_action_count_t
163 xkb_key_get_actions(struct xkb_state *state, const struct xkb_key *key,
164 const union xkb_action **actions)
165 {
166 const xkb_layout_index_t layout = state_key_get_layout(state, key);
167 const xkb_level_index_t level = state_key_get_level(state, key, layout);
168 if (level == XKB_LEVEL_INVALID)
169 goto err;
170
171 const xkb_action_count_t count =
172 xkb_keymap_key_get_actions_by_level(state->keymap, key,
173 layout, level, actions);
174 if (!count)
175 goto err;
176
177 return count;
178
179 err:
180 /* Use a dummy action if no corresponding level was found or if it is empty.
181 * This is required e.g. to handle latches properly. */
182 *actions = &dummy_action;
183 return 1;
184 }
185
186 static struct xkb_filter *
187 xkb_filter_new(struct xkb_state *state)
188 {
189 struct xkb_filter *filter = NULL, *iter;
190
191 darray_foreach(iter, state->filters) {
192 if (iter->func)
193 continue;
194 /* Use available slot */
195 filter = iter;
196 break;
197 }
198
199 if (!filter) {
200 /* No available slot: resize the filters array */
201 darray_resize0(state->filters, darray_size(state->filters) + 1);
202 filter = &darray_item(state->filters, darray_size(state->filters) -1);
203 }
204
205 filter->refcnt = 1;
206 return filter;
207 }
208
209 /***====================================================================***/
210
211 enum xkb_filter_result {
212 /*
213 * The event is consumed by the filters.
214 *
215 * An event is always processed by all filters, but any filter can
216 * prevent it from being processed further by consuming it.
217 */
218 XKB_FILTER_CONSUME,
219 /*
220 * The event may continue to be processed as far as this filter is
221 * concerned.
222 */
223 XKB_FILTER_CONTINUE,
224 };
225
226 /* Modify a group component, depending on the ACTION_ABSOLUTE_SWITCH flag */
227 #define apply_group_delta(filter_, state_, component_) \
228 if ((filter_)->action.group.flags & ACTION_ABSOLUTE_SWITCH) \
229 (state_)->components.component_ = (filter_)->action.group.group; \
230 else \
231 (state_)->components.component_ += (filter_)->action.group.group
232
233 static void
234 xkb_filter_group_set_new(struct xkb_state *state, struct xkb_filter *filter)
235 {
236 static_assert(sizeof(state->components.base_group) == sizeof(filter->priv),
237 "Max groups don't fit");
238 filter->priv = state->components.base_group;
239 apply_group_delta(filter, state, base_group);
240 }
241
242 static bool
243 xkb_filter_group_set_func(struct xkb_state *state,
244 struct xkb_filter *filter,
245 const struct xkb_key *key,
246 enum xkb_key_direction direction)
247 {
248 if (key != filter->key) {
249 filter->action.group.flags &= ~ACTION_LOCK_CLEAR;
250 return XKB_FILTER_CONTINUE;
251 }
252
253 if (direction == XKB_KEY_DOWN) {
254 filter->refcnt++;
255 return XKB_FILTER_CONSUME;
256 }
257 else if (--filter->refcnt > 0) {
258 return XKB_FILTER_CONSUME;
259 }
260
261 static_assert(sizeof(state->components.base_group) == sizeof(filter->priv),
262 "Max groups don't fit");
263 state->components.base_group = (int32_t) filter->priv;
264
265 if (filter->action.group.flags & ACTION_LOCK_CLEAR)
266 state->components.locked_group = 0;
267
268 filter->func = NULL;
269 return XKB_FILTER_CONTINUE;
270 }
271
272 static void
273 xkb_filter_group_lock_new(struct xkb_state *state, struct xkb_filter *filter)
274 {
275 if (filter->action.group.flags & ACTION_LOCK_ON_RELEASE) {
276 /*
277 * Lock on key release: do nothing on key press.
278 *
279 * This is a keymap format v2 extension.
280 */
281 return;
282 } else {
283 /* Lock on key press */
284 apply_group_delta(filter, state, locked_group);
285 }
286
287 }
288
289 static bool
290 xkb_filter_group_lock_func(struct xkb_state *state,
291 struct xkb_filter *filter,
292 const struct xkb_key *key,
293 enum xkb_key_direction direction)
294 {
295 if (key != filter->key) {
296 if ((filter->action.group.flags & ACTION_LOCK_ON_RELEASE) &&
297 direction == XKB_KEY_DOWN) {
298 /*
299 * Another key has been pressed after the locking key:
300 * cancel group lock on release.
301 *
302 * This is a keymap v2 extension.
303 */
304 filter->action.group.flags &= ~ACTION_LOCK_ON_RELEASE;
305 }
306 return XKB_FILTER_CONTINUE;
307 }
308
309 if (direction == XKB_KEY_DOWN) {
310 filter->refcnt++;
311 return XKB_FILTER_CONSUME;
312 }
313 if (--filter->refcnt > 0)
314 return XKB_FILTER_CONSUME;
315
316 if (filter->action.group.flags & ACTION_LOCK_ON_RELEASE) {
317 /*
318 * Lock on key release
319 *
320 * This is a keymap v2 extension.
321 */
322 apply_group_delta(filter, state, locked_group);
323 } else {
324 /* Lock on key press: do nothing on key release. */
325 }
326 filter->func = NULL;
327 return XKB_FILTER_CONTINUE;
328 }
329
330 static bool
331 xkb_action_breaks_latch(const union xkb_action *action,
332 enum xkb_internal_action_flags flag,
333 xkb_mod_mask_t mask)
334 {
335 switch (action->type) {
336 case ACTION_TYPE_NONE:
337 case ACTION_TYPE_VOID:
338 case ACTION_TYPE_PTR_BUTTON:
339 case ACTION_TYPE_PTR_LOCK:
340 case ACTION_TYPE_CTRL_SET:
341 case ACTION_TYPE_CTRL_LOCK:
342 case ACTION_TYPE_SWITCH_VT:
343 case ACTION_TYPE_TERMINATE:
344 return true;
345 case ACTION_TYPE_INTERNAL:
346 return (action->internal.flags & flag) &&
347 ((action->internal.clear_latched_mods & mask) == mask);
348 default:
349 {} /* Label followed by declaration requires C23 */
350 /* Ensure to not miss `xkb_action_type` updates */
351 static_assert(ACTION_TYPE_INTERNAL == 18 &&
352 ACTION_TYPE_INTERNAL + 1 == _ACTION_TYPE_NUM_ENTRIES,
353 "Missing action type");
354 return false;
355 }
356 }
357
358 enum xkb_key_latch_state {
359 NO_LATCH = 0,
360 LATCH_KEY_DOWN,
361 LATCH_PENDING,
362 _KEY_LATCH_STATE_NUM_ENTRIES
363 };
364
365 #define MAX_XKB_KEY_LATCH_STATE_LOG2 2
366 #if (_KEY_LATCH_STATE_NUM_ENTRIES > (1 << MAX_XKB_KEY_LATCH_STATE_LOG2)) || \
367 (-XKB_MAX_GROUPS) < (INT32_MIN >> MAX_XKB_KEY_LATCH_STATE_LOG2) || \
368 XKB_MAX_GROUPS > (INT32_MAX >> MAX_XKB_KEY_LATCH_STATE_LOG2)
369 #error "Cannot represent priv field of the group latch filter"
370 #endif
371
372 /* Hold the latch state *and* the group delta */
373 union group_latch_priv {
374 uint32_t priv;
375 struct {
376 /* The type is really: enum xkb_key_latch_state, but it is problematic
377 * on Windows, because it is interpreted as signed and leads to wrong
378 * negative values. */
379 unsigned int latch:MAX_XKB_KEY_LATCH_STATE_LOG2;
380 int32_t group_delta:(32 - MAX_XKB_KEY_LATCH_STATE_LOG2);
381 };
382 };
383
384 static void
385 xkb_filter_group_latch_new(struct xkb_state *state, struct xkb_filter *filter)
386 {
387 const union group_latch_priv priv = {
388 .latch = LATCH_KEY_DOWN,
389 .group_delta = (filter->action.group.flags & ACTION_ABSOLUTE_SWITCH)
390 ? filter->action.group.group - state->components.base_group
391 : filter->action.group.group
392 };
393 filter->priv = priv.priv;
394 /* Like group set */
395 apply_group_delta(filter, state, base_group);
396 }
397
398 static bool
399 xkb_filter_group_latch_func(struct xkb_state *state,
400 struct xkb_filter *filter,
401 const struct xkb_key *key,
402 enum xkb_key_direction direction)
403 {
404 union group_latch_priv priv = {.priv = filter->priv};
405 enum xkb_key_latch_state latch = priv.latch;
406
407 if (direction == XKB_KEY_DOWN) {
408 const union xkb_action *actions = NULL;
409 const xkb_action_count_t count = xkb_key_get_actions(state, key,
410 &actions);
411
412 if (latch == LATCH_KEY_DOWN) {
413 /*
414 * Another key was pressed while we’ve still got the latching key
415 * held down.
416 *
417 * The exact behavior depends on the keymap format version.
418 * It results in either:
419 * • No change.
420 * • Prevent the latch to trigger and keep the base group set by
421 * xkb_filter_group_latch_new(), until the latch key is
422 * released.
423 */
424 if (state->keymap->format == XKB_KEYMAP_FORMAT_TEXT_V1) {
425 /* Keymap v1: unconditionally prevent the latch to trigger. */
426 latch = NO_LATCH;
427 }
428 else {
429 /*
430 * Keymap v2+: prevent the latch to trigger only if some of the
431 * pressed key’s actions breaks latches, mirroring the behavior
432 * in the LATCH_PENDING state.
433 *
434 * This is an extension to the X11 XKB protocol.
435 */
436 for (xkb_action_count_t k = 0; k < count; k++) {
437 if (xkb_action_breaks_latch(&(actions[k]),
438 INTERNAL_BREAKS_GROUP_LATCH,
439 0)) {
440 latch = NO_LATCH;
441 break;
442 }
443 }
444 }
445 }
446 else if (latch == LATCH_PENDING) {
447 /* If this is a new keypress and we're awaiting our single latched
448 * keypress, then either break the latch if any random key is
449 * pressed, or promote it to a lock if it's the same group delta &
450 * flags and latchToLock option is enabled. */
451 for (xkb_action_count_t k = 0; k < count; k++) {
452 if (actions[k].type == ACTION_TYPE_GROUP_LATCH &&
453 actions[k].group.group == filter->action.group.group &&
454 actions[k].group.flags == filter->action.group.flags) {
455 filter->action = actions[k];
456 if (filter->action.group.flags & ACTION_LATCH_TO_LOCK &&
457 filter->action.group.group != 0) {
458 /* Promote to lock */
459 filter->action.type = ACTION_TYPE_GROUP_LOCK;
460 filter->func = xkb_filter_group_lock_func;
461 xkb_filter_group_lock_new(state, filter);
462 state->components.latched_group -= priv.group_delta;
463 filter->key = key;
464 /* XXX beep beep! */
465 return XKB_FILTER_CONSUME;
466 }
467 /* Do nothing if `latchToLock` option is not activated; if
468 * the latch is not broken by the following actions and the
469 * key is not consumed, then another latch filter will be
470 * created.
471 */
472 continue;
473 }
474 else if (xkb_action_breaks_latch(&(actions[k]),
475 INTERNAL_BREAKS_GROUP_LATCH,
476 0)) {
477 /* Breaks the latch */
478 state->components.latched_group -= priv.group_delta;
479 filter->func = NULL;
480 return XKB_FILTER_CONTINUE;
481 }
482 }
483 }
484 else {
485 /* Ignore press in NO_LATCH state */
486 assert(latch == NO_LATCH);
487 }
488 }
489 else if (direction == XKB_KEY_UP && key == filter->key) {
490 /* Our key got released. If we've set it to clear locks, and we
491 * currently have a group locked, then release it and
492 * don't actually latch. Else we've actually hit the latching
493 * stage, so set PENDING and move our group from base to
494 * latched. */
495 if ((filter->action.group.flags & ACTION_LOCK_CLEAR) &&
496 state->components.locked_group) {
497 if (latch == LATCH_PENDING)
498 state->components.latched_group -= priv.group_delta;
499 else
500 state->components.base_group -= priv.group_delta;
501 state->components.locked_group = 0;
502 filter->func = NULL;
503 }
504 /* Broken latch */
505 else if (latch == NO_LATCH) {
506 state->components.base_group -= priv.group_delta;
507 filter->func = NULL;
508 }
509 /* We may already have reached the latch state if pressing the
510 * key multiple times without latch-to-lock enabled. */
511 else if (latch == LATCH_KEY_DOWN) {
512 latch = LATCH_PENDING;
513 /* Switch from set to latch */
514 state->components.base_group -= priv.group_delta;
515 state->components.latched_group += priv.group_delta;
516 /* XXX beep beep! */
517 }
518 }
519 else {
520 /* Ignore release of other keys */
521 }
522
523 priv.latch = latch;
524 filter->priv = priv.priv;
525
526 return XKB_FILTER_CONTINUE;
527 }
528
529 static void
530 xkb_filter_mod_set_new(struct xkb_state *state, struct xkb_filter *filter)
531 {
532 const enum xkb_action_flags unlock = ACTION_UNLOCK_ON_PRESS
533 | ACTION_LOCK_CLEAR;
534 if ((filter->action.mods.flags & unlock) == unlock) {
535 /*
536 * Unlock on press
537 *
538 * This is a keymap v2 extension.
539 */
540 filter->priv = filter->action.mods.mods.mask
541 & ~state->components.locked_mods;
542 state->components.locked_mods &= ~filter->action.mods.mods.mask;
543 } else {
544 filter->priv = filter->action.mods.mods.mask;
545 }
546
547 state->set_mods |= (xkb_mod_mask_t) filter->priv;
548 }
549
550 static bool
551 xkb_filter_mod_set_func(struct xkb_state *state,
552 struct xkb_filter *filter,
553 const struct xkb_key *key,
554 enum xkb_key_direction direction)
555 {
556 if (key != filter->key) {
557 filter->action.mods.flags &= ~ACTION_LOCK_CLEAR;
558 return XKB_FILTER_CONTINUE;
559 }
560
561 if (direction == XKB_KEY_DOWN) {
562 filter->refcnt++;
563 return XKB_FILTER_CONSUME;
564 }
565 else if (--filter->refcnt > 0) {
566 return XKB_FILTER_CONSUME;
567 }
568
569 state->clear_mods |= (xkb_mod_mask_t) filter->priv;
570 const enum xkb_action_flags unlock = ACTION_UNLOCK_ON_PRESS
571 | ACTION_LOCK_CLEAR;
572 if ((filter->action.mods.flags & unlock) == ACTION_LOCK_CLEAR)
573 state->components.locked_mods &= ~filter->action.mods.mods.mask;
574
575 filter->func = NULL;
576 return XKB_FILTER_CONTINUE;
577 }
578
579 static void
580 xkb_filter_mod_lock_new(struct xkb_state *state, struct xkb_filter *filter)
581 {
582 filter->priv = (state->components.locked_mods &
583 filter->action.mods.mods.mask);
584
585 if (filter->priv && (filter->action.mods.flags & ACTION_UNLOCK_ON_PRESS)) {
586 /*
587 * Some of the target modifiers were locked before key press: unlock.
588 *
589 * This is a keymap v2 extension: unlock-on-press.
590 */
591 if (!(filter->action.mods.flags & ACTION_LOCK_NO_UNLOCK))
592 state->components.locked_mods &= ~filter->priv;
593 /* No further action: cancel filter */
594 filter->func = NULL;
595 } else {
596 /* Set base mods; lock mods if relevant (XKB 1.0 spec) */
597 state->set_mods |= filter->action.mods.mods.mask;
598 if (!(filter->action.mods.flags & ACTION_LOCK_NO_LOCK))
599 state->components.locked_mods |= filter->action.mods.mods.mask;
600 }
601 }
602
603 static bool
604 xkb_filter_mod_lock_func(struct xkb_state *state,
605 struct xkb_filter *filter,
606 const struct xkb_key *key,
607 enum xkb_key_direction direction)
608 {
609 if (key != filter->key)
610 return XKB_FILTER_CONTINUE;
611
612 if (direction == XKB_KEY_DOWN) {
613 filter->refcnt++;
614 return XKB_FILTER_CONSUME;
615 }
616 if (--filter->refcnt > 0)
617 return XKB_FILTER_CONSUME;
618
619 state->clear_mods |= filter->action.mods.mods.mask;
620 if (!(filter->action.mods.flags & ACTION_LOCK_NO_UNLOCK))
621 state->components.locked_mods &= ~filter->priv;
622
623 filter->func = NULL;
624 return XKB_FILTER_CONTINUE;
625 }
626
627 static void
628 xkb_filter_mod_latch_new(struct xkb_state *state, struct xkb_filter *filter)
629 {
630 /* Latch-on-press + clear-locks imply unlock-on-press */
631 const enum xkb_action_flags unlockOnPress = ACTION_UNLOCK_ON_PRESS
632 | ACTION_LATCH_ON_PRESS;
633
634 if ((filter->action.mods.flags & ACTION_LOCK_CLEAR) &&
635 (filter->action.mods.flags & unlockOnPress) &&
636 (state->components.locked_mods & filter->action.mods.mods.mask) ==
637 filter->action.mods.mods.mask) {
638 /*
639 * Unlock on press
640 *
641 * This is a keymap v2 extension: clear locks and do not latch.
642 */
643 state->components.locked_mods &= ~filter->action.mods.mods.mask;
644 filter->func = NULL;
645 } else if (filter->action.mods.flags & ACTION_LATCH_ON_PRESS) {
646 /*
647 * Latch on key press
648 *
649 * This is a keymap format v2 extension.
650 */
651 filter->priv = LATCH_PENDING;
652 state->components.latched_mods |= filter->action.mods.mods.mask;
653 /* XXX beep beep! */
654 } else {
655 /* XKB standard latch action */
656 filter->priv = LATCH_KEY_DOWN;
657 state->set_mods |= filter->action.mods.mods.mask;
658 }
659 }
660
661 static bool
662 xkb_filter_mod_latch_func(struct xkb_state *state,
663 struct xkb_filter *filter,
664 const struct xkb_key *key,
665 enum xkb_key_direction direction)
666 {
667 enum xkb_key_latch_state latch = filter->priv;
668
669 if (direction == XKB_KEY_DOWN) {
670 const union xkb_action *actions = NULL;
671 const xkb_action_count_t count = xkb_key_get_actions(state, key,
672 &actions);
673
674 if (latch == LATCH_KEY_DOWN) {
675 /*
676 * Another key was pressed while we’ve still got the latching key
677 * held down.
678 *
679 * The exact behavior depends on the keymap format version.
680 * It results in either:
681 * • No change.
682 * • Prevent the latch to trigger and keep the base modifiers set
683 * by xkb_filter_mod_latch_new(), until the latch key is released.
684 */
685 if (state->keymap->format == XKB_KEYMAP_FORMAT_TEXT_V1) {
686 /* Keymap v1: unconditionally prevent the latch to trigger. */
687 latch = NO_LATCH;
688 }
689 else {
690 /*
691 * Keymap v2+: prevent the latch to trigger only if some of the
692 * pressed key’s actions breaks latches, mirroring the behavior
693 * in the LATCH_PENDING state.
694 *
695 * This is an extension to the X11 XKB protocol.
696 */
697 for (xkb_action_count_t k = 0; k < count; k++) {
698 if (xkb_action_breaks_latch(&(actions[k]),
699 INTERNAL_BREAKS_MOD_LATCH,
700 filter->action.mods.mods.mask)) {
701 latch = NO_LATCH;
702 break;
703 }
704 }
705 }
706 }
707 else if (latch == LATCH_PENDING) {
708 /* If this is a new keypress and we're awaiting our single latched
709 * keypress, then either break the latch if any random key is pressed,
710 * or promote it to a lock or plain base set if it's the same
711 * modifier. */
712 for (xkb_action_count_t k = 0; k < count; k++) {
713 if (actions[k].type == ACTION_TYPE_MOD_LATCH &&
714 actions[k].mods.flags == filter->action.mods.flags &&
715 actions[k].mods.mods.mask == filter->action.mods.mods.mask) {
716 filter->action = actions[k];
717 if (filter->action.mods.flags & ACTION_LATCH_TO_LOCK) {
718 /* Mutate the action to LockMods() */
719 filter->action.type = ACTION_TYPE_MOD_LOCK;
720 filter->func = xkb_filter_mod_lock_func;
721 xkb_filter_mod_lock_new(state, filter);
722 }
723 else {
724 /* Mutate the action to SetMods() */
725 filter->action.type = ACTION_TYPE_MOD_SET;
726 filter->func = xkb_filter_mod_set_func;
727 xkb_filter_mod_set_new(state, filter);
728 }
729 filter->key = key;
730 /* Clear latches */
731 state->components.latched_mods &= ~filter->action.mods.mods.mask;
732 /* XXX beep beep! */
733 return XKB_FILTER_CONSUME;
734 }
735 else if (xkb_action_breaks_latch(&(actions[k]),
736 INTERNAL_BREAKS_MOD_LATCH,
737 filter->action.mods.mods.mask)) {
738 /* XXX: This may be totally broken, we might need to break the
739 * latch in the next run after this press? */
740 state->components.latched_mods &= ~filter->action.mods.mods.mask;
741 filter->func = NULL;
742 return XKB_FILTER_CONTINUE;
743 }
744 }
745 }
746 else {
747 /* Ignore press in NO_LATCH state */
748 assert(latch == NO_LATCH);
749 }
750 }
751 else if (direction == XKB_KEY_UP && key == filter->key) {
752 /* Our key got released. If we’ve set it to clear locks, and we
753 * currently have the same modifiers locked, then release them and
754 * don't actually latch. Else we’ve actually hit the latching
755 * stage, so set PENDING and move our modifier from base to
756 * latched. */
757
758 /* Latch-on-press + clear-locks imply unlock-on-press */
759 const enum xkb_action_flags unlockOnPress = ACTION_UNLOCK_ON_PRESS
760 | ACTION_LATCH_ON_PRESS;
761
762 if ((filter->action.mods.flags & ACTION_LOCK_CLEAR) &&
763 !(filter->action.mods.flags & unlockOnPress) &&
764 (state->components.locked_mods & filter->action.mods.mods.mask) ==
765 filter->action.mods.mods.mask) {
766 /* XXX: We might be a bit overenthusiastic about clearing
767 * mods other filters have set here? */
768 if (latch == LATCH_PENDING)
769 state->components.latched_mods &=
770 ~filter->action.mods.mods.mask;
771 else
772 state->clear_mods |= filter->action.mods.mods.mask;
773 state->components.locked_mods &= ~filter->action.mods.mods.mask;
774 filter->func = NULL;
775 }
776 else if (latch == NO_LATCH) {
777 /* Broken latch */
778 state->clear_mods |= filter->action.mods.mods.mask;
779 filter->func = NULL;
780 }
781 else if (!(filter->action.mods.flags & ACTION_LATCH_ON_PRESS)) {
782 latch = LATCH_PENDING;
783 state->clear_mods |= filter->action.mods.mods.mask;
784 state->components.latched_mods |= filter->action.mods.mods.mask;
785 /* XXX beep beep! */
786 }
787 }
788 else {
789 /* Ignore release of other keys */
790 }
791
792 filter->priv = latch;
793
794 return XKB_FILTER_CONTINUE;
795 }
796
797 static const struct {
798 void (*new)(struct xkb_state *state, struct xkb_filter *filter);
799 bool (*func)(struct xkb_state *state, struct xkb_filter *filter,
800 const struct xkb_key *key, enum xkb_key_direction direction);
801 } filter_action_funcs[_ACTION_TYPE_NUM_ENTRIES] = {
802 [ACTION_TYPE_MOD_SET] = { xkb_filter_mod_set_new,
803 xkb_filter_mod_set_func },
804 [ACTION_TYPE_MOD_LATCH] = { xkb_filter_mod_latch_new,
805 xkb_filter_mod_latch_func },
806 [ACTION_TYPE_MOD_LOCK] = { xkb_filter_mod_lock_new,
807 xkb_filter_mod_lock_func },
808 [ACTION_TYPE_GROUP_SET] = { xkb_filter_group_set_new,
809 xkb_filter_group_set_func },
810 [ACTION_TYPE_GROUP_LATCH] = { xkb_filter_group_latch_new,
811 xkb_filter_group_latch_func },
812 [ACTION_TYPE_GROUP_LOCK] = { xkb_filter_group_lock_new,
813 xkb_filter_group_lock_func },
814 };
815
816 /**
817 * Applies any relevant filters to the key, first from the list of filters
818 * that are currently active, then if no filter has claimed the key, possibly
819 * apply a new filter from the key action.
820 */
821 static void
822 xkb_filter_apply_all(struct xkb_state *state,
823 const struct xkb_key *key,
824 enum xkb_key_direction direction)
825 {
826 /* First run through all the currently active filters and see if any of
827 * them have consumed this event. */
828 bool consumed = false;
829 struct xkb_filter *filter;
830 darray_foreach(filter, state->filters) {
831 if (!filter->func)
832 continue;
833
834 if (filter->func(state, filter, key, direction) == XKB_FILTER_CONSUME)
835 consumed = true;
836 }
837 if (consumed || direction == XKB_KEY_UP)
838 return;
839
840 /* No filter consumed this event, so proceed with the key actions */
841 const union xkb_action *actions = NULL;
842 const xkb_action_count_t count = xkb_key_get_actions(state, key, &actions);
843
844 /*
845 * Process actions sequentially.
846 *
847 * NOTE: We rely on the parser to disallow multiple modifier or group
848 * actions (see `CheckMultipleActionsCategories`). Allowing multiple such
849 * actions requires a refactor of the state handling.
850 */
851 for (xkb_action_count_t k = 0; k < count; k++) {
852 /*
853 * It's possible for the keymap to set action->type explicitly, like so:
854 * interpret XF86_Next_VMode {
855 * action = Private(type=0x86, data="+VMode");
856 * };
857 * We don't handle those.
858 */
859 if (actions[k].type >= _ACTION_TYPE_NUM_ENTRIES)
860 continue;
861
862 /* Go to next action if no corresponding action handler */
863 if (!filter_action_funcs[actions[k].type].new)
864 continue;
865
866 /* Add a new filter and run the corresponding initial action */
867 filter = xkb_filter_new(state);
868 filter->key = key;
869 filter->func = filter_action_funcs[actions[k].type].func;
870 filter->action = actions[k];
871 filter_action_funcs[actions[k].type].new(state, filter);
872 }
873 }
874
875 struct xkb_state *
876 xkb_state_new(struct xkb_keymap *keymap)
877 {
878 struct xkb_state* restrict const state = calloc(1, sizeof(*state));
879 if (!state)
880 return NULL;
881
882 state->refcnt = 1;
883 state->keymap = xkb_keymap_ref(keymap);
884
885 return state;
886 }
887
888 struct xkb_state *
889 xkb_state_ref(struct xkb_state *state)
890 {
891 assert(state->refcnt > 0);
892 state->refcnt++;
893 return state;
894 }
895
896 void
897 xkb_state_unref(struct xkb_state *state)
898 {
899 assert(!state || state->refcnt > 0);
900 if (!state || --state->refcnt > 0)
901 return;
902
903 xkb_keymap_unref(state->keymap);
904 darray_free(state->filters);
905 free(state);
906 }
907
908 struct xkb_keymap *
909 xkb_state_get_keymap(struct xkb_state *state)
910 {
911 return state->keymap;
912 }
913
914 /**
915 * Update the LED state to match the rest of the xkb_state.
916 */
917 static void
918 xkb_state_led_update_all(struct xkb_state *state)
919 {
920 xkb_led_index_t idx;
921 const struct xkb_led *led;
922
923 state->components.leds = 0;
924
925 xkb_leds_enumerate(idx, led, state->keymap) {
926
927 if (led->which_mods != 0 && led->mods.mask != 0) {
928 xkb_mod_mask_t mod_mask = 0;
929 if (led->which_mods & XKB_STATE_MODS_EFFECTIVE)
930 mod_mask |= state->components.mods;
931 if (led->which_mods & XKB_STATE_MODS_DEPRESSED)
932 mod_mask |= state->components.base_mods;
933 if (led->which_mods & XKB_STATE_MODS_LATCHED)
934 mod_mask |= state->components.latched_mods;
935 if (led->which_mods & XKB_STATE_MODS_LOCKED)
936 mod_mask |= state->components.locked_mods;
937
938 if (led->mods.mask & mod_mask) {
939 state->components.leds |= (UINT32_C(1) << idx);
940 continue;
941 }
942 }
943
944 if (led->which_groups != 0) {
945 if (likely(led->groups) != 0) {
946 xkb_layout_mask_t group_mask = 0;
947 /* Effective and locked groups have been brought into range */
948 assert(state->components.group < XKB_MAX_GROUPS);
949 assert(state->components.locked_group >= 0 &&
950 state->components.locked_group < XKB_MAX_GROUPS);
951 /* Effective and locked groups are used as mask */
952 if (led->which_groups & XKB_STATE_LAYOUT_EFFECTIVE)
953 group_mask |= (UINT32_C(1) << state->components.group);
954 if (led->which_groups & XKB_STATE_LAYOUT_LOCKED)
955 group_mask |= (UINT32_C(1) << state->components.locked_group);
956 /* Base and latched groups only have to be non-zero */
957 if ((led->which_groups & XKB_STATE_LAYOUT_DEPRESSED) &&
958 state->components.base_group != 0)
959 group_mask |= led->groups;
960 if ((led->which_groups & XKB_STATE_LAYOUT_LATCHED) &&
961 state->components.latched_group != 0)
962 group_mask |= led->groups;
963
964 if (led->groups & group_mask) {
965 state->components.leds |= (UINT32_C(1) << idx);
966 continue;
967 }
968 } else {
969 /* Special case for Base and latched groups */
970 if (((led->which_groups & XKB_STATE_LAYOUT_DEPRESSED) &&
971 state->components.base_group == 0) ||
972 ((led->which_groups & XKB_STATE_LAYOUT_LATCHED) &&
973 state->components.latched_group == 0)) {
974 state->components.leds |= (UINT32_C(1) << idx);
975 continue;
976 }
977 }
978 }
979
980 if (led->ctrls & state->keymap->enabled_ctrls) {
981 state->components.leds |= (UINT32_C(1) << idx);
982 continue;
983 }
984 }
985 }
986
987 /**
988 * Calculates the derived state (effective mods/group and LEDs) from an
989 * up-to-date xkb_state.
990 */
991 static void
992 xkb_state_update_derived(struct xkb_state *state)
993 {
994 xkb_layout_index_t wrapped;
995
996 state->components.mods = (state->components.base_mods |
997 state->components.latched_mods |
998 state->components.locked_mods);
999
1000 /* TODO: Use groups_wrap control instead of always RANGE_WRAP. */
1001
1002 /* Lock group must be adjusted, but not base nor latched groups */
1003 wrapped = XkbWrapGroupIntoRange(state->components.locked_group,
1004 state->keymap->num_groups,
1005 RANGE_WRAP, 0);
1006 static_assert(XKB_MAX_GROUPS < INT32_MAX, "Max groups don't fit");
1007 state->components.locked_group =
1008 (int32_t) (wrapped == XKB_LAYOUT_INVALID ? 0 : wrapped);
1009
1010 /* Effective group must be adjusted */
1011 wrapped = XkbWrapGroupIntoRange(state->components.base_group +
1012 state->components.latched_group +
1013 state->components.locked_group,
1014 state->keymap->num_groups,
1015 RANGE_WRAP, 0);
1016 state->components.group =
1017 (wrapped == XKB_LAYOUT_INVALID ? 0 : wrapped);
1018
1019 xkb_state_led_update_all(state);
1020 }
1021
1022 static enum xkb_state_component
1023 get_state_component_changes(const struct state_components *a,
1024 const struct state_components *b)
1025 {
1026 xkb_mod_mask_t mask = 0;
1027
1028 if (a->group != b->group)
1029 mask |= XKB_STATE_LAYOUT_EFFECTIVE;
1030 if (a->base_group != b->base_group)
1031 mask |= XKB_STATE_LAYOUT_DEPRESSED;
1032 if (a->latched_group != b->latched_group)
1033 mask |= XKB_STATE_LAYOUT_LATCHED;
1034 if (a->locked_group != b->locked_group)
1035 mask |= XKB_STATE_LAYOUT_LOCKED;
1036 if (a->mods != b->mods)
1037 mask |= XKB_STATE_MODS_EFFECTIVE;
1038 if (a->base_mods != b->base_mods)
1039 mask |= XKB_STATE_MODS_DEPRESSED;
1040 if (a->latched_mods != b->latched_mods)
1041 mask |= XKB_STATE_MODS_LATCHED;
1042 if (a->locked_mods != b->locked_mods)
1043 mask |= XKB_STATE_MODS_LOCKED;
1044 if (a->leds != b->leds)
1045 mask |= XKB_STATE_LEDS;
1046
1047 return mask;
1048 }
1049
1050 /**
1051 * Given a particular key event, updates the state structure to reflect the
1052 * new modifiers.
1053 */
1054 enum xkb_state_component
1055 xkb_state_update_key(struct xkb_state *state, xkb_keycode_t kc,
1056 enum xkb_key_direction direction)
1057 {
1058 const struct xkb_key* const key = XkbKey(state->keymap, kc);
1059 if (!key)
1060 return 0;
1061
1062 const struct state_components prev_components = state->components;
1063
1064 state->set_mods = 0;
1065 state->clear_mods = 0;
1066
1067 xkb_filter_apply_all(state, key, direction);
1068
1069 xkb_mod_index_t i;
1070 xkb_mod_mask_t bit;
1071 for (i = 0, bit = 1; state->set_mods; i++, bit <<= 1) {
1072 if (state->set_mods & bit) {
1073 state->mod_key_count[i]++;
1074 state->components.base_mods |= bit;
1075 state->set_mods &= ~bit;
1076 }
1077 }
1078
1079 for (i = 0, bit = 1; state->clear_mods; i++, bit <<= 1) {
1080 if (state->clear_mods & bit) {
1081 state->mod_key_count[i]--;
1082 if (state->mod_key_count[i] <= 0) {
1083 state->components.base_mods &= ~bit;
1084 state->mod_key_count[i] = 0;
1085 }
1086 state->clear_mods &= ~bit;
1087 }
1088 }
1089
1090 xkb_state_update_derived(state);
1091
1092 return get_state_component_changes(&prev_components, &state->components);
1093 }
1094
1095 /* We need fake keys for `update_latch_modifiers` and `update_latch_group`.
1096 * These keys must have at least one level in order to break latches. We need 2
1097 * keys with specific actions in order to update group/mod latches without
1098 * affecting each other. */
1099 static struct xkb_key_type_entry synthetic_key_level_entry = { 0 };
1100 static struct xkb_key_type synthetic_key_type = {
1101 .num_entries = 1,
1102 .num_levels = 1,
1103 .entries = &synthetic_key_level_entry
1104 };
1105 static const struct xkb_key synthetic_key = { 0 };
1106
1107 /* Transcription from xserver: XkbLatchModifiers */
1108 static void
1109 update_latch_modifiers(struct xkb_state *state,
1110 xkb_mod_mask_t mask, xkb_mod_mask_t latches)
1111 {
1112 /* Clear affected latched modifiers */
1113 const xkb_mod_mask_t clear = mask & ~latches;
1114 state->components.latched_mods &= ~clear;
1115
1116 /* Clear any pending latch to locks using ad hoc action:
1117 * only affect corresponding modifier latches and no group latch. */
1118 struct xkb_level synthetic_key_level_break_mod_latch = {
1119 .num_syms = 0,
1120 .num_actions = 1,
1121 .upper = XKB_KEY_NoSymbol,
1122 .s.sym = XKB_KEY_NoSymbol,
1123 .a.action.internal = {
1124 .type = ACTION_TYPE_INTERNAL,
1125 .flags = INTERNAL_BREAKS_MOD_LATCH,
1126 .clear_latched_mods = clear
1127 }
1128 };
1129 struct xkb_group synthetic_key_group_break_mod_latch = {
1130 .type = &synthetic_key_type,
1131 .levels = &synthetic_key_level_break_mod_latch
1132 };
1133 const struct xkb_key synthetic_key_break_mod_latch = {
1134 .num_groups = 1,
1135 .groups = &synthetic_key_group_break_mod_latch
1136 };
1137 xkb_filter_apply_all(state, &synthetic_key_break_mod_latch, XKB_KEY_DOWN);
1138
1139 /* Finally set the latched mods by simulate tapping a key with the
1140 * corresponding action */
1141 const struct xkb_key* const key = &synthetic_key;
1142 const union xkb_action latch_mods = {
1143 .mods = {
1144 .type = ACTION_TYPE_MOD_LATCH,
1145 .mods = { .mask = mask & latches },
1146 .flags = 0,
1147 },
1148 };
1149 struct xkb_filter* const filter = xkb_filter_new(state);
1150 filter->key = key;
1151 filter->func = xkb_filter_mod_latch_func;
1152 filter->action = latch_mods;
1153 xkb_filter_mod_latch_new(state, filter);
1154 /* We added the filter manually, so only fire “up” event */
1155 xkb_filter_mod_latch_func(state, filter, key, XKB_KEY_UP);
1156 }
1157
1158 /* Transcription from xserver: XkbLatchGroup */
1159 static void
1160 update_latch_group(struct xkb_state *state, int32_t group)
1161 {
1162 /* Clear any pending latch to locks. */
1163 static struct xkb_level synthetic_key_level_break_group_latch = {
1164 .num_syms = 0,
1165 .num_actions = 1,
1166 .upper = XKB_KEY_NoSymbol,
1167 .s.sym = XKB_KEY_NoSymbol,
1168 .a.action.internal = {
1169 .type = ACTION_TYPE_INTERNAL,
1170 .flags = INTERNAL_BREAKS_GROUP_LATCH,
1171 .clear_latched_mods = 0
1172 }
1173 };
1174 static struct xkb_group synthetic_key_group_break_group_latch = {
1175 .type = &synthetic_key_type,
1176 .levels = &synthetic_key_level_break_group_latch
1177 };
1178 static const struct xkb_key synthetic_key_break_group_latch = {
1179 .num_groups = 1,
1180 .groups = &synthetic_key_group_break_group_latch
1181 };
1182 xkb_filter_apply_all(state, &synthetic_key_break_group_latch, XKB_KEY_DOWN);
1183
1184 /* Simulate tapping a key with a group latch action, but in isolation: i.e.
1185 * without affecting the other filters. */
1186 const struct xkb_key* const key = &synthetic_key;
1187 const union xkb_action latch_group = {
1188 .group = {
1189 .type = ACTION_TYPE_GROUP_LATCH,
1190 .flags = ACTION_ABSOLUTE_SWITCH,
1191 .group = group,
1192 },
1193 };
1194 struct xkb_filter* const filter = xkb_filter_new(state);
1195 filter->key = key;
1196 filter->func = xkb_filter_group_latch_func;
1197 filter->action = latch_group;
1198 xkb_filter_group_latch_new(state, filter);
1199 /* We added the filter manually, so only fire “up” event */
1200 xkb_filter_group_latch_func(state, filter, key, XKB_KEY_UP);
1201 }
1202
1203 /**
1204 * Compute the resolved effective mask of an arbitrary input.
1205 *
1206 * Contrary to `mod_mask_get_effective`, it resolves only modifiers not present
1207 * in the canonical mask, so that it enables `xkb_state_serialize_mods` to
1208 * round trip via `xkb_state_update_mask`.
1209 */
1210 static inline xkb_mod_mask_t
1211 resolve_to_canonical_mods(struct xkb_keymap *keymap, xkb_mod_mask_t mods)
1212 {
1213 return
1214 /*
1215 * Keep canonical modifier mask.
1216 * It contains either real modifiers or canonical virtual modifiers.
1217 */
1218 (mods & keymap->canonical_state_mask) |
1219 /* Resolve other modifiers */
1220 mod_mask_get_effective(keymap,
1221 mods & ~keymap->canonical_state_mask);
1222 }
1223
1224 enum xkb_state_component
1225 xkb_state_update_latched_locked(struct xkb_state *state,
1226 xkb_mod_mask_t affect_latched_mods,
1227 xkb_mod_mask_t latched_mods,
1228 bool affect_latched_layout,
1229 int32_t latched_layout,
1230 xkb_mod_mask_t affect_locked_mods,
1231 xkb_mod_mask_t locked_mods,
1232 bool affect_locked_layout,
1233 int32_t locked_layout)
1234 {
1235 const struct state_components prev_components = state->components;
1236
1237 /* Update locks */
1238 affect_locked_mods =
1239 resolve_to_canonical_mods(state->keymap, affect_locked_mods);
1240 if (affect_locked_mods) {
1241 locked_mods = resolve_to_canonical_mods(state->keymap, locked_mods);
1242 state->components.locked_mods &= ~affect_locked_mods;
1243 state->components.locked_mods |= locked_mods & affect_locked_mods;
1244 }
1245 if (affect_locked_layout) {
1246 state->components.locked_group = locked_layout;
1247 }
1248
1249 /* Update latches */
1250 affect_latched_mods =
1251 resolve_to_canonical_mods(state->keymap, affect_latched_mods);
1252 if (affect_latched_mods) {
1253 latched_mods = resolve_to_canonical_mods(state->keymap, latched_mods);
1254 update_latch_modifiers(state, affect_latched_mods, latched_mods);
1255 }
1256 if (affect_latched_layout) {
1257 update_latch_group(state, latched_layout);
1258 }
1259
1260 xkb_state_update_derived(state);
1261 return get_state_component_changes(&prev_components, &state->components);
1262 }
1263
1264 /**
1265 * Updates the state from a set of explicit masks as gained from
1266 * xkb_state_serialize_mods and xkb_state_serialize_groups. As noted in the
1267 * documentation for these functions in xkbcommon.h, this round-trip is
1268 * lossy, and should only be used to update a slave state mirroring the
1269 * master, e.g. in a client/server window system.
1270 */
1271 enum xkb_state_component
1272 xkb_state_update_mask(struct xkb_state *state,
1273 xkb_mod_mask_t base_mods,
1274 xkb_mod_mask_t latched_mods,
1275 xkb_mod_mask_t locked_mods,
1276 xkb_layout_index_t base_group,
1277 xkb_layout_index_t latched_group,
1278 xkb_layout_index_t locked_group)
1279 {
1280 const struct state_components prev_components = state->components;
1281
1282 /*
1283 * Make sure the mods are fully resolved - since we get arbitrary
1284 * input, they might not be.
1285 *
1286 * It might seem more reasonable to do this only for components.mods
1287 * in xkb_state_update_derived(), rather than for each component
1288 * separately. That would allow to distinguish between "really"
1289 * depressed mods (would be in MODS_DEPRESSED) and indirectly
1290 * depressed to to a mapping (would only be in MODS_EFFECTIVE).
1291 * However, the traditional behavior of xkb_state_update_key() is that
1292 * if a vmod is depressed, its mappings are depressed with it; so we're
1293 * expected to do the same here. Also, LEDs (usually) look if a real
1294 * mod is locked, not just effective; otherwise it won't be lit.
1295 */
1296 state->components.base_mods =
1297 resolve_to_canonical_mods(state->keymap, base_mods);
1298 state->components.latched_mods =
1299 resolve_to_canonical_mods(state->keymap, latched_mods);
1300 state->components.locked_mods =
1301 resolve_to_canonical_mods(state->keymap, locked_mods);
1302
1303 static_assert(XKB_MAX_GROUPS < INT32_MAX, "Max groups don't fit");
1304 state->components.base_group = (int32_t) base_group;
1305 state->components.latched_group = (int32_t) latched_group;
1306 state->components.locked_group = (int32_t) locked_group;
1307
1308 xkb_state_update_derived(state);
1309
1310 return get_state_component_changes(&prev_components, &state->components);
1311 }
1312
1313 /*
1314 * https://www.x.org/releases/current/doc/kbproto/xkbproto.html#Interpreting_the_Lock_Modifier
1315 */
1316 static bool
1317 should_do_caps_transformation(struct xkb_state *state, xkb_keycode_t kc)
1318 {
1319 return
1320 xkb_state_mod_index_is_active(state, XKB_MOD_INDEX_CAPS,
1321 XKB_STATE_MODS_EFFECTIVE) > 0 &&
1322 xkb_state_mod_index_is_consumed(state, kc, XKB_MOD_INDEX_CAPS) == 0;
1323 }
1324
1325 /*
1326 * https://www.x.org/releases/current/doc/kbproto/xkbproto.html#Interpreting_the_Control_Modifier
1327 */
1328 static bool
1329 should_do_ctrl_transformation(struct xkb_state *state, xkb_keycode_t kc)
1330 {
1331 return
1332 xkb_state_mod_index_is_active(state, XKB_MOD_INDEX_CTRL,
1333 XKB_STATE_MODS_EFFECTIVE) > 0 &&
1334 xkb_state_mod_index_is_consumed(state, kc, XKB_MOD_INDEX_CTRL) == 0;
1335 }
1336
1337 /**
1338 * Provides the symbols to use for the given key and state. Returns the
1339 * number of symbols pointed to in syms_out.
1340 */
1341 int
1342 xkb_state_key_get_syms(struct xkb_state *state, xkb_keycode_t kc,
1343 const xkb_keysym_t **syms_out)
1344 {
1345 const xkb_layout_index_t layout = xkb_state_key_get_layout(state, kc);
1346 if (layout == XKB_LAYOUT_INVALID)
1347 goto err;
1348
1349 const xkb_level_index_t level = xkb_state_key_get_level(state, kc, layout);
1350 if (level == XKB_LEVEL_INVALID)
1351 goto err;
1352
1353 const struct xkb_key* const key = XkbKey(state->keymap, kc);
1354
1355 if (!key)
1356 goto err;
1357
1358 const struct xkb_level* const leveli =
1359 xkb_keymap_key_get_level(state->keymap, key, layout, level);
1360
1361 if (!leveli)
1362 goto err;
1363
1364 const xkb_keysym_count_t num_syms = leveli->num_syms;
1365 if (num_syms == 0)
1366 goto err;
1367
1368 if (should_do_caps_transformation(state, kc)) {
1369 /* Only simple capitalization rules: keysyms count is unchanged. */
1370 if (num_syms > 1) {
1371 *syms_out = (leveli->has_upper)
1372 ? leveli->s.syms + num_syms
1373 : leveli->s.syms;
1374 } else {
1375 *syms_out = &leveli->upper;
1376 }
1377 } else {
1378 *syms_out = (num_syms > 1)
1379 ? leveli->s.syms
1380 : &leveli->s.sym;
1381 }
1382 return (int) num_syms;
1383
1384 err:
1385 *syms_out = NULL;
1386 return 0;
1387 }
1388
1389 /*
1390 * Verbatim from `libX11:src/xkb/XKBBind.c`.
1391 *
1392 * The basic transformations are defined in “[Interpreting the Control Modifier]”.
1393 * They correspond to the [caret notation], which maps the characters
1394 * `@ABC...XYZ[\]^_` by masking them with `0x1f`. Note that there is no
1395 * transformation for `?`, although `^?` is defined in the [caret notation].
1396 *
1397 * For convenience, the range ```abc...xyz{|}~`` and the space character ` `
1398 * are processed the same way. This allow to produce control characters without
1399 * requiring the use of the `Shift` modifier for letters.
1400 *
1401 * The transformation of the digits seems to originate from the [VT220 terminal],
1402 * as a compatibility for non-US keyboards. Indeed, these keyboards may not have
1403 * the punctuation characters available or in a convenient position. Some mnemonics:
1404 *
1405 * - ^2 maps to ^@ because @ is on the key 2 in the US layout.
1406 * - ^6 maps to ^^ because ^ is on the key 6 in the US layout.
1407 * - characters 3, 4, 5, 6, and 7 seems to align with the sequence `[\]^_`.
1408 * - 8 closes the sequence and so maps to the last control character.
1409 *
1410 * The `/` transformation seems to be defined for compatibility or convenience.
1411 *
1412 * [Interpreting the Control Modifier]: https://www.x.org/releases/current/doc/kbproto/xkbproto.html#Interpreting_the_Control_Modifier
1413 * [caret notation]: https://en.wikipedia.org/wiki/Caret_notation
1414 * [VT220 terminal]: https://vt100.net/docs/vt220-rm/chapter3.html#T3-5
1415 */
1416 static char
1417 XkbToControl(char ch)
1418 {
1419 char c = ch;
1420
1421 if ((c >= '@' && c < '\177') || c == ' ')
1422 c &= 0x1F;
1423 else if (c == '2')
1424 c = '\000';
1425 else if (c >= '3' && c <= '7')
1426 c -= ('3' - '\033');
1427 else if (c == '8')
1428 c = '\177';
1429 else if (c == '/')
1430 c = '_' & 0x1F;
1431 return c;
1432 }
1433
1434 /**
1435 * Provides either exactly one symbol, or XKB_KEY_NoSymbol.
1436 */
1437 xkb_keysym_t
1438 xkb_state_key_get_one_sym(struct xkb_state *state, xkb_keycode_t kc)
1439 {
1440 const xkb_keysym_t *syms = NULL;
1441 const int num_syms = xkb_state_key_get_syms(state, kc, &syms);
1442
1443 if (num_syms != 1)
1444 return XKB_KEY_NoSymbol;
1445 else
1446 return syms[0];
1447 }
1448
1449 /*
1450 * The caps and ctrl transformations require some special handling,
1451 * so we cannot simply use xkb_state_get_one_sym() for them.
1452 * In particular, if Control is set, we must try very hard to find
1453 * some layout in which the keysym is ASCII and thus can be (maybe)
1454 * converted to a control character. libX11 allows to disable this
1455 * behavior with the XkbLC_ControlFallback (see XkbSetXlibControls(3)),
1456 * but it is enabled by default, yippee.
1457 */
1458 static xkb_keysym_t
1459 get_one_sym_for_string(struct xkb_state *state, xkb_keycode_t kc)
1460 {
1461 const xkb_layout_index_t layout = xkb_state_key_get_layout(state, kc);
1462 const xkb_layout_index_t num_layouts =
1463 xkb_keymap_num_layouts_for_key(state->keymap, kc);
1464 xkb_level_index_t level = xkb_state_key_get_level(state, kc, layout);
1465 if (layout == XKB_LAYOUT_INVALID || num_layouts == 0 ||
1466 level == XKB_LEVEL_INVALID)
1467 return XKB_KEY_NoSymbol;
1468
1469 const xkb_keysym_t *syms = NULL;
1470 int nsyms = xkb_keymap_key_get_syms_by_level(state->keymap, kc,
1471 layout, level, &syms);
1472 if (nsyms != 1)
1473 return XKB_KEY_NoSymbol;
1474 xkb_keysym_t sym = syms[0];
1475
1476 if (should_do_ctrl_transformation(state, kc) && sym > 127u) {
1477 for (xkb_layout_index_t i = 0; i < num_layouts; i++) {
1478 level = xkb_state_key_get_level(state, kc, i);
1479 if (level == XKB_LEVEL_INVALID)
1480 continue;
1481
1482 nsyms = xkb_keymap_key_get_syms_by_level(state->keymap, kc,
1483 i, level, &syms);
1484 if (nsyms == 1 && syms[0] <= 127u) {
1485 sym = syms[0];
1486 break;
1487 }
1488 }
1489 }
1490
1491 if (should_do_caps_transformation(state, kc)) {
1492 sym = xkb_keysym_to_upper(sym);
1493 }
1494
1495 return sym;
1496 }
1497
1498 int
1499 xkb_state_key_get_utf8(struct xkb_state *state, xkb_keycode_t kc,
1500 char *buffer, size_t size)
1501 {
1502 int nsyms;
1503 const xkb_keysym_t *syms = NULL;
1504 const xkb_keysym_t sym = get_one_sym_for_string(state, kc);
1505 if (sym != XKB_KEY_NoSymbol) {
1506 nsyms = 1; syms = &sym;
1507 }
1508 else {
1509 nsyms = xkb_state_key_get_syms(state, kc, &syms);
1510 }
1511
1512 /* Make sure not to truncate in the middle of a UTF-8 sequence. */
1513 int offset = 0;
1514 char tmp[XKB_KEYSYM_UTF8_MAX_SIZE];
1515 for (int i = 0; i < nsyms; i++) {
1516 int ret = xkb_keysym_to_utf8(syms[i], tmp, sizeof(tmp));
1517 if (ret <= 0)
1518 goto err_bad;
1519
1520 ret--;
1521 if ((size_t) offset + ret <= size)
1522 memcpy(buffer + offset, tmp, ret);
1523 offset += ret;
1524 }
1525
1526 if ((size_t) offset >= size)
1527 goto err_trunc;
1528 buffer[offset] = '\0';
1529
1530 if (!is_valid_utf8(buffer, offset))
1531 goto err_bad;
1532
1533 if (offset == 1 && (unsigned int) buffer[0] <= 127u &&
1534 should_do_ctrl_transformation(state, kc))
1535 buffer[0] = XkbToControl(buffer[0]);
1536
1537 return offset;
1538
1539 err_trunc:
1540 if (size > 0)
1541 buffer[size - 1] = '\0';
1542 return offset;
1543
1544 err_bad:
1545 if (size > 0)
1546 buffer[0] = '\0';
1547 return 0;
1548 }
1549
1550 uint32_t
1551 xkb_state_key_get_utf32(struct xkb_state *state, xkb_keycode_t kc)
1552 {
1553 const xkb_keysym_t sym = get_one_sym_for_string(state, kc);
1554 uint32_t cp = xkb_keysym_to_utf32(sym);
1555
1556 if (cp <= 127u && should_do_ctrl_transformation(state, kc))
1557 cp = (uint32_t) XkbToControl((char) cp);
1558
1559 return cp;
1560 }
1561
1562 /**
1563 * Serialises the requested modifier state into an xkb_mod_mask_t, with all
1564 * the same disclaimers as in xkb_state_update_mask.
1565 */
1566 xkb_mod_mask_t
1567 xkb_state_serialize_mods(struct xkb_state *state,
1568 enum xkb_state_component type)
1569 {
1570 xkb_mod_mask_t ret = 0;
1571
1572 if (type & XKB_STATE_MODS_EFFECTIVE)
1573 return state->components.mods;
1574
1575 if (type & XKB_STATE_MODS_DEPRESSED)
1576 ret |= state->components.base_mods;
1577 if (type & XKB_STATE_MODS_LATCHED)
1578 ret |= state->components.latched_mods;
1579 if (type & XKB_STATE_MODS_LOCKED)
1580 ret |= state->components.locked_mods;
1581
1582 return ret;
1583 }
1584
1585 /**
1586 * Serialises the requested group state, with all the same disclaimers as
1587 * in xkb_state_update_mask.
1588 */
1589 xkb_layout_index_t
1590 xkb_state_serialize_layout(struct xkb_state *state,
1591 enum xkb_state_component type)
1592 {
1593 xkb_layout_index_t ret = 0;
1594
1595 if (type & XKB_STATE_LAYOUT_EFFECTIVE)
1596 return state->components.group;
1597
1598 if (type & XKB_STATE_LAYOUT_DEPRESSED)
1599 ret += state->components.base_group;
1600 if (type & XKB_STATE_LAYOUT_LATCHED)
1601 ret += state->components.latched_group;
1602 if (type & XKB_STATE_LAYOUT_LOCKED)
1603 ret += state->components.locked_group;
1604
1605 return ret;
1606 }
1607
1608 /**
1609 * Gets a modifier mask and returns the resolved effective mask; this
1610 * is needed because some modifiers can also map to other modifiers, e.g.
1611 * the "NumLock" modifier usually also sets the "Mod2" modifier.
1612 */
1613 xkb_mod_mask_t
1614 mod_mask_get_effective(struct xkb_keymap *keymap, xkb_mod_mask_t mods)
1615 {
1616 /* Initialize the effective mask with its corresponding real mods. */
1617 xkb_mod_mask_t mask = mods & MOD_REAL_MASK_ALL;
1618
1619 /* Resolve the virtual modifiers */
1620 const struct xkb_mod *mod;
1621 xkb_mod_index_t i;
1622 xkb_vmods_enumerate(i, mod, &keymap->mods)
1623 if (mods & (UINT32_C(1) << i))
1624 mask |= mod->mapping;
1625
1626 return mask;
1627 }
1628
1629 /**
1630 * Returns 1 if the given modifier is active with the specified type(s), 0 if
1631 * not, or -1 if the modifier is invalid.
1632 */
1633 int
1634 xkb_state_mod_index_is_active(struct xkb_state *state,
1635 xkb_mod_index_t idx,
1636 enum xkb_state_component type)
1637 {
1638 if (unlikely(idx >= xkb_keymap_num_mods(state->keymap)))
1639 return -1;
1640
1641 const xkb_mod_mask_t mapping = state->keymap->mods.mods[idx].mapping;
1642 if (!mapping) {
1643 /* Modifier not mapped */
1644 return 0;
1645 }
1646 /* WARNING: this may overmatch for virtual modifiers */
1647 return (xkb_state_serialize_mods(state, type) & mapping) == mapping;
1648 }
1649
1650 /**
1651 * Helper function for xkb_state_mod_indices_are_active and
1652 * xkb_state_mod_names_are_active.
1653 */
1654 static bool
1655 match_mod_masks(struct xkb_state *state,
1656 enum xkb_state_component type,
1657 enum xkb_state_match match,
1658 xkb_mod_mask_t wanted)
1659 {
1660 const xkb_mod_mask_t active = xkb_state_serialize_mods(state, type);
1661
1662 if (!(match & XKB_STATE_MATCH_NON_EXCLUSIVE) && (active & ~wanted))
1663 return false;
1664
1665 if (match & XKB_STATE_MATCH_ANY)
1666 return active & wanted;
1667
1668 return (active & wanted) == wanted;
1669 }
1670
1671 /**
1672 * Returns 1 if the modifiers are active with the specified type(s), 0 if
1673 * not, or -1 if any of the modifiers are invalid.
1674 */
1675 int
1676 xkb_state_mod_indices_are_active(struct xkb_state *state,
1677 enum xkb_state_component type,
1678 enum xkb_state_match match,
1679 ...)
1680 {
1681 va_list ap;
1682 xkb_mod_mask_t wanted = 0;
1683 int ret = 0;
1684 const xkb_mod_index_t num_mods = xkb_keymap_num_mods(state->keymap);
1685
1686 va_start(ap, match);
1687 while (1) {
1688 xkb_mod_index_t idx = va_arg(ap, xkb_mod_index_t);
1689 if (idx == XKB_MOD_INVALID)
1690 break;
1691 if (unlikely(idx >= num_mods)) {
1692 ret = -1;
1693 break;
1694 }
1695 wanted |= state->keymap->mods.mods[idx].mapping;
1696 }
1697 va_end(ap);
1698
1699 if (ret == -1)
1700 return ret;
1701
1702 if (!wanted) {
1703 /* Modifiers not mapped */
1704 return 0;
1705 }
1706
1707 return match_mod_masks(state, type, match, wanted);
1708 }
1709
1710 /**
1711 * Returns 1 if the given modifier is active with the specified type(s), 0 if
1712 * not, or -1 if the modifier is invalid.
1713 */
1714 int
1715 xkb_state_mod_name_is_active(struct xkb_state *state, const char *name,
1716 enum xkb_state_component type)
1717 {
1718 const xkb_mod_index_t idx = xkb_keymap_mod_get_index(state->keymap, name);
1719
1720 if (idx == XKB_MOD_INVALID)
1721 return -1;
1722
1723 return xkb_state_mod_index_is_active(state, idx, type);
1724 }
1725
1726 /**
1727 * Returns 1 if the modifiers are active with the specified type(s), 0 if
1728 * not, or -1 if any of the modifiers are invalid.
1729 */
1730 ATTR_NULL_SENTINEL int
1731 xkb_state_mod_names_are_active(struct xkb_state *state,
1732 enum xkb_state_component type,
1733 enum xkb_state_match match,
1734 ...)
1735 {
1736 va_list ap;
1737 xkb_mod_mask_t wanted = 0;
1738 int ret = 0;
1739
1740 va_start(ap, match);
1741 while (1) {
1742 const char *str = va_arg(ap, const char *);
1743 if (str == NULL)
1744 break;
1745 const xkb_mod_index_t idx = xkb_keymap_mod_get_index(state->keymap, str);
1746 if (idx == XKB_MOD_INVALID) {
1747 ret = -1;
1748 break;
1749 }
1750 wanted |= state->keymap->mods.mods[idx].mapping;
1751 }
1752 va_end(ap);
1753
1754 if (ret == -1)
1755 return ret;
1756
1757 if (!wanted) {
1758 /* Modifiers not mapped */
1759 return 0;
1760 }
1761
1762 return match_mod_masks(state, type, match, wanted);
1763 }
1764
1765 /**
1766 * Returns 1 if the given group is active with the specified type(s), 0 if
1767 * not, or -1 if the group is invalid.
1768 */
1769 int
1770 xkb_state_layout_index_is_active(struct xkb_state *state,
1771 xkb_layout_index_t idx,
1772 enum xkb_state_component type)
1773 {
1774 if (idx >= state->keymap->num_groups)
1775 return -1;
1776
1777 int ret = 0;
1778 if (type & XKB_STATE_LAYOUT_EFFECTIVE)
1779 ret |= (state->components.group == idx);
1780 if (type & XKB_STATE_LAYOUT_DEPRESSED)
1781 ret |= (state->components.base_group == (int32_t) idx);
1782 if (type & XKB_STATE_LAYOUT_LATCHED)
1783 ret |= (state->components.latched_group == (int32_t) idx);
1784 if (type & XKB_STATE_LAYOUT_LOCKED)
1785 ret |= (state->components.locked_group == (int32_t) idx);
1786
1787 return ret;
1788 }
1789
1790 /**
1791 * Returns 1 if the given modifier is active with the specified type(s), 0 if
1792 * not, or -1 if the modifier is invalid.
1793 */
1794 int
1795 xkb_state_layout_name_is_active(struct xkb_state *state, const char *name,
1796 enum xkb_state_component type)
1797 {
1798 const xkb_layout_index_t idx =
1799 xkb_keymap_layout_get_index(state->keymap, name);
1800
1801 if (idx == XKB_LAYOUT_INVALID)
1802 return -1;
1803
1804 return xkb_state_layout_index_is_active(state, idx, type);
1805 }
1806
1807 /**
1808 * Returns 1 if the given LED is active, 0 if not, or -1 if the LED is invalid.
1809 */
1810 int
1811 xkb_state_led_index_is_active(struct xkb_state *state, xkb_led_index_t idx)
1812 {
1813 if (idx >= state->keymap->num_leds ||
1814 state->keymap->leds[idx].name == XKB_ATOM_NONE)
1815 return -1;
1816
1817 return !!(state->components.leds & (UINT32_C(1) << idx));
1818 }
1819
1820 /**
1821 * Returns 1 if the given LED is active, 0 if not, or -1 if the LED is invalid.
1822 */
1823 int
1824 xkb_state_led_name_is_active(struct xkb_state *state, const char *name)
1825 {
1826 const xkb_led_index_t idx = xkb_keymap_led_get_index(state->keymap, name);
1827
1828 if (idx == XKB_LED_INVALID)
1829 return -1;
1830
1831 return xkb_state_led_index_is_active(state, idx);
1832 }
1833
1834 /**
1835 * See:
1836 * - XkbTranslateKeyCode(3), mod_rtrn return value, from libX11.
1837 * - MyEnhancedXkbTranslateKeyCode(), a modification of the above, from GTK+.
1838 */
1839 static xkb_mod_mask_t
1840 key_get_consumed(struct xkb_state *state, const struct xkb_key *key,
1841 enum xkb_consumed_mode mode)
1842 {
1843 const xkb_layout_index_t group =
1844 xkb_state_key_get_layout(state, key->keycode);
1845 if (group == XKB_LAYOUT_INVALID)
1846 return 0;
1847
1848 xkb_mod_mask_t preserve = 0;
1849 xkb_mod_mask_t consumed = 0;
1850
1851 const struct xkb_key_type_entry* const matching_entry =
1852 get_entry_for_key_state(state, key, group);
1853 if (matching_entry)
1854 preserve = matching_entry->preserve.mask;
1855
1856 const struct xkb_key_type* const type = key->groups[group].type;
1857 switch (mode) {
1858 case XKB_CONSUMED_MODE_XKB:
1859 consumed = type->mods.mask;
1860 break;
1861
1862 case XKB_CONSUMED_MODE_GTK: {
1863 const struct xkb_key_type_entry* const no_mods_entry =
1864 get_entry_for_mods(type, 0);
1865 const xkb_level_index_t no_mods_leveli = no_mods_entry
1866 ? no_mods_entry->level
1867 : 0;
1868 const struct xkb_level* const no_mods_level =
1869 &key->groups[group].levels[no_mods_leveli];
1870
1871 for (darray_size_t i = 0; i < type->num_entries; i++) {
1872 const struct xkb_key_type_entry* const entry = &type->entries[i];
1873 if (!entry_is_active(entry))
1874 continue;
1875
1876 const struct xkb_level* const level =
1877 &key->groups[group].levels[entry->level];
1878 if (XkbLevelsSameSyms(level, no_mods_level))
1879 continue;
1880
1881 if (entry == matching_entry || one_bit_set(entry->mods.mask))
1882 consumed |= entry->mods.mask & ~entry->preserve.mask;
1883 }
1884 break;
1885 }
1886 }
1887
1888 return consumed & ~preserve;
1889 }
1890
1891 int
1892 xkb_state_mod_index_is_consumed2(struct xkb_state *state, xkb_keycode_t kc,
1893 xkb_mod_index_t idx,
1894 enum xkb_consumed_mode mode)
1895 {
1896 const struct xkb_key* const key = XkbKey(state->keymap, kc);
1897
1898 if (unlikely(!key || idx >= xkb_keymap_num_mods(state->keymap)))
1899 return -1;
1900
1901 const xkb_mod_mask_t mapping = state->keymap->mods.mods[idx].mapping;
1902 if (!mapping) {
1903 /* Modifier not mapped */
1904 return 0;
1905 }
1906 return (mapping & key_get_consumed(state, key, mode)) == mapping;
1907 }
1908
1909 int
1910 xkb_state_mod_index_is_consumed(struct xkb_state *state, xkb_keycode_t kc,
1911 xkb_mod_index_t idx)
1912 {
1913 return xkb_state_mod_index_is_consumed2(state, kc, idx,
1914 XKB_CONSUMED_MODE_XKB);
1915 }
1916
1917 xkb_mod_mask_t
1918 xkb_state_mod_mask_remove_consumed(struct xkb_state *state, xkb_keycode_t kc,
1919 xkb_mod_mask_t mask)
1920 {
1921 const struct xkb_key* const key = XkbKey(state->keymap, kc);
1922
1923 if (!key)
1924 return 0;
1925
1926 return resolve_to_canonical_mods(state->keymap, mask) &
1927 ~key_get_consumed(state, key, XKB_CONSUMED_MODE_XKB);
1928 }
1929
1930 xkb_mod_mask_t
1931 xkb_state_key_get_consumed_mods2(struct xkb_state *state, xkb_keycode_t kc,
1932 enum xkb_consumed_mode mode)
1933 {
1934 switch (mode) {
1935 case XKB_CONSUMED_MODE_XKB:
1936 case XKB_CONSUMED_MODE_GTK:
1937 break;
1938 default:
1939 log_err_func(state->keymap->ctx, XKB_LOG_MESSAGE_NO_ID,
1940 "unrecognized consumed modifiers mode: %d\n", mode);
1941 return 0;
1942 }
1943
1944 const struct xkb_key* const key = XkbKey(state->keymap, kc);
1945 if (!key)
1946 return 0;
1947
1948 return key_get_consumed(state, key, mode);
1949 }
1950
1951 xkb_mod_mask_t
1952 xkb_state_key_get_consumed_mods(struct xkb_state *state, xkb_keycode_t kc)
1953 {
1954 return xkb_state_key_get_consumed_mods2(state, kc, XKB_CONSUMED_MODE_XKB);
1955 }