keycodes: unwrap KeyNameInfo
[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     enum merge_mode merge;
122
123     xkb_keycode_t min_key_code;
124     xkb_keycode_t max_key_code;
125     darray(xkb_atom_t) key_names;
126     darray(LedNameInfo) led_names;
127     darray(AliasInfo) aliases;
128
129     struct xkb_context *ctx;
130 } KeyNamesInfo;
131
132 /***====================================================================***/
133
134 static void
135 InitAliasInfo(AliasInfo *info, enum merge_mode merge,
136               xkb_atom_t alias, xkb_atom_t real)
137 {
138     memset(info, 0, sizeof(*info));
139     info->merge = merge;
140     info->alias = alias;
141     info->real = real;
142 }
143
144 static LedNameInfo *
145 FindLedByName(KeyNamesInfo *info, xkb_atom_t name,
146               xkb_led_index_t *idx_out)
147 {
148     LedNameInfo *ledi;
149     xkb_led_index_t idx;
150
151     darray_enumerate(idx, ledi, info->led_names) {
152         if (ledi->name == name) {
153             *idx_out = idx;
154             return ledi;
155         }
156     }
157
158     return NULL;
159 }
160
161 static bool
162 AddLedName(KeyNamesInfo *info, enum merge_mode merge, bool same_file,
163            LedNameInfo *new, xkb_led_index_t new_idx)
164 {
165     xkb_led_index_t old_idx;
166     LedNameInfo *old;
167     const int verbosity = xkb_context_get_log_verbosity(info->ctx);
168     const bool report = (same_file && verbosity > 0) || verbosity > 9;
169     const bool replace = (merge == MERGE_REPLACE || merge == MERGE_OVERRIDE);
170
171     /* LED with the same name already exists. */
172     old = FindLedByName(info, new->name, &old_idx);
173     if (old) {
174         if (old_idx == new_idx) {
175             log_warn(info->ctx,
176                      "Multiple indicators named \"%s\"; "
177                      "Identical definitions ignored\n",
178                      xkb_atom_text(info->ctx, new->name));
179             return true;
180         }
181
182         if (report) {
183             xkb_led_index_t use = (replace ? new_idx + 1 : old_idx + 1);
184             xkb_led_index_t ignore = (replace ? old_idx + 1 : new_idx + 1);
185             log_warn(info->ctx,
186                      "Multiple indicators named %s; Using %d, ignoring %d\n",
187                      xkb_atom_text(info->ctx, new->name), use, ignore);
188         }
189
190         if (replace)
191             *old = *new;
192
193         return true;
194     }
195
196     if (new_idx >= darray_size(info->led_names))
197         darray_resize0(info->led_names, new_idx + 1);
198
199     /* LED with the same index already exists. */
200     old = &darray_item(info->led_names, new_idx);
201     if (old->name != XKB_ATOM_NONE) {
202         if (report) {
203             const xkb_atom_t use = (replace ? new->name : old->name);
204             const xkb_atom_t ignore = (replace ? old->name : new->name);
205             log_warn(info->ctx, "Multiple names for indicator %d; "
206                      "Using %s, ignoring %s\n", new_idx + 1,
207                      xkb_atom_text(info->ctx, use),
208                      xkb_atom_text(info->ctx, ignore));
209         }
210
211         if (replace)
212             *old = *new;
213
214         return true;
215     }
216
217     darray_item(info->led_names, new_idx) = *new;
218     return true;
219 }
220
221 static void
222 ClearKeyNamesInfo(KeyNamesInfo *info)
223 {
224     free(info->name);
225     darray_free(info->key_names);
226     darray_free(info->aliases);
227     darray_free(info->led_names);
228 }
229
230 static void
231 InitKeyNamesInfo(KeyNamesInfo *info, struct xkb_context *ctx)
232 {
233     memset(info, 0, sizeof(*info));
234     info->ctx = ctx;
235     info->merge = MERGE_DEFAULT;
236     info->min_key_code = XKB_KEYCODE_MAX;
237 }
238
239 static xkb_keycode_t
240 FindKeyByName(KeyNamesInfo * info, xkb_atom_t name)
241 {
242     xkb_keycode_t i;
243
244     for (i = info->min_key_code; i <= info->max_key_code; i++)
245         if (darray_item(info->key_names, i) == name)
246             return i;
247
248     return XKB_KEYCODE_INVALID;
249 }
250
251 static bool
252 AddKeyName(KeyNamesInfo *info, xkb_keycode_t kc, xkb_atom_t name,
253            enum merge_mode merge, bool same_file, bool report)
254 {
255     xkb_atom_t old_name;
256     xkb_keycode_t old_kc;
257     const int verbosity = xkb_context_get_log_verbosity(info->ctx);
258
259     report = report && ((same_file && verbosity > 0) || verbosity > 7);
260
261     if (kc >= darray_size(info->key_names))
262         darray_resize0(info->key_names, kc + 1);
263
264     info->min_key_code = MIN(info->min_key_code, kc);
265     info->max_key_code = MAX(info->max_key_code, kc);
266
267     /* There's already a key with this keycode. */
268     old_name = darray_item(info->key_names, kc);
269     if (old_name != XKB_ATOM_NONE) {
270         const char *lname = KeyNameText(info->ctx, old_name);
271         const char *kname = KeyNameText(info->ctx, name);
272
273         if (old_name == name) {
274             if (report)
275                 log_warn(info->ctx,
276                          "Multiple identical key name definitions; "
277                          "Later occurrences of \"%s = %d\" ignored\n",
278                          lname, kc);
279             return true;
280         }
281         else if (merge == MERGE_AUGMENT) {
282             if (report)
283                 log_warn(info->ctx,
284                          "Multiple names for keycode %d; "
285                          "Using %s, ignoring %s\n", kc, lname, kname);
286             return true;
287         }
288         else {
289             if (report)
290                 log_warn(info->ctx,
291                          "Multiple names for keycode %d; "
292                          "Using %s, ignoring %s\n", kc, kname, lname);
293             darray_item(info->key_names, kc) = XKB_ATOM_NONE;
294         }
295     }
296
297     /* There's already a key with this name. */
298     old_kc = FindKeyByName(info, name);
299     if (old_kc != XKB_KEYCODE_INVALID && old_kc != kc) {
300         const char *kname = KeyNameText(info->ctx, name);
301
302         if (merge == MERGE_OVERRIDE) {
303             darray_item(info->key_names, old_kc) = XKB_ATOM_NONE;
304             if (report)
305                 log_warn(info->ctx,
306                          "Key name %s assigned to multiple keys; "
307                          "Using %d, ignoring %d\n", kname, kc, old_kc);
308         }
309         else {
310             if (report)
311                 log_vrb(info->ctx, 3,
312                         "Key name %s assigned to multiple keys; "
313                         "Using %d, ignoring %d\n", kname, old_kc, kc);
314             return true;
315         }
316     }
317
318     darray_item(info->key_names, kc) = name;
319     return true;
320 }
321
322 /***====================================================================***/
323
324 static int
325 HandleAliasDef(KeyNamesInfo *info, KeyAliasDef *def, enum merge_mode merge);
326
327 static void
328 MergeIncludedKeycodes(KeyNamesInfo *into, KeyNamesInfo *from,
329                       enum merge_mode merge)
330 {
331     if (from->errorCount > 0) {
332         into->errorCount += from->errorCount;
333         return;
334     }
335
336     if (into->name == NULL) {
337         into->name = from->name;
338         from->name = NULL;
339     }
340
341     /* Merge key names. */
342     if (darray_empty(into->key_names)) {
343         into->key_names = from->key_names;
344         darray_init(from->key_names);
345         into->min_key_code = from->min_key_code;
346         into->max_key_code = from->max_key_code;
347     }
348     else {
349         if (darray_size(into->key_names) < darray_size(from->key_names))
350             darray_resize0(into->key_names, darray_size(from->key_names));
351
352         for (unsigned i = from->min_key_code; i <= from->max_key_code; i++) {
353             xkb_atom_t name = darray_item(from->key_names, i);
354             if (name == XKB_ATOM_NONE)
355                 continue;
356
357             if (!AddKeyName(into, i, name, merge, true, false))
358                 into->errorCount++;
359         }
360     }
361
362     /* Merge key aliases. */
363     if (darray_empty(into->aliases)) {
364         into->aliases = from->aliases;
365         darray_init(from->aliases);
366     }
367     else {
368         AliasInfo *alias;
369
370         darray_foreach(alias, from->aliases) {
371             KeyAliasDef def;
372
373             def.merge = (merge == MERGE_DEFAULT ? alias->merge : merge);
374             def.alias = alias->alias;
375             def.real = alias->real;
376
377             if (!HandleAliasDef(into, &def, def.merge))
378                 into->errorCount++;
379         }
380     }
381
382     /* Merge LED names. */
383     if (darray_empty(into->led_names)) {
384         into->led_names = from->led_names;
385         darray_init(from->led_names);
386     }
387     else {
388         xkb_led_index_t idx;
389         LedNameInfo *ledi;
390
391         darray_enumerate(idx, ledi, from->led_names) {
392             if (ledi->name == XKB_ATOM_NONE)
393                 continue;
394
395             ledi->merge = (merge == MERGE_DEFAULT ? ledi->merge : merge);
396             if (!AddLedName(into, ledi->merge, false, ledi, idx))
397                 into->errorCount++;
398         }
399     }
400 }
401
402 static void
403 HandleKeycodesFile(KeyNamesInfo *info, XkbFile *file, enum merge_mode merge);
404
405 static bool
406 HandleIncludeKeycodes(KeyNamesInfo *info, IncludeStmt *include)
407 {
408     KeyNamesInfo included;
409
410     InitKeyNamesInfo(&included, info->ctx);
411     included.name = include->stmt;
412     include->stmt = NULL;
413
414     for (IncludeStmt *stmt = include; stmt; stmt = stmt->next_incl) {
415         KeyNamesInfo next_incl;
416         XkbFile *file;
417
418         file = ProcessIncludeFile(info->ctx, stmt, FILE_TYPE_KEYCODES);
419         if (!file) {
420             info->errorCount += 10;
421             ClearKeyNamesInfo(&included);
422             return false;
423         }
424
425         InitKeyNamesInfo(&next_incl, info->ctx);
426
427         HandleKeycodesFile(&next_incl, file, MERGE_OVERRIDE);
428
429         MergeIncludedKeycodes(&included, &next_incl, stmt->merge);
430
431         ClearKeyNamesInfo(&next_incl);
432         FreeXkbFile(file);
433     }
434
435     MergeIncludedKeycodes(info, &included, include->merge);
436     ClearKeyNamesInfo(&included);
437
438     return (info->errorCount == 0);
439 }
440
441 static bool
442 HandleKeycodeDef(KeyNamesInfo *info, KeycodeDef *stmt, enum merge_mode merge)
443 {
444     if (stmt->merge != MERGE_DEFAULT) {
445         if (stmt->merge == MERGE_REPLACE)
446             merge = MERGE_OVERRIDE;
447         else
448             merge = stmt->merge;
449     }
450
451     if (stmt->value < 0 || stmt->value > XKB_KEYCODE_MAX) {
452         log_err(info->ctx,
453                 "Illegal keycode %lld: must be between 0..%u; "
454                 "Key ignored\n", (long long) stmt->value, XKB_KEYCODE_MAX);
455         return false;
456     }
457
458     return AddKeyName(info, stmt->value, stmt->name, merge, false, true);
459 }
460
461 static int
462 HandleAliasDef(KeyNamesInfo *info, KeyAliasDef *def, enum merge_mode merge)
463 {
464     AliasInfo *old, new;
465
466     darray_foreach(old, info->aliases) {
467         if (old->alias == def->alias) {
468             if (def->real == old->real) {
469                 log_vrb(info->ctx, 1,
470                         "Alias of %s for %s declared more than once; "
471                         "First definition ignored\n",
472                         KeyNameText(info->ctx, def->alias),
473                         KeyNameText(info->ctx, def->real));
474             }
475             else {
476                 xkb_atom_t use, ignore;
477
478                 use = (merge == MERGE_AUGMENT ? old->real : def->real);
479                 ignore = (merge == MERGE_AUGMENT ? def->real : old->real);
480
481                 log_warn(info->ctx,
482                          "Multiple definitions for alias %s; "
483                          "Using %s, ignoring %s\n",
484                          KeyNameText(info->ctx, old->alias),
485                          KeyNameText(info->ctx, use),
486                          KeyNameText(info->ctx, ignore));
487
488                 old->real = use;
489             }
490
491             old->merge = merge;
492             return true;
493         }
494     }
495
496     InitAliasInfo(&new, merge, def->alias, def->real);
497     darray_append(info->aliases, new);
498     return true;
499 }
500
501 static int
502 HandleKeyNameVar(KeyNamesInfo *info, VarDef *stmt)
503 {
504     const char *elem, *field;
505     ExprDef *arrayNdx;
506
507     if (!ExprResolveLhs(info->ctx, stmt->name, &elem, &field, &arrayNdx))
508         return false;
509
510     if (elem) {
511         log_err(info->ctx, "Unknown element %s encountered; "
512                 "Default for field %s ignored\n", elem, field);
513         return false;
514     }
515
516     if (!istreq(field, "minimum") && !istreq(field, "maximum")) {
517         log_err(info->ctx, "Unknown field encountered; "
518                 "Assignment to field %s ignored\n", field);
519         return false;
520     }
521
522     /* We ignore explicit min/max statements, we always use computed. */
523     return true;
524 }
525
526 static int
527 HandleLedNameDef(KeyNamesInfo *info, LedNameDef *def,
528                  enum merge_mode merge)
529 {
530     LedNameInfo ledi;
531     xkb_atom_t name;
532
533     if (def->ndx < 1 || def->ndx > XKB_MAX_LEDS) {
534         info->errorCount++;
535         log_err(info->ctx,
536                 "Illegal indicator index (%d) specified; must be between 1 .. %d; "
537                 "Ignored\n", def->ndx, XKB_MAX_LEDS);
538         return false;
539     }
540
541     if (!ExprResolveString(info->ctx, def->name, &name)) {
542         char buf[20];
543         snprintf(buf, sizeof(buf), "%d", def->ndx);
544         info->errorCount++;
545         return ReportBadType(info->ctx, "indicator", "name", buf, "string");
546     }
547
548     ledi.merge = info->merge;
549     ledi.name = name;
550     return AddLedName(info, merge, true, &ledi, def->ndx - 1);
551 }
552
553 static void
554 HandleKeycodesFile(KeyNamesInfo *info, XkbFile *file, enum merge_mode merge)
555 {
556     bool ok;
557
558     free(info->name);
559     info->name = strdup_safe(file->name);
560
561     for (ParseCommon *stmt = file->defs; stmt; stmt = stmt->next) {
562         switch (stmt->type) {
563         case STMT_INCLUDE:
564             ok = HandleIncludeKeycodes(info, (IncludeStmt *) stmt);
565             break;
566         case STMT_KEYCODE:
567             ok = HandleKeycodeDef(info, (KeycodeDef *) stmt, merge);
568             break;
569         case STMT_ALIAS:
570             ok = HandleAliasDef(info, (KeyAliasDef *) stmt, merge);
571             break;
572         case STMT_VAR:
573             ok = HandleKeyNameVar(info, (VarDef *) stmt);
574             break;
575         case STMT_LED_NAME:
576             ok = HandleLedNameDef(info, (LedNameDef *) stmt, merge);
577             break;
578         default:
579             log_err(info->ctx,
580                     "Keycode files may define key and indicator names only; "
581                     "Ignoring %s\n", stmt_type_to_string(stmt->type));
582             ok = false;
583             break;
584         }
585
586         if (!ok)
587             info->errorCount++;
588
589         if (info->errorCount > 10) {
590             log_err(info->ctx, "Abandoning keycodes file \"%s\"\n",
591                     file->topName);
592             break;
593         }
594     }
595 }
596
597 /***====================================================================***/
598
599 static bool
600 CopyKeyNamesToKeymap(struct xkb_keymap *keymap, KeyNamesInfo *info)
601 {
602     xkb_keycode_t kc;
603     xkb_led_index_t idx;
604     LedNameInfo *ledi;
605     AliasInfo *alias;
606     unsigned i;
607
608     keymap->keycodes_section_name = strdup_safe(info->name);
609
610     keymap->min_key_code = info->min_key_code;
611     keymap->max_key_code = info->max_key_code;
612
613     /* Copy key names. */
614     keymap->keys = calloc(info->max_key_code + 1, sizeof(*keymap->keys));
615     for (kc = info->min_key_code; kc <= info->max_key_code; kc++) {
616         keymap->keys[kc].keycode = kc;
617         keymap->keys[kc].name = darray_item(info->key_names, kc);
618     }
619
620     /*
621      * Do some sanity checking on the aliases. We can't do it before
622      * because keys and their aliases may be added out-of-order.
623      */
624     keymap->num_key_aliases = 0;
625     darray_foreach(alias, info->aliases) {
626         /* Check that ->real is a key. */
627         if (!XkbKeyByName(keymap, alias->real, false)) {
628             log_vrb(info->ctx, 5,
629                     "Attempt to alias %s to non-existent key %s; Ignored\n",
630                     KeyNameText(info->ctx, alias->alias),
631                     KeyNameText(info->ctx, alias->real));
632             alias->real = XKB_ATOM_NONE;
633             continue;
634         }
635
636         /* Check that ->alias is not a key. */
637         if (XkbKeyByName(keymap, alias->alias, false)) {
638             log_vrb(info->ctx, 5,
639                     "Attempt to create alias with the name of a real key; "
640                     "Alias \"%s = %s\" ignored\n",
641                     KeyNameText(info->ctx, alias->alias),
642                     KeyNameText(info->ctx, alias->real));
643             alias->real = XKB_ATOM_NONE;
644             continue;
645         }
646
647         keymap->num_key_aliases++;
648     }
649
650     /* Copy key aliases. */
651     keymap->key_aliases = calloc(keymap->num_key_aliases,
652                                  sizeof(*keymap->key_aliases));
653     i = 0;
654     darray_foreach(alias, info->aliases) {
655         if (alias->real != XKB_ATOM_NONE) {
656             keymap->key_aliases[i].alias = alias->alias;
657             keymap->key_aliases[i].real = alias->real;
658             i++;
659         }
660     }
661
662     /* Copy LED names. */
663     darray_resize0(keymap->leds, darray_size(info->led_names));
664     darray_enumerate(idx, ledi, info->led_names)
665         if (ledi->name != XKB_ATOM_NONE)
666             darray_item(keymap->leds, idx).name = ledi->name;
667
668     return true;
669 }
670
671 /***====================================================================***/
672
673 bool
674 CompileKeycodes(XkbFile *file, struct xkb_keymap *keymap,
675                 enum merge_mode merge)
676 {
677     KeyNamesInfo info;
678
679     InitKeyNamesInfo(&info, keymap->ctx);
680
681     HandleKeycodesFile(&info, file, merge);
682     if (info.errorCount != 0)
683         goto err_info;
684
685     if (!CopyKeyNamesToKeymap(keymap, &info))
686         goto err_info;
687
688     ClearKeyNamesInfo(&info);
689     return true;
690
691 err_info:
692     ClearKeyNamesInfo(&info);
693     return false;
694 }