Remove xkbcomp/misc.c
[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 "expr.h"
29 #include "parseutils.h"
30
31 /*
32  * The xkb_keycodes section
33  * ========================
34  *
35  * This is the simplest section type, and is the first one to be
36  * compiled. The purpose of this is mostly to map between the
37  * hardware/evdev scancodes and xkb keycodes. Each key is given a name
38  * of up to 4 letters, by which it can be referred to later, e.g. in the
39  * symbols section.
40  *
41  * Minimum/Maximum keycode
42  * -----------------------
43  * Statements of the form:
44  *      minimum = 8;
45  *      maximum = 255;
46  *
47  * The file may explicitly declare the minimum and/or maximum keycode
48  * contained therein (traditionally 8-255, inherited from old xfree86
49  * keycodes). If these are stated explicitly, they are enforced. If
50  * they are not stated, they are computed automatically.
51  *
52  * Keycode statements
53  * ------------------
54  * Statements of the form:
55  *      <TLDE> = 49;
56  *      <AE01> = 10;
57  *
58  * The above would let 49 and 10 be valid keycodes in the keymap, and
59  * assign them the names TLDE and AE01 respectively. The format <WXYZ> is
60  * always used to refer to a key by name.
61  *
62  * [ The naming convention <AE01> just denoted the position of the key
63  * in the main alphanumric section of the keyboard, with the top left key
64  * (usually "~") acting as origin. <AE01> is the key in the first row
65  * second column (which is usually "1"). ]
66  *
67  * In the common case this just maps to the evdev scancodes from
68  * /usr/include/linux/input.h, e.g. the following definitions:
69  *      #define KEY_GRAVE            41
70  *      #define KEY_1                2
71  * Similar definitions appear in the xf86-input-keyboard driver. Note
72  * that in all current keymaps there's a constant offset of 8 (for
73  * historical reasons).
74  *
75  * If there's a conflict, like the same name given to different keycodes,
76  * or same keycode given different names, it is resolved according to the
77  * merge mode which applies to the definitions.
78  *
79  * The reason for the 4 characters limit is that the name is sometimes
80  * converted to an unsigned long (in a direct mapping), instead of a char
81  * array (see KeyNameToLong, LongToKeyName).
82  *
83  * Alias statements
84  * ----------------
85  * Statements of the form:
86  *      alias <MENU> = <COMP>;
87  *
88  * Allows to refer to a previously defined key (here <COMP>) by another
89  * name (here <MENU>). Conflicts are handled similarly.
90  *
91  * Indicator name statements
92  * -------------------------
93  * Statements of the form:
94  *      indicator 1 = "Caps Lock";
95  *      indicator 2 = "Num Lock";
96  *      indicator 3 = "Scroll Lock";
97  *
98  * Assigns a name the indicator (i.e. keyboard LED) with the given index.
99  * The amount of possible indicators is predetermined (XkbNumIndicators).
100  * The indicator may be referred by this name later in the compat section
101  * and by the user.
102  *
103  * Effect on the keymap
104  * --------------------
105  * After all of keycodes sections have been compiled, the following members
106  * of struct xkb_keymap are finalized:
107  *      xkb_keycode_t min_key_code;
108  *      xkb_keycode_t max_key_code;
109  *      darray(struct xkb_key_alias) key_aliases;
110  *      const char *indicator_names[XkbNumIndicators];
111  *      char *keycodes_section_name;
112  * Further, the array of keys:
113  *      darray(struct xkb_key) keys;
114  * had been resized to its final size (i.e. all of the xkb_key objects are
115  * referable by their keycode). However the objects themselves do not
116  * contain any useful information besides the key name at this point.
117  */
118
119 typedef struct _AliasInfo {
120     enum merge_mode merge;
121     unsigned file_id;
122     struct list entry;
123
124     unsigned long alias;
125     unsigned long real;
126 } AliasInfo;
127
128 typedef struct _IndicatorNameInfo {
129     enum merge_mode merge;
130     unsigned file_id;
131     struct list entry;
132
133     xkb_led_index_t ndx;
134     xkb_atom_t name;
135     bool virtual;
136 } IndicatorNameInfo;
137
138 typedef struct _KeyNamesInfo {
139     char *name;     /* e.g. evdev+aliases(qwerty) */
140     int errorCount;
141     unsigned file_id;
142     enum merge_mode merge;
143     xkb_keycode_t computedMin; /* lowest keycode stored */
144     xkb_keycode_t computedMax; /* highest keycode stored */
145     xkb_keycode_t explicitMin;
146     xkb_keycode_t explicitMax;
147     darray(unsigned long) names;
148     darray(unsigned int) files;
149     struct list leds;
150     struct list aliases;
151
152     struct xkb_keymap *keymap;
153 } KeyNamesInfo;
154
155 static void
156 ResizeKeyNameArrays(KeyNamesInfo *info, int newMax)
157 {
158     if (newMax < darray_size(info->names))
159         return;
160
161     darray_resize0(info->names, newMax + 1);
162     darray_resize0(info->files, newMax + 1);
163 }
164
165 static void
166 InitAliasInfo(AliasInfo *info, enum merge_mode merge, unsigned file_id,
167               char alias[XkbKeyNameLength], char real[XkbKeyNameLength])
168 {
169     memset(info, 0, sizeof(*info));
170     info->merge = merge;
171     info->file_id = file_id;
172     info->alias = KeyNameToLong(alias);
173     info->real = KeyNameToLong(real);
174 }
175
176 static void
177 InitIndicatorNameInfo(IndicatorNameInfo * ii, KeyNamesInfo * info)
178 {
179     ii->merge = info->merge;
180     ii->file_id = info->file_id;
181     ii->ndx = 0;
182     ii->name = XKB_ATOM_NONE;
183     ii->virtual = false;
184 }
185
186 static IndicatorNameInfo *
187 NextIndicatorName(KeyNamesInfo * info)
188 {
189     IndicatorNameInfo *ii;
190
191     ii = malloc(sizeof(*ii));
192     if (!ii)
193         return NULL;
194
195     InitIndicatorNameInfo(ii, info);
196     list_append(&ii->entry, &info->leds);
197
198     return ii;
199 }
200
201 static IndicatorNameInfo *
202 FindIndicatorByIndex(KeyNamesInfo * info, xkb_led_index_t ndx)
203 {
204     IndicatorNameInfo *old;
205
206     list_foreach(old, &info->leds, entry)
207         if (old->ndx == ndx)
208             return old;
209
210     return NULL;
211 }
212
213 static IndicatorNameInfo *
214 FindIndicatorByName(KeyNamesInfo * info, xkb_atom_t name)
215 {
216     IndicatorNameInfo *old;
217
218     list_foreach(old, &info->leds, entry)
219         if (old->name == name)
220             return old;
221
222     return NULL;
223 }
224
225 static bool
226 AddIndicatorName(KeyNamesInfo *info, enum merge_mode merge,
227                  IndicatorNameInfo *new)
228 {
229     IndicatorNameInfo *old;
230     bool replace;
231     int verbosity = xkb_get_log_verbosity(info->keymap->ctx);
232
233     replace = (merge == MERGE_REPLACE) || (merge == MERGE_OVERRIDE);
234
235     old = FindIndicatorByName(info, new->name);
236     if (old) {
237         if ((old->file_id == new->file_id && verbosity > 0) ||
238             verbosity > 9) {
239             if (old->ndx == new->ndx) {
240                 if (old->virtual != new->virtual) {
241                     if (replace)
242                         old->virtual = new->virtual;
243                     log_warn(info->keymap->ctx, "Multiple indicators named %s; "
244                              "Using %s instead of %s\n",
245                              xkb_atom_text(info->keymap->ctx, new->name),
246                              (old->virtual ? "virtual" : "real"),
247                              (old->virtual ? "real" : "virtual"));
248                 }
249                 else {
250                     log_warn(info->keymap->ctx, "Multiple indicators named %s; "
251                              "Identical definitions ignored\n",
252                              xkb_atom_text(info->keymap->ctx, new->name));
253                 }
254                 return true;
255             }
256             else {
257                 log_warn(info->keymap->ctx, "Multiple indicators named %s; "
258                          "Using %d, ignoring %d\n",
259                          xkb_atom_text(info->keymap->ctx, new->name),
260                          (replace ? old->ndx : new->ndx),
261                          (replace ? new->ndx : old->ndx));
262             }
263
264             if (replace) {
265                 list_del(&old->entry);
266                 free(old);
267             }
268         }
269     }
270
271     old = FindIndicatorByIndex(info, new->ndx);
272     if (old) {
273         if ((old->file_id == new->file_id && verbosity > 0) ||
274             verbosity > 9) {
275             if (old->name == new->name && old->virtual == new->virtual) {
276                 log_warn(info->keymap->ctx,
277                          "Multiple names for indicator %d; "
278                          "Identical definitions ignored\n", new->ndx);
279             } else {
280                 const char *oldType, *newType;
281                 xkb_atom_t using, ignoring;
282                 if (old->virtual)
283                     oldType = "virtual indicator";
284                 else
285                     oldType = "real indicator";
286                 if (new->virtual)
287                     newType = "virtual indicator";
288                 else
289                     newType = "real indicator";
290                 if (replace) {
291                     using = new->name;
292                     ignoring = old->name;
293                 }
294                 else {
295                     using = old->name;
296                     ignoring = new->name;
297                 }
298                 log_warn(info->keymap->ctx,
299                          "Multiple names for indicator %d; "
300                          "Using %s %s, ignoring %s %s\n",
301                          new->ndx,
302                          oldType, xkb_atom_text(info->keymap->ctx, using),
303                          newType, xkb_atom_text(info->keymap->ctx, ignoring));
304             }
305         }
306         if (replace) {
307             old->name = new->name;
308             old->virtual = new->virtual;
309         }
310         return true;
311     }
312     old = new;
313     new = NextIndicatorName(info);
314     if (!new) {
315         log_wsgo(info->keymap->ctx,
316                  "Couldn't allocate name for indicator %d; Ignored\n",
317                  old->ndx);
318         return false;
319     }
320     new->name = old->name;
321     new->ndx = old->ndx;
322     new->virtual = old->virtual;
323     return true;
324 }
325
326 static void
327 ClearKeyNamesInfo(KeyNamesInfo * info)
328 {
329     AliasInfo *alias, *next_alias;
330     IndicatorNameInfo *ii, *next_ii;
331
332     free(info->name);
333     info->name = NULL;
334     info->merge = MERGE_DEFAULT;
335     info->computedMax = info->explicitMax = info->explicitMin = 0;
336     info->computedMin = XKB_KEYCODE_MAX;
337     darray_free(info->names);
338     darray_free(info->files);
339     list_foreach_safe(ii, next_ii, &info->leds, entry)
340         free(ii);
341     list_init(&info->leds);
342     list_foreach_safe(alias, next_alias, &info->aliases, entry)
343         free(alias);
344     list_init(&info->aliases);
345 }
346
347 static void
348 InitKeyNamesInfo(KeyNamesInfo *info, struct xkb_keymap *keymap,
349                  unsigned file_id)
350 {
351     info->name = NULL;
352     info->merge = MERGE_DEFAULT;
353     list_init(&info->leds);
354     list_init(&info->aliases);
355     info->file_id = file_id;
356     darray_init(info->names);
357     darray_init(info->files);
358     ClearKeyNamesInfo(info);
359     info->errorCount = 0;
360     info->keymap = keymap;
361 }
362
363 static int
364 FindKeyByLong(KeyNamesInfo * info, unsigned long name)
365 {
366     xkb_keycode_t i;
367
368     for (i = info->computedMin; i <= info->computedMax; i++)
369         if (darray_item(info->names, i) == name)
370             return i;
371
372     return 0;
373 }
374
375 /**
376  * Store the name of the key as a long in the info struct under the given
377  * keycode. If the same keys is referred to twice, print a warning.
378  * Note that the key's name is stored as a long, the keycode is the index.
379  */
380 static bool
381 AddKeyName(KeyNamesInfo *info, xkb_keycode_t kc, unsigned long name,
382            enum merge_mode merge, unsigned file_id, bool reportCollisions)
383 {
384     xkb_keycode_t old;
385     int verbosity = xkb_get_log_verbosity(info->keymap->ctx);
386
387     ResizeKeyNameArrays(info, kc);
388
389     if (kc < info->computedMin)
390         info->computedMin = kc;
391     if (kc > info->computedMax)
392         info->computedMax = kc;
393
394     if (reportCollisions)
395         reportCollisions = (verbosity > 7 ||
396                             (verbosity > 0 &&
397                              file_id == darray_item(info->files, kc)));
398
399     if (darray_item(info->names, kc) != 0) {
400         const char *lname = LongKeyNameText(darray_item(info->names, kc));
401         const char *kname = LongKeyNameText(name);
402
403         if (darray_item(info->names, kc) == name && reportCollisions) {
404             log_warn(info->keymap->ctx,
405                      "Multiple identical key name definitions; "
406                      "Later occurences of \"%s = %d\" ignored\n", lname, kc);
407             return true;
408         }
409
410         if (merge == MERGE_AUGMENT) {
411             if (reportCollisions)
412                 log_warn(info->keymap->ctx,
413                          "Multiple names for keycode %d; "
414                          "Using %s, ignoring %s\n", kc, lname, kname);
415             return true;
416         }
417         else {
418             if (reportCollisions)
419                 log_warn(info->keymap->ctx,
420                          "Multiple names for keycode %d; "
421                          "Using %s, ignoring %s\n", kc, kname, lname);
422             darray_item(info->names, kc) = 0;
423             darray_item(info->files, kc) = 0;
424         }
425     }
426
427     old = FindKeyByLong(info, name);
428     if (old != 0 && old != kc) {
429         const char *kname = LongKeyNameText(name);
430
431         if (merge == MERGE_OVERRIDE) {
432             darray_item(info->names, old) = 0;
433             darray_item(info->files, old) = 0;
434             if (reportCollisions)
435                 log_warn(info->keymap->ctx,
436                          "Key name %s assigned to multiple keys; "
437                          "Using %d, ignoring %d\n", kname, kc, old);
438         }
439         else {
440             if (reportCollisions && verbosity > 3)
441                 log_warn(info->keymap->ctx,
442                          "Key name %s assigned to multiple keys; "
443                          "Using %d, ignoring %d\n", kname, old, kc);
444             return true;
445         }
446     }
447
448     darray_item(info->names, kc) = name;
449     darray_item(info->files, kc) = file_id;
450     return true;
451 }
452
453 /***====================================================================***/
454
455 static int
456 HandleAliasDef(KeyNamesInfo *info, KeyAliasDef *def, enum merge_mode merge,
457                unsigned file_id);
458
459 static bool
460 MergeAliases(KeyNamesInfo *into, KeyNamesInfo *from, enum merge_mode merge)
461 {
462     AliasInfo *alias, *next;
463     KeyAliasDef def;
464
465     if (list_empty(&from->aliases))
466         return true;
467
468     if (list_empty(&into->aliases)) {
469         list_replace(&from->aliases, &into->aliases);
470         list_init(&from->aliases);
471         return true;
472     }
473
474     memset(&def, 0, sizeof(def));
475
476     list_foreach_safe(alias, next, &from->aliases, entry) {
477         def.merge = (merge == MERGE_DEFAULT) ? alias->merge : merge;
478         LongToKeyName(alias->alias, def.alias);
479         LongToKeyName(alias->real, def.real);
480
481         if (!HandleAliasDef(into, &def, def.merge, alias->file_id))
482             return false;
483     }
484
485     return true;
486 }
487
488 static void
489 MergeIncludedKeycodes(KeyNamesInfo *into, KeyNamesInfo *from,
490                       enum merge_mode merge)
491 {
492     xkb_keycode_t i;
493     IndicatorNameInfo *led;
494
495     if (from->errorCount > 0) {
496         into->errorCount += from->errorCount;
497         return;
498     }
499
500     if (into->name == NULL) {
501         into->name = from->name;
502         from->name = NULL;
503     }
504
505     ResizeKeyNameArrays(into, from->computedMax);
506
507     for (i = from->computedMin; i <= from->computedMax; i++) {
508         unsigned long name = darray_item(from->names, i);
509         if (name == 0)
510             continue;
511
512         if (!AddKeyName(into, i, name, merge, from->file_id, false))
513             into->errorCount++;
514     }
515
516     list_foreach(led, &from->leds, entry) {
517         led->merge = (merge == MERGE_DEFAULT ? led->merge : merge);
518         if (!AddIndicatorName(into, led->merge, led))
519             into->errorCount++;
520     }
521
522     if (!MergeAliases(into, from, merge))
523         into->errorCount++;
524
525     if (from->explicitMin != 0)
526         if (into->explicitMin == 0 || into->explicitMin > from->explicitMin)
527             into->explicitMin = from->explicitMin;
528
529     if (from->explicitMax > 0)
530         if (into->explicitMax == 0 || into->explicitMax < from->explicitMax)
531             into->explicitMax = from->explicitMax;
532 }
533
534 static void
535 HandleKeycodesFile(KeyNamesInfo *info, XkbFile *file, enum merge_mode merge);
536
537 /**
538  * Handle the given include statement (e.g. "include "evdev+aliases(qwerty)").
539  *
540  * @param info Struct to store the key info in.
541  * @param stmt The include statement from the keymap file.
542  */
543 static bool
544 HandleIncludeKeycodes(KeyNamesInfo *info, IncludeStmt *stmt)
545 {
546     enum merge_mode merge = MERGE_DEFAULT;
547     XkbFile *rtrn;
548     KeyNamesInfo included, next_incl;
549
550     InitKeyNamesInfo(&included, info->keymap, info->file_id);
551     if (stmt->stmt) {
552         free(included.name);
553         included.name = stmt->stmt;
554         stmt->stmt = NULL;
555     }
556
557     for (; stmt; stmt = stmt->next_incl) {
558         if (!ProcessIncludeFile(info->keymap->ctx, stmt, FILE_TYPE_KEYCODES,
559                                 &rtrn, &merge)) {
560             info->errorCount += 10;
561             ClearKeyNamesInfo(&included);
562             return false;
563         }
564
565         InitKeyNamesInfo(&next_incl, info->keymap, rtrn->id);
566
567         HandleKeycodesFile(&next_incl, rtrn, MERGE_OVERRIDE);
568
569         MergeIncludedKeycodes(&included, &next_incl, merge);
570
571         ClearKeyNamesInfo(&next_incl);
572         FreeXKBFile(rtrn);
573     }
574
575     MergeIncludedKeycodes(info, &included, merge);
576     ClearKeyNamesInfo(&included);
577
578     return (info->errorCount == 0);
579 }
580
581 /**
582  * Parse the given statement and store the output in the info struct.
583  * e.g. <ESC> = 9
584  */
585 static int
586 HandleKeycodeDef(KeyNamesInfo *info, KeycodeDef *stmt, enum merge_mode merge)
587 {
588     if ((info->explicitMin != 0 && stmt->value < info->explicitMin) ||
589         (info->explicitMax != 0 && stmt->value > info->explicitMax)) {
590         log_err(info->keymap->ctx,
591                 "Illegal keycode %lu for name %s; "
592                 "Must be in the range %d-%d inclusive\n",
593                 stmt->value, KeyNameText(stmt->name), info->explicitMin,
594                 info->explicitMax ? info->explicitMax : XKB_KEYCODE_MAX);
595         return 0;
596     }
597
598     if (stmt->merge != MERGE_DEFAULT) {
599         if (stmt->merge == MERGE_REPLACE)
600             merge = MERGE_OVERRIDE;
601         else
602             merge = stmt->merge;
603     }
604
605     return AddKeyName(info, stmt->value, KeyNameToLong(stmt->name), merge,
606                       info->file_id, true);
607 }
608
609 static void
610 HandleAliasCollision(KeyNamesInfo *info, AliasInfo *old, AliasInfo *new)
611 {
612     int verbosity = xkb_get_log_verbosity(info->keymap->ctx);
613
614     if (new->real == old->real) {
615         if ((new->file_id == old->file_id && verbosity > 0) || verbosity > 9)
616             log_warn(info->keymap->ctx,
617                      "Alias of %s for %s declared more than once; "
618                      "First definition ignored\n",
619                      LongKeyNameText(new->alias), LongKeyNameText(new->real));
620     }
621     else {
622         unsigned long use, ignore;
623
624         if (new->merge == MERGE_AUGMENT) {
625             use = old->real;
626             ignore = new->real;
627         }
628         else {
629             use = new->real;
630             ignore = old->real;
631         }
632
633         if ((old->file_id == new->file_id && verbosity > 0) || verbosity > 9)
634             log_warn(info->keymap->ctx,
635                      "Multiple definitions for alias %s; "
636                      "Using %s, ignoring %s\n",
637                      LongKeyNameText(old->alias), LongKeyNameText(use),
638                      LongKeyNameText(ignore));
639
640         if (use != old->real)
641             old->real = use;
642     }
643
644     old->file_id = new->file_id;
645     old->merge = new->merge;
646 }
647
648 static int
649 HandleAliasDef(KeyNamesInfo *info, KeyAliasDef *def, enum merge_mode merge,
650                unsigned file_id)
651 {
652     AliasInfo *alias;
653
654     list_foreach(alias, &info->aliases, entry) {
655         if (alias->alias == KeyNameToLong(def->alias)) {
656             AliasInfo new;
657             InitAliasInfo(&new, merge, file_id, def->alias, def->real);
658             HandleAliasCollision(info, alias, &new);
659             return true;
660         }
661     }
662
663     alias = calloc(1, sizeof(*alias));
664     if (!alias) {
665         log_wsgo(info->keymap->ctx, "Allocation failure in HandleAliasDef\n");
666         return false;
667     }
668
669     alias->file_id = file_id;
670     alias->merge = merge;
671     alias->alias = KeyNameToLong(def->alias);
672     alias->real = KeyNameToLong(def->real);
673     list_append(&alias->entry, &info->aliases);
674
675     return true;
676 }
677
678 #define MIN_KEYCODE_DEF 0
679 #define MAX_KEYCODE_DEF 1
680
681 /**
682  * Handle the minimum/maximum statement of the xkb file.
683  * Sets explicitMin/Max of the info struct.
684  *
685  * @return 1 on success, 0 otherwise.
686  */
687 static int
688 HandleKeyNameVar(KeyNamesInfo *info, VarDef *stmt)
689 {
690     const char *elem, *field;
691     xkb_keycode_t kc;
692     ExprDef *arrayNdx;
693     int which;
694
695     if (!ExprResolveLhs(info->keymap->ctx, stmt->name, &elem, &field,
696                         &arrayNdx))
697         return false;               /* internal error, already reported */
698
699     if (elem) {
700         log_err(info->keymap->ctx,
701                 "Unknown element %s encountered; "
702                 "Default for field %s ignored\n", elem, field);
703         return false;
704     }
705
706     if (istreq(field, "minimum")) {
707         which = MIN_KEYCODE_DEF;
708     }
709     else if (istreq(field, "maximum")) {
710         which = MAX_KEYCODE_DEF;
711     }
712     else {
713         log_err(info->keymap->ctx,
714                 "Unknown field encountered; "
715                 "Assigment to field %s ignored\n", field);
716         return false;
717     }
718
719     if (arrayNdx != NULL) {
720         log_err(info->keymap->ctx,
721                 "The %s setting is not an array; "
722                 "Illegal array reference ignored\n", field);
723         return false;
724     }
725
726     if (!ExprResolveKeyCode(info->keymap->ctx, stmt->value, &kc)) {
727         log_err(info->keymap->ctx,
728                 "Illegal keycode encountered; "
729                 "Assignment to field %s ignored\n", field);
730         return false;
731     }
732
733     if (kc > XKB_KEYCODE_MAX) {
734         log_err(info->keymap->ctx,
735                 "Illegal keycode %d (must be in the range %d-%d inclusive); "
736                 "Value of \"%s\" not changed\n",
737                 kc, 0, XKB_KEYCODE_MAX, field);
738         return false;
739     }
740
741     if (which == MIN_KEYCODE_DEF) {
742         if (info->explicitMax > 0 && info->explicitMax < kc) {
743             log_err(info->keymap->ctx,
744                     "Minimum key code (%d) must be <= maximum key code (%d); "
745                     "Minimum key code value not changed\n",
746                     kc, info->explicitMax);
747             return false;
748         }
749
750         if (info->computedMax > 0 && info->computedMin < kc) {
751             log_err(info->keymap->ctx,
752                     "Minimum key code (%d) must be <= lowest defined key (%d); "
753                     "Minimum key code value not changed\n",
754                     kc, info->computedMin);
755             return false;
756         }
757
758         info->explicitMin = kc;
759     }
760     else if (which == MAX_KEYCODE_DEF) {
761         if (info->explicitMin > 0 && info->explicitMin > kc) {
762             log_err(info->keymap->ctx,
763                     "Maximum code (%d) must be >= minimum key code (%d); "
764                     "Maximum code value not changed\n",
765                     kc, info->explicitMin);
766             return false;
767         }
768
769         if (info->computedMax > 0 && info->computedMax > kc) {
770             log_err(info->keymap->ctx,
771                     "Maximum code (%d) must be >= highest defined key (%d); "
772                     "Maximum code value not changed\n",
773                     kc, info->computedMax);
774             return false;
775         }
776
777         info->explicitMax = kc;
778     }
779
780     return true;
781 }
782
783 static int
784 HandleIndicatorNameDef(KeyNamesInfo *info, IndicatorNameDef *def,
785                        enum merge_mode merge)
786 {
787     IndicatorNameInfo ii;
788     const char *str;
789
790     if (def->ndx < 1 || def->ndx > XkbNumIndicators) {
791         info->errorCount++;
792         log_err(info->keymap->ctx,
793                 "Name specified for illegal indicator index %d\n; Ignored\n",
794                 def->ndx);
795         return false;
796     }
797
798     InitIndicatorNameInfo(&ii, info);
799
800     if (!ExprResolveString(info->keymap->ctx, def->name, &str)) {
801         char buf[20];
802         snprintf(buf, sizeof(buf), "%d", def->ndx);
803         info->errorCount++;
804         return ReportBadType(info->keymap, "indicator", "name", buf,
805                              "string");
806     }
807
808     ii.ndx = (xkb_led_index_t) def->ndx;
809     ii.name = xkb_atom_intern(info->keymap->ctx, str);
810     ii.virtual = def->virtual;
811
812     return AddIndicatorName(info, merge, &ii);
813 }
814
815 /**
816  * Handle the xkb_keycodes section of a xkb file.
817  * All information about parsed keys is stored in the info struct.
818  *
819  * Such a section may have include statements, in which case this function is
820  * semi-recursive (it calls HandleIncludeKeycodes, which may call
821  * HandleKeycodesFile again).
822  *
823  * @param info Struct to contain the fully parsed key information.
824  * @param file The input file (parsed xkb_keycodes section)
825  * @param merge Merge strategy (MERGE_OVERRIDE, etc.)
826  */
827 static void
828 HandleKeycodesFile(KeyNamesInfo *info, XkbFile *file, enum merge_mode merge)
829 {
830     ParseCommon *stmt;
831     bool ok;
832
833     free(info->name);
834     info->name = strdup_safe(file->name);
835
836     for (stmt = file->defs; stmt; stmt = stmt->next) {
837         switch (stmt->type) {
838         case STMT_INCLUDE:    /* e.g. include "evdev+aliases(qwerty)" */
839             ok = HandleIncludeKeycodes(info, (IncludeStmt *) stmt);
840             break;
841         case STMT_KEYCODE: /* e.g. <ESC> = 9; */
842             ok = HandleKeycodeDef(info, (KeycodeDef *) stmt, merge);
843             break;
844         case STMT_ALIAS: /* e.g. alias <MENU> = <COMP>; */
845             ok = HandleAliasDef(info, (KeyAliasDef *) stmt, merge,
846                                 info->file_id);
847             break;
848         case STMT_VAR: /* e.g. minimum, maximum */
849             ok = HandleKeyNameVar(info, (VarDef *) stmt);
850             break;
851         case STMT_INDICATOR_NAME: /* e.g. indicator 1 = "Caps Lock"; */
852             ok = HandleIndicatorNameDef(info, (IndicatorNameDef *) stmt,
853                                         merge);
854             break;
855         default:
856             log_err(info->keymap->ctx,
857                     "Keycode files may define key and indicator names only; "
858                     "Ignoring %s\n", StmtTypeToString(stmt->type));
859             ok = false;
860             break;
861         }
862
863         if (!ok)
864             info->errorCount++;
865
866         if (info->errorCount > 10) {
867             log_err(info->keymap->ctx, "Abandoning keycodes file \"%s\"\n",
868                     file->topName);
869             break;
870         }
871     }
872 }
873
874 static int
875 ApplyAliases(KeyNamesInfo *info)
876 {
877     int i;
878     struct xkb_key *key;
879     struct xkb_key_alias *old, *a;
880     AliasInfo *alias, *next;
881     int nNew = 0, nOld;
882     struct xkb_keymap *keymap = info->keymap;
883
884     nOld = darray_size(keymap->key_aliases);
885     old = &darray_item(keymap->key_aliases, 0);
886
887     list_foreach(alias, &info->aliases, entry) {
888         key = FindNamedKey(keymap, alias->real, false, 0);
889         if (!key) {
890             log_lvl(info->keymap->ctx, 5,
891                     "Attempt to alias %s to non-existent key %s; Ignored\n",
892                     LongKeyNameText(alias->alias),
893                     LongKeyNameText(alias->real));
894             alias->alias = 0;
895             continue;
896         }
897
898         key = FindNamedKey(keymap, alias->alias, false, 0);
899         if (key) {
900             log_lvl(info->keymap->ctx, 5,
901                     "Attempt to create alias with the name of a real key; "
902                     "Alias \"%s = %s\" ignored\n",
903                     LongKeyNameText(alias->alias),
904                     LongKeyNameText(alias->real));
905             alias->alias = 0;
906             continue;
907         }
908
909         nNew++;
910
911         if (!old)
912             continue;
913
914         for (i = 0, a = old; i < nOld; i++, a++) {
915             AliasInfo old_alias;
916
917             if (KeyNameToLong(a->alias) == alias->alias)
918                 continue;
919
920             InitAliasInfo(&old_alias, MERGE_AUGMENT, 0, a->alias, a->real);
921             HandleAliasCollision(info, &old_alias, alias);
922             old_alias.real = KeyNameToLong(a->real);
923             alias->alias = 0;
924             nNew--;
925             break;
926         }
927     }
928
929     if (nNew == 0)
930         goto out;
931
932     darray_resize0(keymap->key_aliases, nOld + nNew);
933
934     a = &darray_item(keymap->key_aliases, nOld);
935     list_foreach(alias, &info->aliases, entry) {
936         if (alias->alias != 0) {
937             LongToKeyName(alias->alias, a->alias);
938             LongToKeyName(alias->real, a->real);
939             a++;
940         }
941     }
942
943 out:
944     list_foreach_safe(alias, next, &info->aliases, entry)
945         free(alias);
946     list_init(&info->aliases);
947     return true;
948 }
949
950 /**
951  * Compile the xkb_keycodes section, parse it's output, return the results.
952  *
953  * @param file The parsed XKB file (may have include statements requiring
954  * further parsing)
955  * @param result The effective keycodes, as gathered from the file.
956  * @param merge Merge strategy.
957  *
958  * @return true on success, false otherwise.
959  */
960 bool
961 CompileKeycodes(XkbFile *file, struct xkb_keymap *keymap,
962                 enum merge_mode merge)
963 {
964     xkb_keycode_t kc;
965     KeyNamesInfo info; /* contains all the info after parsing */
966     IndicatorNameInfo *ii;
967
968     InitKeyNamesInfo(&info, keymap, file->id);
969
970     HandleKeycodesFile(&info, file, merge);
971
972     /* all the keys are now stored in info */
973
974     if (info.errorCount != 0)
975         goto err_info;
976
977     if (info.explicitMin > 0) /* if "minimum" statement was present */
978         keymap->min_key_code = info.explicitMin;
979     else
980         keymap->min_key_code = info.computedMin;
981
982     if (info.explicitMax > 0) /* if "maximum" statement was present */
983         keymap->max_key_code = info.explicitMax;
984     else
985         keymap->max_key_code = info.computedMax;
986
987     darray_resize0(keymap->keys, keymap->max_key_code + 1);
988     for (kc = info.computedMin; kc <= info.computedMax; kc++)
989         LongToKeyName(darray_item(info.names, kc),
990                       XkbKey(keymap, kc)->name);
991
992     keymap->keycodes_section_name = strdup_safe(info.name);
993
994     list_foreach(ii, &info.leds, entry)
995         keymap->indicator_names[ii->ndx - 1] =
996             xkb_atom_text(keymap->ctx, ii->name);
997
998     ApplyAliases(&info);
999
1000     ClearKeyNamesInfo(&info);
1001     return true;
1002
1003 err_info:
1004     ClearKeyNamesInfo(&info);
1005     return false;
1006 }
1007
1008 /**
1009  * Find the key with the given name.
1010  *
1011  * @param keymap The keymap to search in.
1012  * @param name The 4-letter name of the key as a long.
1013  * @param use_aliases true if the key aliases should be searched too.
1014  * @param start_from Keycode to start searching from.
1015  *
1016  * @return the key if it is found, NULL otherwise.
1017  */
1018 struct xkb_key *
1019 FindNamedKey(struct xkb_keymap *keymap, unsigned long name,
1020              bool use_aliases, xkb_keycode_t start_from)
1021 {
1022     struct xkb_key *key;
1023
1024     if (start_from < keymap->min_key_code)
1025         start_from = keymap->min_key_code;
1026     else if (start_from > keymap->max_key_code)
1027         return NULL;
1028
1029     xkb_foreach_key_from(key, keymap, start_from)
1030         if (KeyNameToLong(key->name) == name)
1031             return key;
1032
1033     if (use_aliases) {
1034         unsigned long new_name;
1035         if (FindKeyNameForAlias(keymap, name, &new_name))
1036             return FindNamedKey(keymap, new_name, false, 0);
1037     }
1038
1039     return NULL;
1040 }
1041
1042 bool
1043 FindKeyNameForAlias(struct xkb_keymap *keymap, unsigned long lname,
1044                     unsigned long *real_name)
1045 {
1046     char name[XkbKeyNameLength];
1047     struct xkb_key_alias *a;
1048
1049     LongToKeyName(lname, name);
1050     darray_foreach(a, keymap->key_aliases) {
1051         if (strncmp(name, a->alias, XkbKeyNameLength) == 0) {
1052             *real_name = KeyNameToLong(a->real);
1053             return true;
1054         }
1055     }
1056
1057     return false;
1058 }