parser: drop %name-prefix, use -p yacc argument instead
[platform/upstream/libxkbcommon.git] / src / xkbcomp / keycodes.c
1 /************************************************************
2  * Copyright (c) 1994 by Silicon Graphics Computer Systems, Inc.
3  *
4  * Permission to use, copy, modify, and distribute this
5  * software and its documentation for any purpose and without
6  * fee is hereby granted, provided that the above copyright
7  * notice appear in all copies and that both that copyright
8  * notice and this permission notice appear in supporting
9  * documentation, and that the name of Silicon Graphics not be
10  * used in advertising or publicity pertaining to distribution
11  * of the software without specific prior written permission.
12  * Silicon Graphics makes no representation about the suitability
13  * of this software for any purpose. It is provided "as is"
14  * without any express or implied warranty.
15  *
16  * SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
17  * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
18  * AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
19  * GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
20  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
21  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
22  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION  WITH
23  * THE USE OR PERFORMANCE OF THIS SOFTWARE.
24  *
25  ********************************************************/
26
27 #include "xkbcomp-priv.h"
28 #include "text.h"
29 #include "expr.h"
30 #include "include.h"
31
32 /*
33  * The xkb_keycodes section
34  * ========================
35  *
36  * This is the simplest section type, and is the first one to be
37  * compiled. The purpose of this is mostly to map between the
38  * hardware/evdev scancodes and xkb keycodes. Each key is given a name
39  * by which it can be referred to later, e.g. in the symbols section.
40  *
41  * Keycode statements
42  * ------------------
43  * Statements of the form:
44  *      <TLDE> = 49;
45  *      <AE01> = 10;
46  *
47  * The above would let 49 and 10 be valid keycodes in the keymap, and
48  * assign them the names TLDE and AE01 respectively. The format <WXYZ> is
49  * always used to refer to a key by name.
50  *
51  * [ The naming convention <AE01> just denoted the position of the key
52  * in the main alphanumric section of the keyboard, with the two letters
53  * specifying the row and the two digits specifying the column, from
54  * the bottom left.]
55  *
56  * In the common case this just maps to the evdev scancodes from
57  * /usr/include/linux/input.h, e.g. the following definitions:
58  *      #define KEY_GRAVE            41
59  *      #define KEY_1                2
60  * Similar definitions appear in the xf86-input-keyboard driver. Note
61  * that in all current keymaps there's a constant offset of 8 (for
62  * historical reasons).
63  *
64  * If there's a conflict, like the same name given to different keycodes,
65  * or same keycode given different names, it is resolved according to the
66  * merge mode which applies to the definitions.
67  *
68  * Alias statements
69  * ----------------
70  * Statements of the form:
71  *      alias <MENU> = <COMP>;
72  *
73  * Allows to refer to a previously defined key (here <COMP>) by another
74  * name (here <MENU>). Conflicts are handled similarly.
75  *
76  * LED name statements
77  * -------------------------
78  * Statements of the form:
79  *      indicator 1 = "Caps Lock";
80  *      indicator 2 = "Num Lock";
81  *      indicator 3 = "Scroll Lock";
82  *
83  * Assigns a name to the keyboard LED (a.k.a indicator) with the given index.
84  * The led may be referred by this name later in the compat section
85  * and by the user.
86  *
87  * Effect on the keymap
88  * --------------------
89  * After all of the xkb_keycodes sections have been compiled, the
90  * following members of struct xkb_keymap are finalized:
91  *      xkb_keycode_t min_key_code;
92  *      xkb_keycode_t max_key_code;
93  *      unsigned int num_aliases;
94  *      struct xkb_key_alias *key_aliases;
95  *      char *keycodes_section_name;
96  * The 'name' field of leds declared in xkb_keycodes:
97  *      darray(struct xkb_led) leds;
98  * Further, the array of keys:
99  *      struct xkb_key *keys;
100  * had been resized to its final size (i.e. all of the xkb_key objects are
101  * referable by their keycode). However the objects themselves do not
102  * contain any useful information besides the key name at this point.
103  */
104
105 typedef struct {
106     enum merge_mode merge;
107
108     xkb_atom_t alias;
109     xkb_atom_t real;
110 } AliasInfo;
111
112 typedef struct {
113     enum merge_mode merge;
114
115     xkb_atom_t name;
116 } LedNameInfo;
117
118 typedef struct {
119     char *name;
120     int errorCount;
121
122     xkb_keycode_t min_key_code;
123     xkb_keycode_t max_key_code;
124     darray(xkb_atom_t) key_names;
125     darray(LedNameInfo) led_names;
126     darray(AliasInfo) aliases;
127
128     struct xkb_context *ctx;
129 } KeyNamesInfo;
130
131 /***====================================================================***/
132
133 static void
134 InitAliasInfo(AliasInfo *info, enum merge_mode merge,
135               xkb_atom_t alias, xkb_atom_t real)
136 {
137     memset(info, 0, sizeof(*info));
138     info->merge = merge;
139     info->alias = alias;
140     info->real = real;
141 }
142
143 static LedNameInfo *
144 FindLedByName(KeyNamesInfo *info, xkb_atom_t name,
145               xkb_led_index_t *idx_out)
146 {
147     LedNameInfo *ledi;
148     xkb_led_index_t idx;
149
150     darray_enumerate(idx, ledi, info->led_names) {
151         if (ledi->name == name) {
152             *idx_out = idx;
153             return ledi;
154         }
155     }
156
157     return NULL;
158 }
159
160 static bool
161 AddLedName(KeyNamesInfo *info, enum merge_mode merge, bool same_file,
162            LedNameInfo *new, xkb_led_index_t new_idx)
163 {
164     xkb_led_index_t old_idx;
165     LedNameInfo *old;
166     const int verbosity = xkb_context_get_log_verbosity(info->ctx);
167     const bool report = (same_file && verbosity > 0) || verbosity > 9;
168     const bool replace = (merge == MERGE_REPLACE || merge == MERGE_OVERRIDE);
169
170     /* LED with the same name already exists. */
171     old = FindLedByName(info, new->name, &old_idx);
172     if (old) {
173         if (old_idx == new_idx) {
174             log_warn(info->ctx,
175                      "Multiple indicators named \"%s\"; "
176                      "Identical definitions ignored\n",
177                      xkb_atom_text(info->ctx, new->name));
178             return true;
179         }
180
181         if (report) {
182             xkb_led_index_t use = (replace ? new_idx + 1 : old_idx + 1);
183             xkb_led_index_t ignore = (replace ? old_idx + 1 : new_idx + 1);
184             log_warn(info->ctx,
185                      "Multiple indicators named %s; Using %d, ignoring %d\n",
186                      xkb_atom_text(info->ctx, new->name), use, ignore);
187         }
188
189         if (replace)
190             *old = *new;
191
192         return true;
193     }
194
195     if (new_idx >= darray_size(info->led_names))
196         darray_resize0(info->led_names, new_idx + 1);
197
198     /* LED with the same index already exists. */
199     old = &darray_item(info->led_names, new_idx);
200     if (old->name != XKB_ATOM_NONE) {
201         if (report) {
202             const xkb_atom_t use = (replace ? new->name : old->name);
203             const xkb_atom_t ignore = (replace ? old->name : new->name);
204             log_warn(info->ctx, "Multiple names for indicator %d; "
205                      "Using %s, ignoring %s\n", new_idx + 1,
206                      xkb_atom_text(info->ctx, use),
207                      xkb_atom_text(info->ctx, ignore));
208         }
209
210         if (replace)
211             *old = *new;
212
213         return true;
214     }
215
216     darray_item(info->led_names, new_idx) = *new;
217     return true;
218 }
219
220 static void
221 ClearKeyNamesInfo(KeyNamesInfo *info)
222 {
223     free(info->name);
224     darray_free(info->key_names);
225     darray_free(info->aliases);
226     darray_free(info->led_names);
227 }
228
229 static void
230 InitKeyNamesInfo(KeyNamesInfo *info, struct xkb_context *ctx)
231 {
232     memset(info, 0, sizeof(*info));
233     info->ctx = ctx;
234     info->min_key_code = XKB_KEYCODE_INVALID;
235 #if XKB_KEYCODE_INVALID < XKB_KEYCODE_MAX
236 #error "Hey, you can't be changing stuff like that."
237 #endif
238 }
239
240 static xkb_keycode_t
241 FindKeyByName(KeyNamesInfo *info, xkb_atom_t name)
242 {
243     xkb_keycode_t i;
244
245     for (i = info->min_key_code; i <= info->max_key_code; i++)
246         if (darray_item(info->key_names, i) == name)
247             return i;
248
249     return XKB_KEYCODE_INVALID;
250 }
251
252 static bool
253 AddKeyName(KeyNamesInfo *info, xkb_keycode_t kc, xkb_atom_t name,
254            enum merge_mode merge, bool same_file, bool report)
255 {
256     xkb_atom_t old_name;
257     xkb_keycode_t old_kc;
258     const int verbosity = xkb_context_get_log_verbosity(info->ctx);
259
260     report = report && ((same_file && verbosity > 0) || verbosity > 7);
261
262     if (kc >= darray_size(info->key_names))
263         darray_resize0(info->key_names, kc + 1);
264
265     info->min_key_code = MIN(info->min_key_code, kc);
266     info->max_key_code = MAX(info->max_key_code, kc);
267
268     /* There's already a key with this keycode. */
269     old_name = darray_item(info->key_names, kc);
270     if (old_name != XKB_ATOM_NONE) {
271         const char *lname = KeyNameText(info->ctx, old_name);
272         const char *kname = KeyNameText(info->ctx, name);
273
274         if (old_name == name) {
275             if (report)
276                 log_warn(info->ctx,
277                          "Multiple identical key name definitions; "
278                          "Later occurrences of \"%s = %d\" ignored\n",
279                          lname, kc);
280             return true;
281         }
282         else if (merge == MERGE_AUGMENT) {
283             if (report)
284                 log_warn(info->ctx,
285                          "Multiple names for keycode %d; "
286                          "Using %s, ignoring %s\n", kc, lname, kname);
287             return true;
288         }
289         else {
290             if (report)
291                 log_warn(info->ctx,
292                          "Multiple names for keycode %d; "
293                          "Using %s, ignoring %s\n", kc, kname, lname);
294             darray_item(info->key_names, kc) = XKB_ATOM_NONE;
295         }
296     }
297
298     /* There's already a key with this name. */
299     old_kc = FindKeyByName(info, name);
300     if (old_kc != XKB_KEYCODE_INVALID && old_kc != kc) {
301         const char *kname = KeyNameText(info->ctx, name);
302
303         if (merge == MERGE_OVERRIDE) {
304             darray_item(info->key_names, old_kc) = XKB_ATOM_NONE;
305             if (report)
306                 log_warn(info->ctx,
307                          "Key name %s assigned to multiple keys; "
308                          "Using %d, ignoring %d\n", kname, kc, old_kc);
309         }
310         else {
311             if (report)
312                 log_vrb(info->ctx, 3,
313                         "Key name %s assigned to multiple keys; "
314                         "Using %d, ignoring %d\n", kname, old_kc, kc);
315             return true;
316         }
317     }
318
319     darray_item(info->key_names, kc) = name;
320     return true;
321 }
322
323 /***====================================================================***/
324
325 static int
326 HandleAliasDef(KeyNamesInfo *info, KeyAliasDef *def, enum merge_mode merge);
327
328 static void
329 MergeIncludedKeycodes(KeyNamesInfo *into, KeyNamesInfo *from,
330                       enum merge_mode merge)
331 {
332     if (from->errorCount > 0) {
333         into->errorCount += from->errorCount;
334         return;
335     }
336
337     if (into->name == NULL) {
338         into->name = from->name;
339         from->name = NULL;
340     }
341
342     /* Merge key names. */
343     if (darray_empty(into->key_names)) {
344         into->key_names = from->key_names;
345         darray_init(from->key_names);
346         into->min_key_code = from->min_key_code;
347         into->max_key_code = from->max_key_code;
348     }
349     else {
350         if (darray_size(into->key_names) < darray_size(from->key_names))
351             darray_resize0(into->key_names, darray_size(from->key_names));
352
353         for (unsigned i = from->min_key_code; i <= from->max_key_code; i++) {
354             xkb_atom_t name = darray_item(from->key_names, i);
355             if (name == XKB_ATOM_NONE)
356                 continue;
357
358             if (!AddKeyName(into, i, name, merge, true, false))
359                 into->errorCount++;
360         }
361     }
362
363     /* Merge key aliases. */
364     if (darray_empty(into->aliases)) {
365         into->aliases = from->aliases;
366         darray_init(from->aliases);
367     }
368     else {
369         AliasInfo *alias;
370
371         darray_foreach(alias, from->aliases) {
372             KeyAliasDef def;
373
374             def.merge = (merge == MERGE_DEFAULT ? alias->merge : merge);
375             def.alias = alias->alias;
376             def.real = alias->real;
377
378             if (!HandleAliasDef(into, &def, def.merge))
379                 into->errorCount++;
380         }
381     }
382
383     /* Merge LED names. */
384     if (darray_empty(into->led_names)) {
385         into->led_names = from->led_names;
386         darray_init(from->led_names);
387     }
388     else {
389         xkb_led_index_t idx;
390         LedNameInfo *ledi;
391
392         darray_enumerate(idx, ledi, from->led_names) {
393             if (ledi->name == XKB_ATOM_NONE)
394                 continue;
395
396             ledi->merge = (merge == MERGE_DEFAULT ? ledi->merge : merge);
397             if (!AddLedName(into, ledi->merge, false, ledi, idx))
398                 into->errorCount++;
399         }
400     }
401 }
402
403 static void
404 HandleKeycodesFile(KeyNamesInfo *info, XkbFile *file, enum merge_mode merge);
405
406 static bool
407 HandleIncludeKeycodes(KeyNamesInfo *info, IncludeStmt *include)
408 {
409     KeyNamesInfo included;
410
411     InitKeyNamesInfo(&included, info->ctx);
412     included.name = include->stmt;
413     include->stmt = NULL;
414
415     for (IncludeStmt *stmt = include; stmt; stmt = stmt->next_incl) {
416         KeyNamesInfo next_incl;
417         XkbFile *file;
418
419         file = ProcessIncludeFile(info->ctx, stmt, FILE_TYPE_KEYCODES);
420         if (!file) {
421             info->errorCount += 10;
422             ClearKeyNamesInfo(&included);
423             return false;
424         }
425
426         InitKeyNamesInfo(&next_incl, info->ctx);
427
428         HandleKeycodesFile(&next_incl, file, MERGE_OVERRIDE);
429
430         MergeIncludedKeycodes(&included, &next_incl, stmt->merge);
431
432         ClearKeyNamesInfo(&next_incl);
433         FreeXkbFile(file);
434     }
435
436     MergeIncludedKeycodes(info, &included, include->merge);
437     ClearKeyNamesInfo(&included);
438
439     return (info->errorCount == 0);
440 }
441
442 static bool
443 HandleKeycodeDef(KeyNamesInfo *info, KeycodeDef *stmt, enum merge_mode merge)
444 {
445     if (stmt->merge != MERGE_DEFAULT) {
446         if (stmt->merge == MERGE_REPLACE)
447             merge = MERGE_OVERRIDE;
448         else
449             merge = stmt->merge;
450     }
451
452     if (stmt->value < 0 || stmt->value > XKB_KEYCODE_MAX) {
453         log_err(info->ctx,
454                 "Illegal keycode %lld: must be between 0..%u; "
455                 "Key ignored\n", (long long) stmt->value, XKB_KEYCODE_MAX);
456         return false;
457     }
458
459     return AddKeyName(info, stmt->value, stmt->name, merge, false, true);
460 }
461
462 static int
463 HandleAliasDef(KeyNamesInfo *info, KeyAliasDef *def, enum merge_mode merge)
464 {
465     AliasInfo *old, new;
466
467     darray_foreach(old, info->aliases) {
468         if (old->alias == def->alias) {
469             if (def->real == old->real) {
470                 log_vrb(info->ctx, 1,
471                         "Alias of %s for %s declared more than once; "
472                         "First definition ignored\n",
473                         KeyNameText(info->ctx, def->alias),
474                         KeyNameText(info->ctx, def->real));
475             }
476             else {
477                 xkb_atom_t use, ignore;
478
479                 use = (merge == MERGE_AUGMENT ? old->real : def->real);
480                 ignore = (merge == MERGE_AUGMENT ? def->real : old->real);
481
482                 log_warn(info->ctx,
483                          "Multiple definitions for alias %s; "
484                          "Using %s, ignoring %s\n",
485                          KeyNameText(info->ctx, old->alias),
486                          KeyNameText(info->ctx, use),
487                          KeyNameText(info->ctx, ignore));
488
489                 old->real = use;
490             }
491
492             old->merge = merge;
493             return true;
494         }
495     }
496
497     InitAliasInfo(&new, merge, def->alias, def->real);
498     darray_append(info->aliases, new);
499     return true;
500 }
501
502 static int
503 HandleKeyNameVar(KeyNamesInfo *info, VarDef *stmt)
504 {
505     const char *elem, *field;
506     ExprDef *arrayNdx;
507
508     if (!ExprResolveLhs(info->ctx, stmt->name, &elem, &field, &arrayNdx))
509         return false;
510
511     if (elem) {
512         log_err(info->ctx, "Unknown element %s encountered; "
513                 "Default for field %s ignored\n", elem, field);
514         return false;
515     }
516
517     if (!istreq(field, "minimum") && !istreq(field, "maximum")) {
518         log_err(info->ctx, "Unknown field encountered; "
519                 "Assignment to field %s ignored\n", field);
520         return false;
521     }
522
523     /* We ignore explicit min/max statements, we always use computed. */
524     return true;
525 }
526
527 static int
528 HandleLedNameDef(KeyNamesInfo *info, LedNameDef *def,
529                  enum merge_mode merge)
530 {
531     LedNameInfo ledi;
532     xkb_atom_t name;
533
534     if (def->ndx < 1 || def->ndx > XKB_MAX_LEDS) {
535         info->errorCount++;
536         log_err(info->ctx,
537                 "Illegal indicator index (%d) specified; must be between 1 .. %d; "
538                 "Ignored\n", def->ndx, XKB_MAX_LEDS);
539         return false;
540     }
541
542     if (!ExprResolveString(info->ctx, def->name, &name)) {
543         char buf[20];
544         snprintf(buf, sizeof(buf), "%d", def->ndx);
545         info->errorCount++;
546         return ReportBadType(info->ctx, "indicator", "name", buf, "string");
547     }
548
549     ledi.merge = merge;
550     ledi.name = name;
551     return AddLedName(info, merge, true, &ledi, def->ndx - 1);
552 }
553
554 static void
555 HandleKeycodesFile(KeyNamesInfo *info, XkbFile *file, enum merge_mode merge)
556 {
557     bool ok;
558
559     free(info->name);
560     info->name = strdup_safe(file->name);
561
562     for (ParseCommon *stmt = file->defs; stmt; stmt = stmt->next) {
563         switch (stmt->type) {
564         case STMT_INCLUDE:
565             ok = HandleIncludeKeycodes(info, (IncludeStmt *) stmt);
566             break;
567         case STMT_KEYCODE:
568             ok = HandleKeycodeDef(info, (KeycodeDef *) stmt, merge);
569             break;
570         case STMT_ALIAS:
571             ok = HandleAliasDef(info, (KeyAliasDef *) stmt, merge);
572             break;
573         case STMT_VAR:
574             ok = HandleKeyNameVar(info, (VarDef *) stmt);
575             break;
576         case STMT_LED_NAME:
577             ok = HandleLedNameDef(info, (LedNameDef *) stmt, merge);
578             break;
579         default:
580             log_err(info->ctx,
581                     "Keycode files may define key and indicator names only; "
582                     "Ignoring %s\n", stmt_type_to_string(stmt->type));
583             ok = false;
584             break;
585         }
586
587         if (!ok)
588             info->errorCount++;
589
590         if (info->errorCount > 10) {
591             log_err(info->ctx, "Abandoning keycodes file \"%s\"\n",
592                     file->topName);
593             break;
594         }
595     }
596 }
597
598 /***====================================================================***/
599
600 static bool
601 CopyKeyNamesToKeymap(struct xkb_keymap *keymap, KeyNamesInfo *info)
602 {
603     xkb_keycode_t kc;
604     xkb_led_index_t idx;
605     LedNameInfo *ledi;
606     AliasInfo *alias;
607     unsigned i;
608
609     keymap->keycodes_section_name = strdup_safe(info->name);
610     XkbEscapeMapName(keymap->keycodes_section_name);
611
612     if (info->min_key_code != XKB_KEYCODE_INVALID) {
613         keymap->min_key_code = info->min_key_code;
614         keymap->max_key_code = info->max_key_code;
615     }
616     else {
617         /*
618          * If the keymap has no keys, let's just use the safest pair
619          * we know.
620          */
621         keymap->min_key_code = 8;
622         keymap->max_key_code = 255;
623     }
624
625     keymap->keys = calloc(keymap->max_key_code + 1, sizeof(*keymap->keys));
626     for (kc = keymap->min_key_code; kc <= keymap->max_key_code; kc++)
627         keymap->keys[kc].keycode = kc;
628
629     /* Copy key names. */
630     for (kc = info->min_key_code; kc <= info->max_key_code; kc++)
631         keymap->keys[kc].name = darray_item(info->key_names, kc);
632
633     /*
634      * Do some sanity checking on the aliases. We can't do it before
635      * because keys and their aliases may be added out-of-order.
636      */
637     keymap->num_key_aliases = 0;
638     darray_foreach(alias, info->aliases) {
639         /* Check that ->real is a key. */
640         if (!XkbKeyByName(keymap, alias->real, false)) {
641             log_vrb(info->ctx, 5,
642                     "Attempt to alias %s to non-existent key %s; Ignored\n",
643                     KeyNameText(info->ctx, alias->alias),
644                     KeyNameText(info->ctx, alias->real));
645             alias->real = XKB_ATOM_NONE;
646             continue;
647         }
648
649         /* Check that ->alias is not a key. */
650         if (XkbKeyByName(keymap, alias->alias, false)) {
651             log_vrb(info->ctx, 5,
652                     "Attempt to create alias with the name of a real key; "
653                     "Alias \"%s = %s\" ignored\n",
654                     KeyNameText(info->ctx, alias->alias),
655                     KeyNameText(info->ctx, alias->real));
656             alias->real = XKB_ATOM_NONE;
657             continue;
658         }
659
660         keymap->num_key_aliases++;
661     }
662
663     /* Copy key aliases. */
664     keymap->key_aliases = calloc(keymap->num_key_aliases,
665                                  sizeof(*keymap->key_aliases));
666     i = 0;
667     darray_foreach(alias, info->aliases) {
668         if (alias->real != XKB_ATOM_NONE) {
669             keymap->key_aliases[i].alias = alias->alias;
670             keymap->key_aliases[i].real = alias->real;
671             i++;
672         }
673     }
674
675     /* Copy LED names. */
676     darray_resize0(keymap->leds, darray_size(info->led_names));
677     darray_enumerate(idx, ledi, info->led_names)
678         if (ledi->name != XKB_ATOM_NONE)
679             darray_item(keymap->leds, idx).name = ledi->name;
680
681     return true;
682 }
683
684 /***====================================================================***/
685
686 bool
687 CompileKeycodes(XkbFile *file, struct xkb_keymap *keymap,
688                 enum merge_mode merge)
689 {
690     KeyNamesInfo info;
691
692     InitKeyNamesInfo(&info, keymap->ctx);
693
694     HandleKeycodesFile(&info, file, merge);
695     if (info.errorCount != 0)
696         goto err_info;
697
698     if (!CopyKeyNamesToKeymap(keymap, &info))
699         goto err_info;
700
701     ClearKeyNamesInfo(&info);
702     return true;
703
704 err_info:
705     ClearKeyNamesInfo(&info);
706     return false;
707 }