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