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