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