Debian Codegraph @

src/xkbcomp/keymap-dump.c

raw
1 /*
2 * For HPND:
3 * Copyright (c) 1994 by Silicon Graphics Computer Systems, Inc.
4 *
5 * For MIT:
6 * Copyright © 2012 Intel Corporation
7 *
8 * SPDX-License-Identifier: HPND AND MIT
9 *
10 * Author: Daniel Stone <[email protected]>
11 */
12
13 #include "config.h"
14
15 #include <assert.h>
16 #include <stdlib.h>
17
18 #include "xkbcommon/xkbcommon-keysyms.h"
19 #include "xkbcommon/xkbcommon.h"
20 #include "keymap.h"
21 #include "action.h"
22 #include "messages-codes.h"
23 #include "xkbcomp-priv.h"
24 #include "text.h"
25
26 #define BUF_CHUNK_SIZE 4096
27
28 struct buf {
29 char *buf;
30 size_t size;
31 size_t alloc;
32 };
33
34 #define xkb_abs(n) _Generic((n), \
35 int: abs, \
36 long int: labs, \
37 default: llabs )((n))
38
39 static bool
40 do_realloc(struct buf *buf, size_t at_least)
41 {
42 buf->alloc += BUF_CHUNK_SIZE;
43 if (at_least >= BUF_CHUNK_SIZE)
44 buf->alloc += at_least;
45
46 char *const new = realloc(buf->buf, buf->alloc);
47 if (!new)
48 return false;
49
50 buf->buf = new;
51 return true;
52 }
53
54 ATTR_PRINTF(2, 3) static bool
55 check_write_buf(struct buf *buf, const char *fmt, ...)
56 {
57 va_list args;
58 int printed;
59 size_t available;
60
61 available = buf->alloc - buf->size;
62 /* Try to write to the buffer and get the required min size (without the
63 * final null byte).
64 * C11 states that if `available` is 0, then the pointer may be null. */
65 assert(buf->buf || available == 0);
66 va_start(args, fmt);
67 printed = vsnprintf(buf->buf ? buf->buf + buf->size : buf->buf, available,
68 fmt, args);
69 va_end(args);
70
71 if (printed < 0) {
72 /* Some error */
73 goto err;
74 } else if ((size_t) printed >= available) {
75 /* Not enough space: need to realloc */
76 if (!do_realloc(buf, printed + 1))
77 goto err;
78
79 /* The buffer has enough space now. */
80 available = buf->alloc - buf->size;
81 assert(buf->buf && (size_t) printed < available);
82 va_start(args, fmt);
83 printed = vsnprintf(buf->buf + buf->size, available, fmt, args);
84 va_end(args);
85
86 if (printed < 0 || (size_t) printed >= available)
87 goto err;
88 }
89
90 buf->size += printed;
91 return true;
92
93 err:
94 free(buf->buf);
95 buf->buf = NULL;
96 return false;
97 }
98
99 #define write_buf(buf, ...) do { \
100 if (!check_write_buf(buf, __VA_ARGS__)) \
101 return false; \
102 } while (0)
103
104 static bool
105 check_copy_to_buf(struct buf *buf, const char* source, size_t len)
106 {
107 if (len == 0)
108 return true;
109
110 const size_t available = buf->alloc - buf->size;
111 if (len >= available) {
112 /* len + 1 (terminating NULL) */
113 if (!do_realloc(buf, len + 1)) {
114 free(buf->buf);
115 buf->buf = NULL;
116 return false;
117 }
118 }
119
120 memcpy(buf->buf + buf->size, source, len);
121 buf->size += len;
122 /* Append NULL byte */
123 buf->buf[buf->size] = '\0';
124 return true;
125 }
126
127 #define copy_to_buf_len(buf, source, len) do { \
128 if (!check_copy_to_buf(buf, source, len)) \
129 return false; \
130 } while (0)
131
132 #define copy_to_buf(buf, source) \
133 copy_to_buf_len(buf, source, sizeof(source) - 1)
134
135 static bool
136 check_write_string_literal(struct buf *buf, const char* string)
137 {
138 copy_to_buf(buf, "\"");
139
140 /* Write chunks, separated by characters requiring escape sequence */
141 size_t pending_start = 0;
142 size_t current = 0;
143 char escape_buffer[] = {'\\', '0', '0', '0', '0'};
144 for (; string[current] != '\0'; current++) {
145 uint8_t escape_len;
146 switch (string[current]) {
147 case '\n':
148 /* `\n` would break strings */
149 escape_buffer[1] = 'n';
150 escape_len = 2;
151 break;
152 case '\\':
153 /* `\` would create escape sequences */
154 escape_buffer[1] = '\\';
155 escape_len = 2;
156 break;
157 default:
158 /*
159 * Handle `"` (would break strings) and ASCII control characters
160 * with an octal escape sequence. Xorg xkbcomp does not parse the
161 * escape sequence `\"` nor xkbcommon < 1.9.0, so in order to be
162 * backward compatible we must use the octal escape sequence in
163 * xkbcomp style `\0nnn` with *4* digits:
164 *
165 * 1. To be compatible with Xorg xkbcomp.
166 * 2. To avoid issues with the next char: e.g. "\00427" should not
167 * be emitted as "\427" nor "\0427".
168 *
169 * Note that xkbcommon < 1.9.0 will still not parse this correctly,
170 * although it will not raise an error: e.g. the escape for `"`,
171 * `\0042`, would be parsed as `\004` + `2`.
172 */
173 if (unlikely((unsigned char)string[current] < 0x20U ||
174 string[current] == '"')) {
175 escape_buffer[1] = '0';
176 escape_buffer[2] = '0';
177 escape_buffer[3] = (char)('0' + (string[current] >> 3));
178 escape_buffer[4] = (char)('0' + (string[current] & 0x7));
179 escape_len = 5;
180 } else {
181 /* Expand the chunk */
182 continue;
183 }
184 }
185 /* Write pending chunk */
186 assert(current >= pending_start);
187 copy_to_buf_len(buf, string + pending_start, current - pending_start);
188 /* Write escape sequence */
189 copy_to_buf_len(buf, escape_buffer, escape_len);
190 pending_start = current + 1;
191 }
192 /* Write remaining chunk */
193 assert(current >= pending_start);
194 copy_to_buf_len(buf, string + pending_start, current - pending_start);
195
196 copy_to_buf(buf, "\"");
197 return true;
198 }
199
200 #define write_buf_string_literal(buf, string) do { \
201 if (!check_write_string_literal(buf, string)) \
202 return false; \
203 } while (0)
204
205 static bool
206 write_vmods(struct xkb_keymap *keymap, enum xkb_keymap_format format,
207 struct buf *buf)
208 {
209 const struct xkb_mod *mod;
210 xkb_mod_index_t vmod = 0;
211 bool has_some = false;
212
213 xkb_vmods_enumerate(vmod, mod, &keymap->mods) {
214 if (!has_some) {
215 copy_to_buf(buf, "\tvirtual_modifiers ");
216 has_some = true;
217 } else {
218 copy_to_buf(buf, ",");
219 }
220 write_buf(buf, "%s", xkb_atom_text(keymap->ctx, mod->name));
221
222 /*
223 * Ensure to always honor explicit mappings when auto canonical vmods
224 * is enabled, so that parsing/serializing can round-trip. This is not
225 * required when the feature is disabled (keymap format v1).
226 *
227 * If the auto feature is enabled, `virtual_modifiers M;` will assign
228 * a canonical mapping > 0xff to `M` if there is no further explicit/
229 * implicit mapping for `M`.
230 *
231 * On the contrary, `virtual_modifiers M = none;` prevents the auto
232 * mapping of `M`. So if the auto feature is enabled and there is no
233 * further explicit/implicit mapping for `M`, then the mapping of `M`
234 * will remain unchanged: `none`. It must be serialized to an explicit
235 * mapping to prevent triggering the auto canonical mapping presented
236 * above.
237 */
238 const bool auto_canonical_mods = (format >= XKB_KEYMAP_FORMAT_TEXT_V2);
239
240 if ((keymap->mods.explicit_vmods & (UINT32_C(1) << vmod)) &&
241 (auto_canonical_mods || mod->mapping != 0)) {
242 /*
243 * Explicit non-default mapping
244 * NOTE: we can only pretty-print *real* modifiers in this context.
245 */
246 write_buf(buf, "=%s",
247 ModMaskText(keymap->ctx, MOD_REAL, &keymap->mods,
248 mod->mapping));
249 }
250 }
251
252 if (has_some)
253 copy_to_buf(buf, ";\n\n");
254
255 return true;
256 }
257
258 static bool
259 write_keycodes(struct xkb_keymap *keymap, bool pretty, struct buf *buf)
260 {
261 const struct xkb_key *key;
262 xkb_led_index_t idx;
263 const struct xkb_led *led;
264
265 if (keymap->keycodes_section_name)
266 write_buf(buf, "xkb_keycodes \"%s\" {\n",
267 keymap->keycodes_section_name);
268 else
269 copy_to_buf(buf, "xkb_keycodes {\n");
270
271 /* xkbcomp and X11 really want to see keymaps with a minimum of 8, and
272 * a maximum of at least 255, else XWayland really starts hating life.
273 * If this is a problem and people really need strictly bounded keymaps,
274 * we should probably control this with a flag. */
275 write_buf(buf, "\tminimum = %"PRIu32";\n", MIN(keymap->min_key_code, 8));
276 write_buf(buf, "\tmaximum = %"PRIu32";\n", MAX(keymap->max_key_code, 255));
277
278 xkb_keys_foreach(key, keymap) {
279 if (key->name == XKB_ATOM_NONE)
280 continue;
281
282 if (pretty)
283 write_buf(buf, "\t%-20s", KeyNameText(keymap->ctx, key->name));
284 else
285 write_buf(buf, "\t%s", KeyNameText(keymap->ctx, key->name));
286 write_buf(buf, " = %"PRIu32";\n", key->keycode);
287 }
288
289 xkb_leds_enumerate(idx, led, keymap)
290 if (led->name != XKB_ATOM_NONE) {
291 write_buf(buf, "\tindicator %u = ", idx + 1);
292 write_buf_string_literal(buf, xkb_atom_text(keymap->ctx, led->name));
293 copy_to_buf(buf, ";\n");
294 }
295
296 for (darray_size_t i = 0; i < keymap->num_key_aliases; i++) {
297 if (pretty)
298 write_buf(buf, "\talias %-14s",
299 KeyNameText(keymap->ctx, keymap->key_aliases[i].alias));
300 else
301 write_buf(buf, "\talias %s",
302 KeyNameText(keymap->ctx, keymap->key_aliases[i].alias));
303 write_buf(buf, " = %s;\n",
304 KeyNameText(keymap->ctx, keymap->key_aliases[i].real));
305 }
306
307 copy_to_buf(buf, "};\n\n");
308 return true;
309 }
310
311 static bool
312 write_types(struct xkb_keymap *keymap, enum xkb_keymap_format format,
313 bool drop_unused, struct buf *buf)
314 {
315 if (keymap->types_section_name)
316 write_buf(buf, "xkb_types \"%s\" {\n",
317 keymap->types_section_name);
318 else
319 copy_to_buf(buf, "xkb_types {\n");
320
321 if (!write_vmods(keymap, format, buf))
322 return false;
323
324 for (darray_size_t i = 0; i < keymap->num_types; i++) {
325 const struct xkb_key_type * const type = &keymap->types[i];
326 if (!type->required && drop_unused)
327 continue;
328
329 copy_to_buf(buf, "\ttype ");
330 write_buf_string_literal(buf, xkb_atom_text(keymap->ctx, type->name));
331 copy_to_buf(buf, " {\n");
332
333 write_buf(buf, "\t\tmodifiers= %s;\n",
334 ModMaskText(keymap->ctx, MOD_BOTH, &keymap->mods,
335 type->mods.mods));
336
337 for (darray_size_t j = 0; j < type->num_entries; j++) {
338 const char *str;
339 const struct xkb_key_type_entry *entry = &type->entries[j];
340
341 /*
342 * Printing level 1 entries is redundant, it's the default,
343 * unless there's preserve info.
344 */
345 if (entry->level == 0 && entry->preserve.mods == 0)
346 continue;
347
348 str = ModMaskText(keymap->ctx, MOD_BOTH, &keymap->mods,
349 entry->mods.mods);
350 write_buf(buf, "\t\tmap[%s]= %"PRIu32";\n",
351 str, entry->level + 1);
352
353 if (entry->preserve.mods)
354 write_buf(buf, "\t\tpreserve[%s]= %s;\n",
355 str, ModMaskText(keymap->ctx, MOD_BOTH, &keymap->mods,
356 entry->preserve.mods));
357 }
358
359 for (xkb_level_index_t n = 0; n < type->num_level_names; n++)
360 if (type->level_names[n]) {
361 write_buf(buf, "\t\tlevel_name[%"PRIu32"]= ", n + 1);
362 write_buf_string_literal(
363 buf, xkb_atom_text(keymap->ctx, type->level_names[n]));
364 copy_to_buf(buf, ";\n");
365 }
366
367
368 copy_to_buf(buf, "\t};\n");
369 }
370
371 copy_to_buf(buf, "};\n\n");
372 return true;
373 }
374
375 static bool
376 write_led_map(struct xkb_keymap *keymap, struct buf *buf,
377 const struct xkb_led *led)
378 {
379 copy_to_buf(buf, "\tindicator ");
380 write_buf_string_literal(buf, xkb_atom_text(keymap->ctx, led->name));
381 copy_to_buf(buf, " {\n");
382
383 if (led->which_groups) {
384 if (led->which_groups != XKB_STATE_LAYOUT_EFFECTIVE) {
385 write_buf(buf, "\t\twhichGroupState= %s;\n",
386 LedStateMaskText(keymap->ctx, groupComponentMaskNames,
387 led->which_groups));
388 }
389 write_buf(buf, "\t\tgroups= 0x%02x;\n",
390 led->groups);
391 }
392
393 if (led->which_mods) {
394 if (led->which_mods != XKB_STATE_MODS_EFFECTIVE) {
395 write_buf(buf, "\t\twhichModState= %s;\n",
396 LedStateMaskText(keymap->ctx, modComponentMaskNames,
397 led->which_mods));
398 }
399 write_buf(buf, "\t\tmodifiers= %s;\n",
400 ModMaskText(keymap->ctx, MOD_BOTH, &keymap->mods,
401 led->mods.mods));
402 }
403
404 if (led->ctrls) {
405 write_buf(buf, "\t\tcontrols= %s;\n",
406 ControlMaskText(keymap->ctx, led->ctrls));
407 }
408
409 copy_to_buf(buf, "\t};\n");
410 return true;
411 }
412
413 static const char *
414 affect_lock_text(enum xkb_action_flags flags, bool show_both)
415 {
416 switch (flags & (ACTION_LOCK_NO_LOCK | ACTION_LOCK_NO_UNLOCK)) {
417 case 0:
418 return show_both ? ",affect=both" : "";
419 case ACTION_LOCK_NO_UNLOCK:
420 return ",affect=lock";
421 case ACTION_LOCK_NO_LOCK:
422 return ",affect=unlock";
423 case ACTION_LOCK_NO_LOCK | ACTION_LOCK_NO_UNLOCK:
424 return ",affect=neither";
425 default:
426 return "";
427 }
428 }
429
430 #define SYMBOL_PADDING 15
431 #define ACTION_PADDING 30
432
433 static bool
434 write_action(struct xkb_keymap *keymap, enum xkb_keymap_format format,
435 xkb_layout_index_t max_groups, struct buf *buf,
436 const union xkb_action *action,
437 const char *prefix, const char *suffix)
438 {
439 const char *type;
440 const char *args = NULL;
441
442 if (!prefix)
443 prefix = "";
444 if (!suffix)
445 suffix = "";
446
447 type = ActionTypeText(action->type);
448
449 switch (action->type) {
450 case ACTION_TYPE_MOD_SET:
451 case ACTION_TYPE_MOD_LATCH:
452 case ACTION_TYPE_MOD_LOCK:
453 if (action->mods.flags & ACTION_MODS_LOOKUP_MODMAP)
454 args = "modMapMods";
455 else
456 args = ModMaskText(keymap->ctx, MOD_BOTH, &keymap->mods,
457 action->mods.mods.mods);
458 bool unlockOnPress = (action->mods.flags & ACTION_UNLOCK_ON_PRESS);
459 if (unlockOnPress && !isModsUnLockOnPressSupported(format)) {
460 log_err(keymap->ctx, XKB_ERROR_INCOMPATIBLE_KEYMAP_TEXT_FORMAT,
461 "Cannot use \"%s(unlockOnPress=true)\" in keymap format %d\n",
462 ActionTypeText(action->type), format);
463 unlockOnPress = false;
464 }
465 bool latchOnPress = action->type == ACTION_TYPE_MOD_LATCH &&
466 (action->group.flags & ACTION_LATCH_ON_PRESS);
467 if (latchOnPress && !isModsLatchOnPressSupported(format)) {
468 log_err(keymap->ctx, XKB_ERROR_INCOMPATIBLE_KEYMAP_TEXT_FORMAT,
469 "Cannot use \"LatchMods(latchOnPress=true)\" "
470 "in keymap format %d\n", format);
471 latchOnPress = false;
472 }
473 write_buf(buf, "%s%s(modifiers=%s%s%s%s%s%s)%s", prefix, type, args,
474 (action->type != ACTION_TYPE_MOD_LOCK && (action->mods.flags & ACTION_LOCK_CLEAR)) ? ",clearLocks" : "",
475 (action->type != ACTION_TYPE_MOD_LOCK && (action->mods.flags & ACTION_LATCH_TO_LOCK)) ? ",latchToLock" : "",
476 (action->type == ACTION_TYPE_MOD_LOCK) ? affect_lock_text(action->mods.flags, false) : "",
477 (unlockOnPress) ? ",unlockOnPress" : "",
478 (latchOnPress) ? ",latchOnPress" : "",
479 suffix);
480 break;
481
482 case ACTION_TYPE_GROUP_SET:
483 case ACTION_TYPE_GROUP_LATCH:
484 case ACTION_TYPE_GROUP_LOCK:
485 if ((uint32_t) xkb_abs(action->group.group) <
486 (max_groups + !(action->group.flags & ACTION_ABSOLUTE_SWITCH))) {
487 bool lockOnRelease = action->type == ACTION_TYPE_GROUP_LOCK &&
488 (action->group.flags & ACTION_LOCK_ON_RELEASE);
489 if (lockOnRelease && !isGroupLockOnReleaseSupported(format)) {
490 log_err(keymap->ctx, XKB_ERROR_INCOMPATIBLE_KEYMAP_TEXT_FORMAT,
491 "Cannot use \"GroupLock(lockOnRelease=true)\" "
492 "in keymap format %d\n", format);
493 lockOnRelease = false;
494 }
495 write_buf(buf, "%s%s(group=%s%"PRId32"%s%s%s)%s", prefix, type,
496 (!(action->group.flags & ACTION_ABSOLUTE_SWITCH) && action->group.group > 0) ? "+" : "",
497 (action->group.flags & ACTION_ABSOLUTE_SWITCH) ? action->group.group + 1 : action->group.group,
498 (action->type != ACTION_TYPE_GROUP_LOCK && (action->group.flags & ACTION_LOCK_CLEAR)) ? ",clearLocks" : "",
499 (action->type != ACTION_TYPE_GROUP_LOCK && (action->group.flags & ACTION_LATCH_TO_LOCK)) ? ",latchToLock" : "",
500 (lockOnRelease) ? ",lockOnRelease" : "",
501 suffix);
502 } else {
503 /* Unsupported group index: degrade to VoidAction() */
504 goto void_action;
505 }
506 break;
507
508 case ACTION_TYPE_TERMINATE:
509 write_buf(buf, "%s%s()%s", prefix, type, suffix);
510 break;
511
512 case ACTION_TYPE_PTR_MOVE:
513 write_buf(buf, "%s%s(x=%s%d,y=%s%d%s)%s", prefix, type,
514 (!(action->ptr.flags & ACTION_ABSOLUTE_X) && action->ptr.x >= 0) ? "+" : "",
515 action->ptr.x,
516 (!(action->ptr.flags & ACTION_ABSOLUTE_Y) && action->ptr.y >= 0) ? "+" : "",
517 action->ptr.y,
518 (action->ptr.flags & ACTION_ACCEL) ? "" : ",!accel",
519 suffix);
520 break;
521
522 case ACTION_TYPE_PTR_LOCK:
523 args = affect_lock_text(action->btn.flags, true);
524 /* fallthrough */
525 case ACTION_TYPE_PTR_BUTTON:
526 write_buf(buf, "%s%s(button=", prefix, type);
527 if (action->btn.button > 0 && action->btn.button <= 5)
528 write_buf(buf, "%u", action->btn.button);
529 else
530 copy_to_buf(buf, "default");
531 if (action->btn.count)
532 write_buf(buf, ",count=%u", action->btn.count);
533 if (args)
534 write_buf(buf, "%s", args);
535 write_buf(buf, ")%s", suffix);
536 break;
537
538 case ACTION_TYPE_PTR_DEFAULT:
539 write_buf(buf, "%s%s(", prefix, type);
540 write_buf(buf, "affect=button,button=%s%d",
541 (!(action->dflt.flags & ACTION_ABSOLUTE_SWITCH) && action->dflt.value >= 0) ? "+" : "",
542 action->dflt.value);
543 write_buf(buf, ")%s", suffix);
544 break;
545
546 case ACTION_TYPE_SWITCH_VT:
547 write_buf(buf, "%s%s(screen=%s%d,%ssame)%s", prefix, type,
548 (!(action->screen.flags & ACTION_ABSOLUTE_SWITCH) && action->screen.screen >= 0) ? "+" : "",
549 action->screen.screen,
550 (action->screen.flags & ACTION_SAME_SCREEN) ? "" : "!",
551 suffix);
552 break;
553
554 case ACTION_TYPE_CTRL_SET:
555 case ACTION_TYPE_CTRL_LOCK:
556 write_buf(buf, "%s%s(controls=%s%s)%s", prefix, type,
557 ControlMaskText(keymap->ctx, action->ctrls.ctrls),
558 (action->type == ACTION_TYPE_CTRL_LOCK) ? affect_lock_text(action->ctrls.flags, false) : "",
559 suffix);
560 break;
561
562 case ACTION_TYPE_NONE:
563 write_buf(buf, "%sNoAction()%s", prefix, suffix);
564 break;
565
566 case ACTION_TYPE_VOID:
567 void_action:
568 /*
569 * VoidAction() is a libxkbcommon extension.
570 * Use LockControls as a backward-compatible fallback.
571 * We cannot serialize it to `NoAction()`, as it would be dropped in
572 * e.g. the context of multiple actions.
573 * We better not use `Private` either, because it could still be
574 * interpreted by X11.
575 */
576 if (format == XKB_KEYMAP_FORMAT_TEXT_V1)
577 write_buf(buf, "%sLockControls(controls=none,affect=neither)%s",
578 prefix, suffix);
579 else
580 write_buf(buf, "%sVoidAction()%s", prefix, suffix);
581 break;
582
583 default:
584 {} /* Label followed by declaration requires C23 */
585 /* Ensure to not miss `xkb_action_type` updates */
586 static_assert(ACTION_TYPE_INTERNAL == 18 &&
587 ACTION_TYPE_INTERNAL + 1 == _ACTION_TYPE_NUM_ENTRIES,
588 "Missing action type");
589 /* Unsupported legacy actions should have degraded to NoAction */
590 assert(action->type != ACTION_TYPE_UNSUPPORTED_LEGACY);
591 write_buf(buf,
592 "%s%s(type=0x%02x,data[0]=0x%02x,data[1]=0x%02x,data[2]=0x%02x,data[3]=0x%02x,data[4]=0x%02x,data[5]=0x%02x,data[6]=0x%02x)%s",
593 prefix, type, action->type, action->priv.data[0],
594 action->priv.data[1], action->priv.data[2],
595 action->priv.data[3], action->priv.data[4],
596 action->priv.data[5], action->priv.data[6],
597 suffix);
598 break;
599 }
600
601 return true;
602 }
603
604 static const union xkb_action void_actions[] = {
605 { .type = ACTION_TYPE_VOID }
606 };
607
608 static bool
609 write_actions(struct xkb_keymap *keymap, enum xkb_keymap_format format,
610 xkb_layout_index_t max_groups, struct buf *buf, struct buf *buf2,
611 const struct xkb_key *key, xkb_layout_index_t group)
612 {
613 static const union xkb_action noAction = { .type = ACTION_TYPE_NONE };
614
615 for (xkb_level_index_t level = 0; level < XkbKeyNumLevels(key, group);
616 level++) {
617
618 if (level != 0)
619 copy_to_buf(buf, ", ");
620
621 const union xkb_action *actions = NULL;
622 xkb_action_count_t count = xkb_keymap_key_get_actions_by_level(
623 keymap, key, group, level, &actions
624 );
625
626 if (count > 1 && format < XKB_KEYMAP_FORMAT_TEXT_V2) {
627 /* V1: Degrade multiple actions to VoidAction() */
628 actions = void_actions;
629 count = 1;
630 log_err(keymap->ctx, XKB_ERROR_INCOMPATIBLE_KEYMAP_TEXT_FORMAT,
631 "Cannot serialize multiple actions per level "
632 "in keymap format %d; degrade to VoidAction()\n", format);
633 }
634
635 buf2->size = 0;
636 if (count == 0) {
637 if (!write_action(keymap, format, max_groups,
638 buf2, &noAction, NULL, NULL))
639 return false;
640 write_buf(buf, "%*s", ACTION_PADDING, buf2->buf);
641 }
642 else if (count == 1) {
643 if (!write_action(keymap, format, max_groups,
644 buf2, &(actions[0]), NULL, NULL))
645 return false;
646 write_buf(buf, "%*s", ACTION_PADDING, buf2->buf);
647 }
648 else {
649 copy_to_buf(buf2, "{ ");
650 for (xkb_action_count_t k = 0; k < count; k++) {
651 if (k != 0)
652 copy_to_buf(buf2, ", ");
653 size_t old_size = buf2->size;
654 if (!write_action(keymap, format, max_groups,
655 buf2, &(actions[k]), NULL, NULL))
656 return false;
657 /* Check if padding is necessary */
658 if (buf2->size >= old_size + ACTION_PADDING)
659 continue;
660 /* Compute and write padding, then write the action again */
661 const int padding = (int)(old_size + ACTION_PADDING - buf2->size);
662 buf2->size = old_size;
663 write_buf(buf2, "%*s", padding, "");
664 if (!write_action(keymap, format, max_groups,
665 buf2, &(actions[k]), NULL, NULL))
666 return false;
667 }
668 copy_to_buf(buf2, " }");
669 write_buf(buf, "%*s", ACTION_PADDING, buf2->buf);
670 }
671 }
672
673 return true;
674 }
675
676 static bool
677 write_compat(struct xkb_keymap *keymap, enum xkb_keymap_format format,
678 xkb_layout_index_t max_groups, bool drop_unused, bool pretty,
679 struct buf *buf)
680 {
681 const struct xkb_led *led;
682
683 if (keymap->compat_section_name)
684 write_buf(buf, "xkb_compatibility \"%s\" {\n",
685 keymap->compat_section_name);
686 else
687 copy_to_buf(buf, "xkb_compatibility {\n");
688
689 if (!write_vmods(keymap, format, buf))
690 return false;
691
692 copy_to_buf(buf, "\tinterpret.useModMapMods= AnyLevel;\n");
693 copy_to_buf(buf, "\tinterpret.repeat= False;\n");
694
695 /* xkbcomp requires at least one interpret entry. */
696 const darray_size_t num_sym_interprets = keymap->num_sym_interprets
697 ? keymap->num_sym_interprets
698 : 1;
699 const struct xkb_sym_interpret* const sym_interprets
700 = keymap->num_sym_interprets
701 ? keymap->sym_interprets
702 : &default_interpret;
703
704 for (darray_size_t i = 0; i < num_sym_interprets; i++) {
705 const struct xkb_sym_interpret *si = &sym_interprets[i];
706 if (!si->required && drop_unused)
707 continue;
708
709 if (pretty || !si->sym) {
710 write_buf(buf, "\tinterpret %s+%s(%s) {",
711 si->sym ? KeysymText(keymap->ctx, si->sym) : "Any",
712 SIMatchText(si->match),
713 ModMaskText(keymap->ctx, MOD_BOTH, &keymap->mods, si->mods));
714 } else {
715 write_buf(buf, "\tinterpret 0x%"PRIx32"+%s(%s) {",
716 si->sym, SIMatchText(si->match),
717 ModMaskText(keymap->ctx, MOD_BOTH, &keymap->mods, si->mods));
718 }
719
720 bool has_explicit_properties = false;
721
722 if (si->virtual_mod != XKB_MOD_INVALID) {
723 write_buf(buf, "\n\t\tvirtualModifier= %s;",
724 ModIndexText(keymap->ctx, &keymap->mods,
725 si->virtual_mod));
726 has_explicit_properties = true;
727 }
728
729 if (si->level_one_only) {
730 copy_to_buf(buf, "\n\t\tuseModMapMods=level1;");
731 has_explicit_properties = true;
732 }
733
734 if (si->repeat) {
735 copy_to_buf(buf, "\n\t\trepeat= True;");
736 has_explicit_properties = true;
737 }
738
739 const union xkb_action *action = NULL;
740 xkb_action_count_t action_count = si->num_actions;
741 if (action_count <= 1) {
742 action = &si->a.action;
743 }
744 else if (format < XKB_KEYMAP_FORMAT_TEXT_V2) {
745 /* V1: Degrade multiple actions to VoidAction() */
746 action = &void_actions[0];
747 action_count = 1;
748 log_err(keymap->ctx, XKB_ERROR_INCOMPATIBLE_KEYMAP_TEXT_FORMAT,
749 "Cannot serialize multiple actions per level "
750 "in keymap format %d; degrade to VoidAction()\n", format);
751 }
752
753 if (action_count > 1) {
754 copy_to_buf(buf, "\n\t\taction= {");
755 const char suffix[] = ", ";
756 for (xkb_action_count_t k = 0; k < si->num_actions; k++) {
757 if (!write_action(keymap, format, max_groups,
758 buf, &si->a.actions[k], "", suffix))
759 return false;
760 }
761 buf->size -= sizeof(suffix) - 1; /* trailing comma */
762 copy_to_buf(buf, "};");
763 has_explicit_properties = true;
764 } else if (action_count == 1) {
765 if (!write_action(keymap, format, max_groups, buf, action,
766 "\n\t\taction= ", ";"))
767 return false;
768 has_explicit_properties = true;
769 }
770 write_buf(buf, (has_explicit_properties
771 ? "\n\t};\n"
772 /* Empty interpret is a syntax error in xkbcomp, so
773 * use a dummy entry */
774 : "\n\t\taction= NoAction();\n\t};\n"));
775 }
776
777 xkb_leds_foreach(led, keymap)
778 if (led->which_groups || led->groups || led->which_mods ||
779 led->mods.mods || led->ctrls)
780 if (!write_led_map(keymap, buf, led))
781 return false;
782
783 copy_to_buf(buf, "};\n\n");
784
785 return true;
786 }
787
788 static bool
789 write_keysyms(struct xkb_keymap *keymap, struct buf *buf, struct buf *buf2,
790 const struct xkb_key *key, xkb_layout_index_t group,
791 bool pretty, bool show_actions)
792 {
793 const unsigned int padding = (pretty)
794 ? ((show_actions) ? ACTION_PADDING : SYMBOL_PADDING)
795 : 0;
796 for (xkb_level_index_t level = 0; level < XkbKeyNumLevels(key, group);
797 level++) {
798 const xkb_keysym_t *syms;
799 int num_syms;
800
801 if (level != 0)
802 copy_to_buf(buf, ", ");
803
804 num_syms = xkb_keymap_key_get_syms_by_level(keymap, key->keycode,
805 group, level, &syms);
806
807 const xkb_keysym_t no_symbol = XKB_KEY_NoSymbol;
808 if (num_syms == 0) {
809 num_syms = 1;
810 syms = &no_symbol;
811 }
812
813 /*
814 * NOTE: Use `NoSymbol` even without pretty output, for compatibility
815 * with xkbcomp and libxkbcommon < 1.12
816 */
817
818 if (num_syms == 1) {
819 if (pretty || syms[0] == XKB_KEY_NoSymbol)
820 write_buf(buf, "%*s", padding, KeysymText(keymap->ctx, syms[0]));
821 else
822 write_buf(buf, "0x%"PRIx32, syms[0]);
823 } else {
824 if (pretty) {
825 buf2->size = 0;
826 copy_to_buf(buf2, "{ ");
827 for (int s = 0; s < num_syms; s++) {
828 if (s != 0)
829 copy_to_buf(buf2, ", ");
830 write_buf(buf2, "%*s", (show_actions ? padding : 0),
831 KeysymText(keymap->ctx, syms[s]));
832 }
833 copy_to_buf(buf2, " }");
834 write_buf(buf, "%*s", padding, buf2->buf);
835 } else {
836 copy_to_buf(buf, "{");
837 for (int s = 0; s < num_syms; s++) {
838 if (s != 0)
839 copy_to_buf(buf, ",");
840 if (syms[s] == XKB_KEY_NoSymbol)
841 copy_to_buf(buf, "NoSymbol");
842 else
843 write_buf(buf, "0x%"PRIx32, syms[s]);
844 }
845 copy_to_buf(buf, "}");
846 }
847 }
848 }
849
850 return true;
851 }
852
853 static bool
854 write_key(struct xkb_keymap *keymap, enum xkb_keymap_format format,
855 xkb_layout_index_t max_groups, bool pretty,
856 struct buf *buf, struct buf *buf2, const struct xkb_key *key)
857 {
858 bool simple = true;
859 const xkb_layout_index_t num_groups = MIN(key->num_groups, max_groups);
860
861 if (pretty)
862 write_buf(buf, "\tkey %-20s {", KeyNameText(keymap->ctx, key->name));
863 else
864 write_buf(buf, "\tkey %s {", KeyNameText(keymap->ctx, key->name));
865
866 if (key->explicit & EXPLICIT_TYPES) {
867 simple = false;
868
869 bool multi_type = false;
870 for (xkb_layout_index_t group = 1; group < num_groups; group++) {
871 if (key->groups[group].type != key->groups[0].type) {
872 multi_type = true;
873 break;
874 }
875 }
876
877 if (multi_type) {
878 for (xkb_layout_index_t group = 0; group < num_groups; group++) {
879 if (!key->groups[group].explicit_type)
880 continue;
881
882 const struct xkb_key_type * const type = key->groups[group].type;
883 write_buf(buf, "\n\t\ttype[%"PRIu32"]= ", group + 1);
884 write_buf_string_literal(
885 buf, xkb_atom_text(keymap->ctx, type->name));
886 copy_to_buf(buf, ",");
887 }
888 }
889 else {
890 const struct xkb_key_type * const type = key->groups[0].type;
891 write_buf(buf, "\n\t\ttype= ");
892 write_buf_string_literal(
893 buf, xkb_atom_text(keymap->ctx, type->name));
894 copy_to_buf(buf, ",");
895 }
896 }
897
898 /*
899 * NOTE: we use key->explicit and not key->group[i].explicit_actions, in
900 * order to have X11 and the previous versions of libxkbcommon (without this
901 * group property) parse the keymap as intended, by setting explicitly for
902 * this key all actions in all groups.
903 *
904 * One side effect is that no interpretation will be run on this key anymore,
905 * so we may have to set some extra fields explicitly: repeat, virtualMods.
906 */
907 const bool show_actions = (key->explicit & EXPLICIT_INTERP);
908
909 /* If we show actions, interprets are not going to be used to set this
910 * field, so make it explicit. */
911 if ((key->explicit & EXPLICIT_REPEAT) || show_actions) {
912 if (key->repeats)
913 copy_to_buf(buf, "\n\t\trepeat= Yes,");
914 else
915 copy_to_buf(buf, "\n\t\trepeat= No,");
916 }
917
918 /* If we show actions, interprets are not going to be used to set this
919 * field, so make it explicit. */
920 if ((key->explicit & EXPLICIT_VMODMAP) || (show_actions && key->vmodmap))
921 write_buf(buf, "\n\t\tvirtualMods= %s,",
922 ModMaskText(keymap->ctx, MOD_BOTH, &keymap->mods,
923 key->vmodmap));
924
925 switch (key->out_of_range_group_action) {
926 case RANGE_SATURATE:
927 copy_to_buf(buf, "\n\t\tgroupsClamp,");
928 break;
929
930 case RANGE_REDIRECT:
931 if (key->out_of_range_group_number < num_groups) {
932 /* TODO: Fallback or warning if condition fails? */
933 write_buf(buf, "\n\t\tgroupsRedirect= %"PRIu32",",
934 key->out_of_range_group_number + 1);
935 }
936 break;
937
938 default:
939 break;
940 }
941
942 if (num_groups > 1 || show_actions)
943 simple = false;
944
945 if (simple) {
946 const bool only_symbols = key->explicit == EXPLICIT_SYMBOLS;
947 if (num_groups == 0) {
948 /* Remove trailing comma */
949 if (buf->buf[buf->size - 1] == ',')
950 buf->size--;
951 } else {
952 if (!only_symbols)
953 copy_to_buf(buf, "\n\t");
954 copy_to_buf(buf, "\t[ ");
955 if (!write_keysyms(keymap, buf, buf2, key, 0, pretty, false))
956 return false;
957 copy_to_buf(buf, " ]");
958 }
959 write_buf(buf, "%s", (only_symbols ? " };\n" : "\n\t};\n"));
960 }
961 else {
962 assert(num_groups > 0);
963 for (xkb_layout_index_t group = 0; group < num_groups; group++) {
964 if (group != 0)
965 copy_to_buf(buf, ",");
966 write_buf(buf, "\n\t\tsymbols[%"PRIu32"]= [ ", group + 1);
967 if (!write_keysyms(keymap, buf, buf2, key, group, pretty, show_actions))
968 return false;
969 copy_to_buf(buf, " ]");
970 if (show_actions) {
971 write_buf(buf, ",\n\t\tactions[%"PRIu32"]= [ ", group + 1);
972 if (!write_actions(keymap, format, max_groups,
973 buf, buf2, key, group))
974 return false;
975 copy_to_buf(buf, " ]");
976 }
977 }
978 copy_to_buf(buf, "\n\t};\n");
979 }
980
981 return true;
982 }
983
984 static bool
985 write_symbols(struct xkb_keymap *keymap, enum xkb_keymap_format format,
986 xkb_layout_index_t max_groups, bool pretty, struct buf *buf)
987 {
988
989 if (keymap->symbols_section_name)
990 write_buf(buf, "xkb_symbols \"%s\" {\n", keymap->symbols_section_name);
991 else
992 copy_to_buf(buf, "xkb_symbols {\n");
993
994 const xkb_layout_index_t num_group_names = MIN(keymap->num_group_names,
995 max_groups);
996 bool has_group_names = false;
997 for (xkb_layout_index_t group = 0; group < num_group_names; group++)
998 if (keymap->group_names[group]) {
999 write_buf(buf, "\tname[%"PRIu32"]=", group + 1);
1000 write_buf_string_literal(
1001 buf, xkb_atom_text(keymap->ctx, keymap->group_names[group]));
1002 copy_to_buf(buf, ";\n");
1003 has_group_names = true;
1004 }
1005 if (has_group_names)
1006 copy_to_buf(buf, "\n");
1007
1008 struct buf buf2 = { NULL, 0, 0 };
1009 const struct xkb_key *key;
1010 xkb_keys_foreach(key, keymap) {
1011 /* Skip keys with no explicit values */
1012 if (key->explicit) {
1013 if (!write_key(keymap, format, max_groups, pretty, buf, &buf2, key)) {
1014 free(buf2.buf);
1015 return false;
1016 }
1017 }
1018 }
1019 free(buf2.buf);
1020
1021 xkb_mod_index_t i;
1022 const struct xkb_mod *mod;
1023 xkb_rmods_enumerate(i, mod, &keymap->mods) {
1024 bool had_any = false;
1025 xkb_keys_foreach(key, keymap) {
1026 if (key->modmap & (UINT32_C(1) << i)) {
1027 if (!had_any)
1028 write_buf(buf, "\tmodifier_map %s { ",
1029 xkb_atom_text(keymap->ctx, mod->name));
1030 write_buf(buf, "%s%s",
1031 had_any ? ", " : "",
1032 KeyNameText(keymap->ctx, key->name));
1033 had_any = true;
1034 }
1035 }
1036 if (had_any)
1037 copy_to_buf(buf, " };\n");
1038 }
1039
1040 copy_to_buf(buf, "};\n\n");
1041 return true;
1042 }
1043
1044 static bool
1045 write_keymap(struct xkb_keymap *keymap, enum xkb_keymap_format format,
1046 enum xkb_keymap_serialize_flags flags, struct buf *buf)
1047 {
1048 const xkb_layout_index_t max_groups = format_max_groups(format);
1049 if (keymap->num_groups > max_groups) {
1050 log_err(keymap->ctx, XKB_ERROR_UNSUPPORTED_GROUP_INDEX,
1051 "Cannot serialize %"PRIu32" groups in keymap format %d: "
1052 "maximum is %"PRIu32"; discarding unsupported groups\n",
1053 keymap->num_groups, format, max_groups);
1054 }
1055
1056 const bool pretty = !!(flags & XKB_KEYMAP_SERIALIZE_PRETTY);
1057 const bool drop_unused = !(flags & XKB_KEYMAP_SERIALIZE_KEEP_UNUSED);
1058
1059 return (check_write_buf(buf, "xkb_keymap {\n") &&
1060 write_keycodes(keymap, pretty, buf) &&
1061 write_types(keymap, format, drop_unused, buf) &&
1062 write_compat(keymap, format, max_groups, drop_unused, pretty, buf) &&
1063 write_symbols(keymap, format, max_groups, pretty, buf) &&
1064 check_write_buf(buf, "};\n"));
1065 }
1066
1067 char *
1068 text_v1_keymap_get_as_string(struct xkb_keymap *keymap,
1069 enum xkb_keymap_format format,
1070 enum xkb_keymap_serialize_flags flags)
1071 {
1072 struct buf buf = { NULL, 0, 0 };
1073
1074 if (!write_keymap(keymap, format, flags, &buf)) {
1075 free(buf.buf);
1076 return NULL;
1077 }
1078
1079 return buf.buf;
1080 }