Debian Codegraph @

src/xkbcomp/keymap.c

raw
1 /*
2 * Copyright © 2009 Dan Nicholson
3 * Copyright © 2012 Intel Corporation
4 * Copyright © 2012 Ran Benita <[email protected]>
5 * SPDX-License-Identifier: MIT
6 *
7 * Author: Dan Nicholson <[email protected]>
8 * Author: Daniel Stone <[email protected]>
9 * Author: Ran Benita <[email protected]>
10 */
11
12 #include "config.h"
13
14 #include <string.h>
15 #include <stdbool.h>
16
17 #include "xkbcommon/xkbcommon.h"
18 #include "darray.h"
19 #include "keymap.h"
20 #include "text.h"
21 #include "utils.h"
22 #include "xkbcomp-priv.h"
23
24 static bool
25 has_unbound_vmods(struct xkb_keymap *keymap, xkb_mod_mask_t mask)
26 {
27 xkb_mod_index_t k;
28 struct xkb_mod *mod;
29 xkb_vmods_enumerate(k, mod, &keymap->mods)
30 if ((mask & (UINT32_C(1) << k)) && mod->mapping == 0)
31 return true;
32 return false;
33 }
34
35 static inline void
36 ComputeEffectiveMask(struct xkb_keymap *keymap, struct xkb_mods *mods)
37 {
38 /*
39 * Since we accept numeric values for the vmod mask in the keymap, we may
40 * have extra bits set that encode no real/virtual modifier. Keep them
41 * unchanged for consistency.
42 */
43 const xkb_mod_mask_t unknown_mods = ~(xkb_mod_mask_t)
44 ((UINT64_C(1) << keymap->mods.num_mods) - UINT64_C(1));
45 mods->mask = mod_mask_get_effective(keymap, mods->mods)
46 | (mods->mods & unknown_mods);
47 }
48
49 static void
50 UpdateActionMods(struct xkb_keymap *keymap, union xkb_action *act,
51 xkb_mod_mask_t modmap)
52 {
53 switch (act->type) {
54 case ACTION_TYPE_MOD_SET:
55 case ACTION_TYPE_MOD_LATCH:
56 case ACTION_TYPE_MOD_LOCK:
57 if (act->mods.flags & ACTION_MODS_LOOKUP_MODMAP)
58 act->mods.mods.mods = modmap;
59 ComputeEffectiveMask(keymap, &act->mods.mods);
60 break;
61 default:
62 break;
63 }
64 }
65
66 const struct xkb_sym_interpret default_interpret = {
67 /* Keysym unused for when applying interpretation, but used as a default
68 * entry when dumping the keymap */
69 .sym = XKB_KEY_VoidSymbol,
70 .repeat = true,
71 .match = MATCH_ANY_OR_NONE,
72 .mods = 0,
73 .virtual_mod = XKB_MOD_INVALID,
74 .num_actions = 0,
75 .a = { .action = { .type = ACTION_TYPE_NONE } },
76 };
77
78 typedef darray(const struct xkb_sym_interpret*) xkb_sym_interprets;
79
80 /**
81 * Find an interpretation which applies to this particular level, either by
82 * finding an exact match for the symbol and modifier combination, or a
83 * generic XKB_KEY_NoSymbol match.
84 */
85 static bool
86 FindInterpForKey(struct xkb_keymap *keymap, const struct xkb_key *key,
87 xkb_layout_index_t group, xkb_level_index_t level,
88 xkb_sym_interprets *interprets)
89 {
90 const xkb_keysym_t *syms;
91 int num_syms;
92
93 num_syms = xkb_keymap_key_get_syms_by_level(keymap, key->keycode, group,
94 level, &syms);
95 if (num_syms <= 0)
96 return false;
97
98 /*
99 * There may be multiple matchings interprets; we should always return
100 * the most specific. Here we rely on compat.c to set up the
101 * sym_interprets array from the most specific to the least specific,
102 * such that when we find a match we return immediately.
103 */
104 for (int s = 0; s < num_syms; s++) {
105 bool found = false;
106 for (darray_size_t i = 0; i < keymap->num_sym_interprets; i++) {
107 struct xkb_sym_interpret * const interp = &keymap->sym_interprets[i];
108 xkb_mod_mask_t mods;
109
110 found = false;
111
112 if (interp->sym != syms[s] && interp->sym != XKB_KEY_NoSymbol)
113 continue;
114
115 if (interp->level_one_only && level != 0)
116 mods = 0;
117 else
118 mods = key->modmap;
119
120 switch (interp->match) {
121 case MATCH_NONE:
122 found = !(interp->mods & mods);
123 break;
124 case MATCH_ANY_OR_NONE:
125 found = (!mods || (interp->mods & mods));
126 break;
127 case MATCH_ANY:
128 found = (interp->mods & mods);
129 break;
130 case MATCH_ALL:
131 found = ((interp->mods & mods) == interp->mods);
132 break;
133 case MATCH_EXACTLY:
134 found = (interp->mods == mods);
135 break;
136 }
137
138 if (found && i > 0 && interp->sym == XKB_KEY_NoSymbol) {
139 /*
140 * For an interpretation matching Any keysym, we may get the
141 * same interpretation for multiple keysyms. This may result in
142 * unwanted duplicate actions. So set this interpretation only
143 * if no previous keysym was matched with this interpret at this
144 * level, else set the default interpretation.
145 */
146 struct xkb_sym_interpret const **previous_interp;
147 darray_foreach(previous_interp, *interprets) {
148 if (*previous_interp == interp) {
149 /* Keep as a safeguard against refactoring
150 * NOLINTNEXTLINE(clang-analyzer-deadcode.DeadStores) */
151 found = false;
152 log_warn(keymap->ctx, XKB_LOG_MESSAGE_NO_ID,
153 "Repeated interpretation ignored for keysym "
154 "#%d \"%s\" at level %"PRIu32"/group %"PRIu32" "
155 "on key %s.\n",
156 s + 1, KeysymText(keymap->ctx, syms[s]),
157 level + 1, group + 1,
158 KeyNameText(keymap->ctx, key->name));
159 goto not_found;
160 }
161 }
162 }
163 if (found) {
164 darray_append(*interprets, interp);
165 interp->required = true;
166 break;
167 }
168 }
169 if (!found)
170 not_found:
171 darray_append(*interprets, &default_interpret);
172 }
173 return true;
174 }
175
176 static bool
177 ApplyInterpsToKey(struct xkb_keymap *keymap, struct xkb_key *key)
178 {
179 xkb_mod_mask_t vmodmap = 0;
180 xkb_level_index_t level;
181 // FIXME: do not use darray, add actions directly in FindInterpForKey
182 xkb_sym_interprets interprets = darray_new();
183 darray(union xkb_action) actions = darray_new();
184
185 for (xkb_layout_index_t group = 0; group < key->num_groups; group++) {
186 /* Skip any interpretation for this group if it has explicit actions */
187 if (key->groups[group].explicit_actions)
188 continue;
189
190 for (level = 0; level < XkbKeyNumLevels(key, group); level++) {
191 assert(key->groups[group].levels[level].num_actions == 0);
192
193 const struct xkb_sym_interpret **interp_iter;
194 const struct xkb_sym_interpret *interp;
195 size_t k;
196 darray_resize(interprets, 0);
197
198 const bool found = FindInterpForKey(keymap, key, group, level, &interprets);
199 if (!found)
200 continue;
201
202 darray_enumerate(k, interp_iter, interprets) {
203 interp = *interp_iter;
204 /* Infer default key behaviours from the base level. */
205 if (group == 0 && level == 0)
206 if (!(key->explicit & EXPLICIT_REPEAT) && interp->repeat)
207 key->repeats = true;
208
209 if ((group == 0 && level == 0) || !interp->level_one_only)
210 if (interp->virtual_mod != XKB_MOD_INVALID)
211 vmodmap |= (UINT32_C(1) << interp->virtual_mod);
212
213 switch (interp->num_actions) {
214 case 0:
215 break;
216 case 1:
217 darray_append(actions, interp->a.action);
218 break;
219 default:
220 darray_append_items(actions, interp->a.actions,
221 interp->num_actions);
222 }
223 }
224
225 /* Copy the actions */
226 if (unlikely(darray_size(actions)) > MAX_ACTIONS_PER_LEVEL) {
227 log_warn(keymap->ctx, XKB_LOG_MESSAGE_NO_ID,
228 "Could not append interpret actions to key %s: "
229 "maximum is %u, got: %u. Dropping excessive actions\n",
230 KeyNameText(keymap->ctx, key->name),
231 MAX_ACTIONS_PER_LEVEL, darray_size(actions));
232 key->groups[group].levels[level].num_actions =
233 MAX_ACTIONS_PER_LEVEL;
234 } else {
235 key->groups[group].levels[level].num_actions =
236 (xkb_action_count_t) darray_size(actions);
237 }
238 switch (darray_size(actions)) {
239 case 0:
240 key->groups[group].levels[level].a.action =
241 (union xkb_action) { .type = ACTION_TYPE_NONE };
242 break;
243 case 1:
244 key->groups[group].levels[level].a.action =
245 darray_item(actions, 0);
246 break;
247 default:
248 key->groups[group].levels[level].a.actions =
249 memdup(darray_items(actions),
250 key->groups[group].levels[level].num_actions,
251 sizeof(*darray_items(actions)));
252 if (!key->groups[group].levels[level].a.actions) {
253 log_err(keymap->ctx, XKB_ERROR_ALLOCATION_ERROR,
254 "Could not allocate interpret actions\n");
255 darray_free(actions);
256 darray_free(interprets);
257 return false;
258 }
259 }
260
261 /* Do not free here */
262 darray_resize(actions, 0);
263 }
264 }
265 darray_free(actions);
266 darray_free(interprets);
267
268 if (!(key->explicit & EXPLICIT_VMODMAP))
269 key->vmodmap = vmodmap;
270
271 return true;
272 }
273
274 static inline bool
275 is_mod_action(union xkb_action *action)
276 {
277 return action->type == ACTION_TYPE_MOD_SET ||
278 action->type == ACTION_TYPE_MOD_LATCH ||
279 action->type == ACTION_TYPE_MOD_LOCK;
280 }
281
282 static inline bool
283 is_group_action(union xkb_action *action)
284 {
285 return action->type == ACTION_TYPE_GROUP_SET ||
286 action->type == ACTION_TYPE_GROUP_LATCH ||
287 action->type == ACTION_TYPE_GROUP_LOCK;
288 }
289
290 /* Check for mixing actions of the same category.
291 * We do not support that yet, because it needs a careful refactor of the state
292 * handling. See: `xkb_filter_apply_all`. */
293 static void
294 CheckMultipleActionsCategories(struct xkb_keymap *keymap, struct xkb_key *key)
295 {
296 for (xkb_layout_index_t g = 0; g < key->num_groups; g++) {
297 for (xkb_level_index_t l = 0; l < XkbKeyNumLevels(key, g); l++) {
298 struct xkb_level *level = &key->groups[g].levels[l];
299 if (level->num_actions <= 1)
300 continue;
301 for (xkb_action_count_t i = 0; i < level->num_actions; i++) {
302 union xkb_action *action1 = &level->a.actions[i];
303 bool mod_action = is_mod_action(action1);
304 bool group_action = is_group_action(action1);
305 if (!(mod_action || group_action))
306 continue;
307 for (xkb_action_count_t j = i + 1; j < level->num_actions; j++) {
308 union xkb_action *action2 = &level->a.actions[j];
309 if ((mod_action && is_mod_action(action2)) ||
310 (group_action && is_group_action(action2)))
311 {
312 log_err(keymap->ctx, XKB_LOG_MESSAGE_NO_ID,
313 "Cannot use multiple %s actions "
314 "in the same level. Action #%u "
315 "for key %s in group %"PRIu32"/level %"PRIu32" "
316 "ignored.\n",
317 (mod_action ? "modifiers" : "group"),
318 j + 1, KeyNameText(keymap->ctx, key->name),
319 g + 1, l + 1);
320 action2->type = ACTION_TYPE_NONE;
321 }
322 }
323 }
324 }
325 }
326 }
327
328 static void
329 add_key_aliases(struct xkb_keymap *keymap, darray_size_t min, darray_size_t max,
330 struct xkb_key_alias *aliases)
331 {
332 for (darray_size_t alias = min; alias <= max; alias++) {
333 const KeycodeMatch entry = keymap->key_names[alias];
334 if (entry.is_alias && entry.found) {
335 *aliases = (struct xkb_key_alias) {
336 .alias = alias,
337 .real = entry.alias.real
338 };
339 aliases++;
340 }
341 }
342 }
343
344 /**
345 * This collects a bunch of disparate functions which was done in the server
346 * at various points that really should've been done within xkbcomp. Turns out
347 * your actions and types are a lot more useful when any of your modifiers
348 * other than Shift actually do something ...
349 */
350 static bool
351 UpdateDerivedKeymapFields(struct xkb_keymap *keymap)
352 {
353 /**
354 * Create the key alias list
355 *
356 * Since we already allocated the key name LUT, we try to overwrite it:
357 * - An alias entry is exactly 2× the size of a LUT entry (on most compilers).
358 * - We ensure that there is a real key for each alias.
359 * - So, if each alias maps to a different keycode, we usually have:
360 * current alloc(keymap.key_names) ≥ needed alloc(keymap.key_aliases).
361 * - Usual keymaps have enough space in the LUT to enable overwriting real
362 * key entries without overlap with the alias entries.
363 * - In the unlikely event that this is not the case, we need to realloc.
364 */
365 #ifdef _WIN32
366 /* Bit fields are not packed on Windows as efficiently as other platforms */
367 static_assert(sizeof(struct xkb_key_alias) == sizeof(KeycodeMatch), "");
368 #else
369 static_assert(sizeof(struct xkb_key_alias) == 2 * sizeof(KeycodeMatch), "");
370 #endif
371 darray_size_t num_key_aliases = 0;
372 darray_size_t min_alias = 0;
373 darray_size_t max_alias = 0;
374 for (xkb_atom_t alias = 0; alias < keymap->num_key_names; alias++) {
375 const KeycodeMatch entry = keymap->key_names[alias];
376 if (entry.is_alias && entry.found) {
377 if (!num_key_aliases)
378 min_alias = alias;
379 max_alias = alias;
380 num_key_aliases++;
381 }
382 }
383 if (num_key_aliases) {
384 /*
385 * No fancy algorithm used here: either we can trivially write the whole
386 * range of `xkb_key_aliases` without overlapping with the `KeycodeMatch`
387 * alias entries or we allocate a new array.
388 * In practice no new allocation is needed and it performs better than
389 * using a buffer to handle overlaps.
390 */
391 const darray_size_t required_space = sizeof(struct xkb_key_alias)
392 / sizeof(KeycodeMatch)
393 * num_key_aliases;
394 assert(num_key_aliases <= keymap->num_key_names);
395 if (min_alias >= required_space) {
396 /* Overwrite before the *first* alias entry */
397 add_key_aliases(keymap, min_alias, max_alias, keymap->key_aliases);
398 /* Shrink */
399 struct xkb_key_alias * const r =
400 realloc(keymap->key_aliases,
401 num_key_aliases * sizeof(*keymap->key_aliases));
402 if (!r)
403 return false;
404 keymap->key_aliases = r;
405 } else if (keymap->num_key_names - max_alias - 1 > required_space) {
406 /* Overwrite after the *last* alias entry */
407 struct xkb_key_alias * const aliases = (struct xkb_key_alias *) (
408 keymap->key_names + max_alias + 1 +
409 !is_aligned(keymap->key_names + max_alias + 1, sizeof(*aliases))
410 );
411 add_key_aliases(keymap, min_alias, max_alias, aliases);
412 /* Move to the start */
413 memcpy(keymap->key_aliases, aliases,
414 num_key_aliases * sizeof(*keymap->key_aliases));
415 /* Shrink */
416 struct xkb_key_alias * const r =
417 realloc(keymap->key_aliases,
418 num_key_aliases * sizeof(*keymap->key_aliases));
419 if (!r)
420 return false;
421 keymap->key_aliases = r;
422 } else {
423 /*
424 * No space trivially available: instead of processing the LUT with
425 * a buffer to handle overlaps, we simply allocate a dedicated array
426 */
427 struct xkb_key_alias * const aliases = calloc(num_key_aliases,
428 sizeof(*aliases));
429 if (!aliases)
430 return false;
431 add_key_aliases(keymap, min_alias, max_alias, aliases);
432 free(keymap->key_names);
433 keymap->key_aliases = aliases;
434 }
435 }
436 keymap->num_key_aliases = num_key_aliases;
437
438 /* Find all the interprets for the key and bind them to actions,
439 * which will also update the vmodmap. */
440 struct xkb_key *key;
441 xkb_keys_foreach(key, keymap) {
442 if (!ApplyInterpsToKey(keymap, key))
443 return false;
444 CheckMultipleActionsCategories(keymap, key);
445 }
446
447 /* Update keymap->mods, the virtual -> real mod mapping. */
448 xkb_mod_index_t idx;
449 struct xkb_mod *mod;
450 xkb_keys_foreach(key, keymap)
451 xkb_vmods_enumerate(idx, mod, &keymap->mods)
452 if (key->vmodmap & (UINT32_C(1) << idx))
453 mod->mapping |= key->modmap;
454
455 if (keymap->format >= XKB_KEYMAP_FORMAT_TEXT_V2) {
456 /*
457 * XKB extension: canonical virtual modifiers (incompatible with X11)
458 *
459 * Virtual modifiers that are not mapped, map to their canonical
460 * encoding, i.e. themselves.
461 *
462 * This excludes:
463 * - Modifiers mapped *explicitly*: e.g. `virtual_modifiers M = 0x1;`.
464 * - Modifiers mapped *implicitly* via vmodmap/modifier_map, i.e. the
465 * usual X11 way used in xkeyboard-config.
466 */
467 xkb_vmods_enumerate(idx, mod, &keymap->mods) {
468 const xkb_mod_mask_t mask = UINT32_C(1) << idx;
469 if (mod->mapping == 0 && !(keymap->mods.explicit_vmods & mask)) {
470 mod->mapping = mask;
471 /*
472 * Make the mapping explicit, so that it is interoperable
473 * without relying on the implementation-specific virtual
474 * modifiers indices.
475 */
476 keymap->mods.explicit_vmods |= mask;
477 }
478 }
479 }
480
481 /* Update the canonical modifiers state mask */
482 assert(keymap->canonical_state_mask == MOD_REAL_MASK_ALL);
483 xkb_mod_mask_t extra_canonical_mods = 0;
484 xkb_vmods_enumerate(idx, mod, &keymap->mods) {
485 extra_canonical_mods |= mod->mapping;
486 }
487 keymap->canonical_state_mask |= extra_canonical_mods;
488
489 /* Now update the level masks for all the types to reflect the vmods. */
490 for (darray_size_t i = 0; i < keymap->num_types; i++) {
491 ComputeEffectiveMask(keymap, &keymap->types[i].mods);
492
493 for (darray_size_t j = 0; j < keymap->types[i].num_entries; j++) {
494 if (has_unbound_vmods(keymap,
495 keymap->types[i].entries[j].mods.mods)) {
496 /*
497 * Map entries which specify unbound virtual modifiers are not
498 * considered (see the XKB protocol, section “Determining the
499 * KeySym Associated with a Key Event”).
500 *
501 * Deactivate entry by zeroing its mod mask and skipping further
502 * processing.
503 *
504 * See also: `entry_is_active`.
505 */
506 keymap->types[i].entries[j].mods.mask = 0;
507 continue;
508 }
509 ComputeEffectiveMask(keymap, &keymap->types[i].entries[j].mods);
510 ComputeEffectiveMask(keymap, &keymap->types[i].entries[j].preserve);
511 }
512 }
513
514 /* Update action modifiers. */
515 xkb_keys_foreach(key, keymap) {
516 for (xkb_layout_index_t i = 0; i < key->num_groups; i++) {
517 for (xkb_level_index_t j = 0; j < XkbKeyNumLevels(key, i); j++) {
518 if (key->groups[i].levels[j].num_actions == 1) {
519 UpdateActionMods(keymap, &key->groups[i].levels[j].a.action,
520 key->modmap);
521 } else {
522 for (xkb_action_count_t k = 0;
523 k < key->groups[i].levels[j].num_actions; k++) {
524 UpdateActionMods(keymap,
525 &key->groups[i].levels[j].a.actions[k],
526 key->modmap);
527 }
528 }
529 }
530 }
531 }
532
533 /* Update vmod -> led maps. */
534 struct xkb_led *led;
535 xkb_leds_foreach(led, keymap)
536 ComputeEffectiveMask(keymap, &led->mods);
537
538 /* Find maximum number of groups out of all keys in the keymap. */
539 xkb_keys_foreach(key, keymap)
540 keymap->num_groups = MAX(keymap->num_groups, key->num_groups);
541
542 return true;
543 }
544
545 typedef bool (*compile_file_fn)(XkbFile *file, struct xkb_keymap *keymap);
546
547 static const compile_file_fn compile_file_fns[LAST_KEYMAP_FILE_TYPE + 1] = {
548 [FILE_TYPE_KEYCODES] = CompileKeycodes,
549 [FILE_TYPE_TYPES] = CompileKeyTypes,
550 [FILE_TYPE_COMPAT] = CompileCompatMap,
551 [FILE_TYPE_SYMBOLS] = CompileSymbols,
552 };
553
554 bool
555 CompileKeymap(XkbFile *file, struct xkb_keymap *keymap)
556 {
557 XkbFile *files[LAST_KEYMAP_FILE_TYPE + 1] = { NULL };
558 enum xkb_file_type type;
559 struct xkb_context *ctx = keymap->ctx;
560
561 /* Collect section files and check for duplicates. */
562 for (file = (XkbFile *) file->defs; file;
563 file = (XkbFile *) file->common.next) {
564 if (file->file_type < FIRST_KEYMAP_FILE_TYPE ||
565 file->file_type > LAST_KEYMAP_FILE_TYPE) {
566 if (file->file_type == FILE_TYPE_GEOMETRY) {
567 log_vrb(ctx, XKB_LOG_VERBOSITY_BRIEF,
568 XKB_WARNING_UNSUPPORTED_GEOMETRY_SECTION,
569 "Geometry sections are not supported; ignoring\n");
570 } else {
571 log_err(ctx, XKB_LOG_MESSAGE_NO_ID,
572 "Cannot define %s in a keymap file\n",
573 xkb_file_type_to_string(file->file_type));
574 }
575 continue;
576 }
577
578 if (files[file->file_type]) {
579 log_err(ctx, XKB_LOG_MESSAGE_NO_ID,
580 "More than one %s section in keymap file; "
581 "All sections after the first ignored\n",
582 xkb_file_type_to_string(file->file_type));
583 continue;
584 }
585
586 files[file->file_type] = file;
587 }
588
589 /*
590 * Compile sections
591 *
592 * NOTE: Any component is optional.
593 */
594 for (type = FIRST_KEYMAP_FILE_TYPE;
595 type <= LAST_KEYMAP_FILE_TYPE;
596 type++) {
597 if (files[type] == NULL) {
598 log_dbg(ctx, XKB_LOG_MESSAGE_NO_ID,
599 "Component %s not provided in keymap\n",
600 xkb_file_type_to_string(type));
601 } else {
602 log_dbg(ctx, XKB_LOG_MESSAGE_NO_ID,
603 "Compiling %s \"%s\"\n",
604 xkb_file_type_to_string(type), safe_map_name(files[type]));
605 }
606
607 /* Missing components are initialized with defaults */
608 const bool ok = compile_file_fns[type](files[type], keymap);
609 if (!ok) {
610 log_err(ctx, XKB_LOG_MESSAGE_NO_ID,
611 "Failed to compile %s\n",
612 xkb_file_type_to_string(type));
613 return false;
614 }
615 }
616
617 return UpdateDerivedKeymapFields(keymap);
618 }