3688af4fa226425df5749f122e4dcb2b22e23c82
[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 the xkb_keycodes sections have been compiled, the
108  * following members 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  *      char *keycodes_section_name;
113  * The 'name' field of indicators declared in xkb_keycodes:
114  *      struct xkb_indicator_map indicators[XkbNumIndicators];
115  * Further, the array of keys:
116  *      darray(struct xkb_key) keys;
117  * had been resized to its final size (i.e. all of the xkb_key objects are
118  * referable by their keycode). However the objects themselves do not
119  * contain any useful information besides the key name at this point.
120  */
121
122 typedef struct _AliasInfo {
123     enum merge_mode merge;
124     unsigned file_id;
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
134     xkb_atom_t name;
135 } IndicatorNameInfo;
136
137 typedef struct _KeyNamesInfo {
138     char *name;     /* e.g. evdev+aliases(qwerty) */
139     int errorCount;
140     unsigned file_id;
141     enum merge_mode merge;
142
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     IndicatorNameInfo indicator_names[XkbNumIndicators];
150     darray(AliasInfo) aliases;
151
152     struct xkb_context *ctx;
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[XKB_KEY_NAME_LENGTH], char real[XKB_KEY_NAME_LENGTH])
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 IndicatorNameInfo *
177 FindIndicatorByName(KeyNamesInfo *info, xkb_atom_t name,
178                     xkb_led_index_t *idx_out)
179 {
180     xkb_led_index_t idx;
181
182     for (idx = 0; idx < XkbNumIndicators; idx++) {
183         if (info->indicator_names[idx].name == name) {
184             *idx_out = idx;
185             return &info->indicator_names[idx];
186         }
187     }
188
189     return NULL;
190 }
191
192 static bool
193 AddIndicatorName(KeyNamesInfo *info, enum merge_mode merge,
194                  IndicatorNameInfo *new, xkb_led_index_t new_idx)
195 {
196     xkb_led_index_t old_idx;
197     IndicatorNameInfo *old;
198     bool replace, report;
199     int verbosity = xkb_get_log_verbosity(info->ctx);
200
201     replace = (merge == MERGE_REPLACE) || (merge == MERGE_OVERRIDE);
202
203     old = FindIndicatorByName(info, new->name, &old_idx);
204     if (old) {
205         report = ((old->file_id == new->file_id && verbosity > 0) ||
206                   verbosity > 9);
207
208         if (old_idx == new_idx) {
209             if (report)
210                 log_warn(info->ctx, "Multiple indicators named %s; "
211                          "Identical definitions ignored\n",
212                          xkb_atom_text(info->ctx, new->name));
213             return true;
214         }
215
216         if (report)
217             log_warn(info->ctx, "Multiple indicators named %s; "
218                      "Using %d, ignoring %d\n",
219                      xkb_atom_text(info->ctx, new->name),
220                      (replace ? old_idx + 1 : new_idx + 1),
221                      (replace ? new_idx + 1 : old_idx + 1));
222
223         /*
224          * XXX: If in the next check we ignore new, than we will have
225          * deleted this old for nothing!
226          */
227         if (replace)
228             memset(old, 0, sizeof(*old));
229     }
230
231     old = &info->indicator_names[new_idx];
232     if (old->name != XKB_ATOM_NONE) {
233         report = ((old->file_id == new->file_id && verbosity > 0) ||
234                   verbosity > 9);
235
236         if (old->name == new->name) {
237             if (report)
238                 log_warn(info->ctx, "Multiple names for indicator %d; "
239                          "Identical definitions ignored\n", new_idx + 1);
240         }
241         else if (replace) {
242             if (report)
243                 log_warn(info->ctx, "Multiple names for indicator %d; "
244                          "Using %s, ignoring %s\n", new_idx + 1,
245                          xkb_atom_text(info->ctx, new->name),
246                          xkb_atom_text(info->ctx, old->name));
247             old->name = new->name;
248         }
249         else {
250             if (report)
251                 log_warn(info->ctx, "Multiple names for indicator %d; "
252                          "Using %s, ignoring %s\n", new_idx + 1,
253                          xkb_atom_text(info->ctx, old->name),
254                          xkb_atom_text(info->ctx, new->name));
255         }
256
257         return true;
258     }
259
260     info->indicator_names[new_idx] = *new;
261     return true;
262 }
263
264 static void
265 ClearKeyNamesInfo(KeyNamesInfo * info)
266 {
267     free(info->name);
268     info->name = NULL;
269     info->merge = MERGE_DEFAULT;
270     info->computedMax = info->explicitMax = info->explicitMin = 0;
271     info->computedMin = XKB_KEYCODE_MAX;
272     darray_free(info->names);
273     darray_free(info->files);
274     memset(info->indicator_names, 0, sizeof(info->indicator_names));
275     darray_free(info->aliases);
276 }
277
278 static void
279 InitKeyNamesInfo(KeyNamesInfo *info, struct xkb_context *ctx,
280                  unsigned file_id)
281 {
282     info->name = NULL;
283     info->merge = MERGE_DEFAULT;
284     darray_init(info->aliases);
285     info->file_id = file_id;
286     darray_init(info->names);
287     darray_init(info->files);
288     ClearKeyNamesInfo(info);
289     info->errorCount = 0;
290     info->ctx = ctx;
291 }
292
293 static int
294 FindKeyByLong(KeyNamesInfo * info, unsigned long name)
295 {
296     xkb_keycode_t i;
297
298     for (i = info->computedMin; i <= info->computedMax; i++)
299         if (darray_item(info->names, i) == name)
300             return i;
301
302     return 0;
303 }
304
305 /**
306  * Store the name of the key as a long in the info struct under the given
307  * keycode. If the same keys is referred to twice, print a warning.
308  * Note that the key's name is stored as a long, the keycode is the index.
309  */
310 static bool
311 AddKeyName(KeyNamesInfo *info, xkb_keycode_t kc, unsigned long name,
312            enum merge_mode merge, unsigned file_id, bool reportCollisions)
313 {
314     xkb_keycode_t old;
315     int verbosity = xkb_get_log_verbosity(info->ctx);
316
317     ResizeKeyNameArrays(info, kc);
318
319     if (kc < info->computedMin)
320         info->computedMin = kc;
321     if (kc > info->computedMax)
322         info->computedMax = kc;
323
324     if (reportCollisions)
325         reportCollisions = (verbosity > 7 ||
326                             (verbosity > 0 &&
327                              file_id == darray_item(info->files, kc)));
328
329     if (darray_item(info->names, kc) != 0) {
330         const char *lname = LongKeyNameText(darray_item(info->names, kc));
331         const char *kname = LongKeyNameText(name);
332
333         if (darray_item(info->names, kc) == name && reportCollisions) {
334             log_warn(info->ctx, "Multiple identical key name definitions; "
335                      "Later occurences of \"%s = %d\" ignored\n", lname, kc);
336             return true;
337         }
338
339         if (merge == MERGE_AUGMENT) {
340             if (reportCollisions)
341                 log_warn(info->ctx, "Multiple names for keycode %d; "
342                          "Using %s, ignoring %s\n", kc, lname, kname);
343             return true;
344         }
345         else {
346             if (reportCollisions)
347                 log_warn(info->ctx, "Multiple names for keycode %d; "
348                          "Using %s, ignoring %s\n", kc, kname, lname);
349             darray_item(info->names, kc) = 0;
350             darray_item(info->files, kc) = 0;
351         }
352     }
353
354     old = FindKeyByLong(info, name);
355     if (old != 0 && old != kc) {
356         const char *kname = LongKeyNameText(name);
357
358         if (merge == MERGE_OVERRIDE) {
359             darray_item(info->names, old) = 0;
360             darray_item(info->files, old) = 0;
361             if (reportCollisions)
362                 log_warn(info->ctx, "Key name %s assigned to multiple keys; "
363                          "Using %d, ignoring %d\n", kname, kc, old);
364         }
365         else {
366             if (reportCollisions && verbosity > 3)
367                 log_warn(info->ctx, "Key name %s assigned to multiple keys; "
368                          "Using %d, ignoring %d\n", kname, old, kc);
369             return true;
370         }
371     }
372
373     darray_item(info->names, kc) = name;
374     darray_item(info->files, kc) = file_id;
375     return true;
376 }
377
378 /***====================================================================***/
379
380 static int
381 HandleAliasDef(KeyNamesInfo *info, KeyAliasDef *def, enum merge_mode merge,
382                unsigned file_id);
383
384 static bool
385 MergeAliases(KeyNamesInfo *into, KeyNamesInfo *from, enum merge_mode merge)
386 {
387     AliasInfo *alias;
388     KeyAliasDef def;
389
390     if (darray_empty(from->aliases))
391         return true;
392
393     if (darray_empty(into->aliases)) {
394         into->aliases = from->aliases;
395         darray_init(from->aliases);
396         return true;
397     }
398
399     memset(&def, 0, sizeof(def));
400
401     darray_foreach(alias, from->aliases) {
402         def.merge = (merge == MERGE_DEFAULT) ? alias->merge : merge;
403         LongToKeyName(alias->alias, def.alias);
404         LongToKeyName(alias->real, def.real);
405
406         if (!HandleAliasDef(into, &def, def.merge, alias->file_id))
407             return false;
408     }
409
410     return true;
411 }
412
413 static void
414 MergeIncludedKeycodes(KeyNamesInfo *into, KeyNamesInfo *from,
415                       enum merge_mode merge)
416 {
417     xkb_keycode_t i;
418     xkb_led_index_t idx;
419
420     if (from->errorCount > 0) {
421         into->errorCount += from->errorCount;
422         return;
423     }
424
425     if (into->name == NULL) {
426         into->name = from->name;
427         from->name = NULL;
428     }
429
430     ResizeKeyNameArrays(into, from->computedMax);
431
432     for (i = from->computedMin; i <= from->computedMax; i++) {
433         unsigned long name = darray_item(from->names, i);
434         if (name == 0)
435             continue;
436
437         if (!AddKeyName(into, i, name, merge, from->file_id, false))
438             into->errorCount++;
439     }
440
441     for (idx = 0; idx < XkbNumIndicators; idx++) {
442         IndicatorNameInfo *led = &from->indicator_names[idx];
443         if (led->name == XKB_ATOM_NONE)
444             continue;
445
446         led->merge = (merge == MERGE_DEFAULT ? led->merge : merge);
447         if (!AddIndicatorName(into, led->merge, led, idx))
448             into->errorCount++;
449     }
450
451     if (!MergeAliases(into, from, merge))
452         into->errorCount++;
453
454     if (from->explicitMin != 0)
455         if (into->explicitMin == 0 || into->explicitMin > from->explicitMin)
456             into->explicitMin = from->explicitMin;
457
458     if (from->explicitMax > 0)
459         if (into->explicitMax == 0 || into->explicitMax < from->explicitMax)
460             into->explicitMax = from->explicitMax;
461 }
462
463 static void
464 HandleKeycodesFile(KeyNamesInfo *info, XkbFile *file, enum merge_mode merge);
465
466 static bool
467 HandleIncludeKeycodes(KeyNamesInfo *info, IncludeStmt *stmt)
468 {
469     enum merge_mode merge = MERGE_DEFAULT;
470     XkbFile *rtrn;
471     KeyNamesInfo included, next_incl;
472
473     InitKeyNamesInfo(&included, info->ctx, info->file_id);
474     if (stmt->stmt) {
475         free(included.name);
476         included.name = stmt->stmt;
477         stmt->stmt = NULL;
478     }
479
480     for (; stmt; stmt = stmt->next_incl) {
481         if (!ProcessIncludeFile(info->ctx, stmt, FILE_TYPE_KEYCODES,
482                                 &rtrn, &merge)) {
483             info->errorCount += 10;
484             ClearKeyNamesInfo(&included);
485             return false;
486         }
487
488         InitKeyNamesInfo(&next_incl, info->ctx, rtrn->id);
489
490         HandleKeycodesFile(&next_incl, rtrn, MERGE_OVERRIDE);
491
492         MergeIncludedKeycodes(&included, &next_incl, merge);
493
494         ClearKeyNamesInfo(&next_incl);
495         FreeXkbFile(rtrn);
496     }
497
498     MergeIncludedKeycodes(info, &included, merge);
499     ClearKeyNamesInfo(&included);
500
501     return (info->errorCount == 0);
502 }
503
504 static int
505 HandleKeycodeDef(KeyNamesInfo *info, KeycodeDef *stmt, enum merge_mode merge)
506 {
507     if ((info->explicitMin != 0 && stmt->value < info->explicitMin) ||
508         (info->explicitMax != 0 && stmt->value > info->explicitMax)) {
509         log_err(info->ctx, "Illegal keycode %lu for name %s; "
510                 "Must be in the range %d-%d inclusive\n",
511                 stmt->value, KeyNameText(stmt->name), info->explicitMin,
512                 info->explicitMax ? info->explicitMax : XKB_KEYCODE_MAX);
513         return 0;
514     }
515
516     if (stmt->merge != MERGE_DEFAULT) {
517         if (stmt->merge == MERGE_REPLACE)
518             merge = MERGE_OVERRIDE;
519         else
520             merge = stmt->merge;
521     }
522
523     return AddKeyName(info, stmt->value, KeyNameToLong(stmt->name), merge,
524                       info->file_id, true);
525 }
526
527 static void
528 HandleAliasCollision(KeyNamesInfo *info, AliasInfo *old, AliasInfo *new)
529 {
530     int verbosity = xkb_get_log_verbosity(info->ctx);
531     bool report = ((new->file_id == old->file_id && verbosity > 0) ||
532                    verbosity > 9);
533
534     if (new->real == old->real) {
535         if (report)
536             log_warn(info->ctx, "Alias of %s for %s declared more than once; "
537                      "First definition ignored\n",
538                      LongKeyNameText(new->alias), LongKeyNameText(new->real));
539     }
540     else {
541         unsigned long use, ignore;
542
543         use = (new->merge == MERGE_AUGMENT ? old->real : new->real);
544         ignore = (new->merge == MERGE_AUGMENT ? new->real : old->real);
545
546         if (report)
547             log_warn(info->ctx, "Multiple definitions for alias %s; "
548                      "Using %s, ignoring %s\n",
549                      LongKeyNameText(old->alias), LongKeyNameText(use),
550                      LongKeyNameText(ignore));
551
552         old->real = use;
553     }
554
555     old->file_id = new->file_id;
556     old->merge = new->merge;
557 }
558
559 static int
560 HandleAliasDef(KeyNamesInfo *info, KeyAliasDef *def, enum merge_mode merge,
561                unsigned file_id)
562 {
563     AliasInfo *alias, new;
564
565     darray_foreach(alias, info->aliases) {
566         if (alias->alias == KeyNameToLong(def->alias)) {
567             InitAliasInfo(&new, merge, file_id, def->alias, def->real);
568             HandleAliasCollision(info, alias, &new);
569             return true;
570         }
571     }
572
573     InitAliasInfo(&new, merge, file_id, def->alias, def->real);
574     darray_append(info->aliases, new);
575     return true;
576 }
577
578 #define MIN_KEYCODE_DEF 0
579 #define MAX_KEYCODE_DEF 1
580
581 static int
582 HandleKeyNameVar(KeyNamesInfo *info, VarDef *stmt)
583 {
584     const char *elem, *field;
585     xkb_keycode_t kc;
586     ExprDef *arrayNdx;
587     int which;
588
589     if (!ExprResolveLhs(info->ctx, stmt->name, &elem, &field, &arrayNdx))
590         return false;
591
592     if (elem) {
593         log_err(info->ctx, "Unknown element %s encountered; "
594                 "Default for field %s ignored\n", elem, field);
595         return false;
596     }
597
598     if (istreq(field, "minimum")) {
599         which = MIN_KEYCODE_DEF;
600     }
601     else if (istreq(field, "maximum")) {
602         which = MAX_KEYCODE_DEF;
603     }
604     else {
605         log_err(info->ctx, "Unknown field encountered; "
606                 "Assigment to field %s ignored\n", field);
607         return false;
608     }
609
610     if (arrayNdx != NULL) {
611         log_err(info->ctx, "The %s setting is not an array; "
612                 "Illegal array reference ignored\n", field);
613         return false;
614     }
615
616     if (!ExprResolveKeyCode(info->ctx, stmt->value, &kc)) {
617         log_err(info->ctx, "Illegal keycode encountered; "
618                 "Assignment to field %s ignored\n", field);
619         return false;
620     }
621
622     if (kc > XKB_KEYCODE_MAX) {
623         log_err(info->ctx,
624                 "Illegal keycode %d (must be in the range %d-%d inclusive); "
625                 "Value of \"%s\" not changed\n",
626                 kc, 0, XKB_KEYCODE_MAX, field);
627         return false;
628     }
629
630     if (which == MIN_KEYCODE_DEF) {
631         if (info->explicitMax > 0 && info->explicitMax < kc) {
632             log_err(info->ctx,
633                     "Minimum key code (%d) must be <= maximum key code (%d); "
634                     "Minimum key code value not changed\n",
635                     kc, info->explicitMax);
636             return false;
637         }
638
639         if (info->computedMax > 0 && info->computedMin < kc) {
640             log_err(info->ctx,
641                     "Minimum key code (%d) must be <= lowest defined key (%d); "
642                     "Minimum key code value not changed\n",
643                     kc, info->computedMin);
644             return false;
645         }
646
647         info->explicitMin = kc;
648     }
649     else if (which == MAX_KEYCODE_DEF) {
650         if (info->explicitMin > 0 && info->explicitMin > kc) {
651             log_err(info->ctx,
652                     "Maximum code (%d) must be >= minimum key code (%d); "
653                     "Maximum code value not changed\n",
654                     kc, info->explicitMin);
655             return false;
656         }
657
658         if (info->computedMax > 0 && info->computedMax > kc) {
659             log_err(info->ctx,
660                     "Maximum code (%d) must be >= highest defined key (%d); "
661                     "Maximum code value not changed\n",
662                     kc, info->computedMax);
663             return false;
664         }
665
666         info->explicitMax = kc;
667     }
668
669     return true;
670 }
671
672 static int
673 HandleIndicatorNameDef(KeyNamesInfo *info, IndicatorNameDef *def,
674                        enum merge_mode merge)
675 {
676     IndicatorNameInfo ii;
677     xkb_atom_t name;
678
679     if (def->ndx < 1 || def->ndx > XkbNumIndicators) {
680         info->errorCount++;
681         log_err(info->ctx,
682                 "Name specified for illegal indicator index %d\n; Ignored\n",
683                 def->ndx);
684         return false;
685     }
686
687     if (!ExprResolveString(info->ctx, def->name, &name)) {
688         char buf[20];
689         snprintf(buf, sizeof(buf), "%d", def->ndx);
690         info->errorCount++;
691         return ReportBadType(info->ctx, "indicator", "name", buf,
692                              "string");
693     }
694
695     ii.merge = info->merge;
696     ii.file_id = info->file_id;
697     ii.name = name;
698     return AddIndicatorName(info, merge, &ii, def->ndx - 1);
699 }
700
701 static void
702 HandleKeycodesFile(KeyNamesInfo *info, XkbFile *file, enum merge_mode merge)
703 {
704     ParseCommon *stmt;
705     bool ok;
706
707     free(info->name);
708     info->name = strdup_safe(file->name);
709
710     for (stmt = file->defs; stmt; stmt = stmt->next) {
711         switch (stmt->type) {
712         case STMT_INCLUDE:
713             ok = HandleIncludeKeycodes(info, (IncludeStmt *) stmt);
714             break;
715         case STMT_KEYCODE:
716             ok = HandleKeycodeDef(info, (KeycodeDef *) stmt, merge);
717             break;
718         case STMT_ALIAS:
719             ok = HandleAliasDef(info, (KeyAliasDef *) stmt, merge,
720                                 info->file_id);
721             break;
722         case STMT_VAR:
723             ok = HandleKeyNameVar(info, (VarDef *) stmt);
724             break;
725         case STMT_INDICATOR_NAME:
726             ok = HandleIndicatorNameDef(info, (IndicatorNameDef *) stmt,
727                                         merge);
728             break;
729         default:
730             log_err(info->ctx,
731                     "Keycode files may define key and indicator names only; "
732                     "Ignoring %s\n", stmt_type_to_string(stmt->type));
733             ok = false;
734             break;
735         }
736
737         if (!ok)
738             info->errorCount++;
739
740         if (info->errorCount > 10) {
741             log_err(info->ctx, "Abandoning keycodes file \"%s\"\n",
742                     file->topName);
743             break;
744         }
745     }
746 }
747
748 static void
749 ApplyAliases(KeyNamesInfo *info, struct xkb_keymap *keymap)
750 {
751     struct xkb_key *key;
752     struct xkb_key_alias *a, new;
753     AliasInfo *alias;
754
755     darray_foreach(alias, info->aliases) {
756         /* Check that ->real is a key. */
757         key = FindNamedKey(keymap, alias->real, false, 0);
758         if (!key) {
759             log_vrb(info->ctx, 5,
760                     "Attempt to alias %s to non-existent key %s; Ignored\n",
761                     LongKeyNameText(alias->alias),
762                     LongKeyNameText(alias->real));
763             continue;
764         }
765
766         /* Check that ->alias is not a key. */
767         key = FindNamedKey(keymap, alias->alias, false, 0);
768         if (key) {
769             log_vrb(info->ctx, 5,
770                     "Attempt to create alias with the name of a real key; "
771                     "Alias \"%s = %s\" ignored\n",
772                     LongKeyNameText(alias->alias),
773                     LongKeyNameText(alias->real));
774             continue;
775         }
776
777         /* Check that ->alias in not already an alias, and if so handle it. */
778         darray_foreach(a, keymap->key_aliases) {
779             AliasInfo old_alias;
780
781             if (KeyNameToLong(a->alias) != alias->alias)
782                 continue;
783
784             InitAliasInfo(&old_alias, MERGE_AUGMENT, 0, a->alias, a->real);
785             HandleAliasCollision(info, &old_alias, alias);
786             LongToKeyName(old_alias.alias, a->alias);
787             LongToKeyName(old_alias.real, a->real);
788             alias->alias = 0;
789         }
790         if (alias->alias == 0)
791             continue;
792
793         /* Add the alias. */
794         LongToKeyName(alias->alias, new.alias);
795         LongToKeyName(alias->real, new.real);
796         darray_append(keymap->key_aliases, new);
797     }
798
799     darray_free(info->aliases);
800 }
801
802 static bool
803 CopyKeyNamesToKeymap(struct xkb_keymap *keymap, KeyNamesInfo *info)
804 {
805     xkb_keycode_t kc;
806     xkb_led_index_t idx;
807
808     if (info->explicitMin > 0)
809         keymap->min_key_code = info->explicitMin;
810     else
811         keymap->min_key_code = info->computedMin;
812
813     if (info->explicitMax > 0)
814         keymap->max_key_code = info->explicitMax;
815     else
816         keymap->max_key_code = info->computedMax;
817
818     darray_resize0(keymap->keys, keymap->max_key_code + 1);
819     for (kc = info->computedMin; kc <= info->computedMax; kc++)
820         LongToKeyName(darray_item(info->names, kc),
821                       XkbKey(keymap, kc)->name);
822
823     keymap->keycodes_section_name = strdup_safe(info->name);
824
825     for (idx = 0; idx < XkbNumIndicators; idx++) {
826         IndicatorNameInfo *led = &info->indicator_names[idx];
827         if (led->name == XKB_ATOM_NONE)
828             continue;
829
830         keymap->indicators[idx].name = led->name;
831     }
832
833     ApplyAliases(info, keymap);
834
835     return true;
836 }
837
838 bool
839 CompileKeycodes(XkbFile *file, struct xkb_keymap *keymap,
840                 enum merge_mode merge)
841 {
842     KeyNamesInfo info;
843
844     InitKeyNamesInfo(&info, keymap->ctx, file->id);
845
846     HandleKeycodesFile(&info, file, merge);
847     if (info.errorCount != 0)
848         goto err_info;
849
850     if (!CopyKeyNamesToKeymap(keymap, &info))
851         goto err_info;
852
853     ClearKeyNamesInfo(&info);
854     return true;
855
856 err_info:
857     ClearKeyNamesInfo(&info);
858     return false;
859 }
860
861 struct xkb_key *
862 FindNamedKey(struct xkb_keymap *keymap, unsigned long name,
863              bool use_aliases, xkb_keycode_t start_from)
864 {
865     struct xkb_key *key;
866
867     if (start_from < keymap->min_key_code)
868         start_from = keymap->min_key_code;
869     else if (start_from > keymap->max_key_code)
870         return NULL;
871
872     xkb_foreach_key_from(key, keymap, start_from)
873         if (KeyNameToLong(key->name) == name)
874             return key;
875
876     if (use_aliases) {
877         unsigned long new_name;
878         if (FindKeyNameForAlias(keymap, name, &new_name))
879             return FindNamedKey(keymap, new_name, false, 0);
880     }
881
882     return NULL;
883 }
884
885 bool
886 FindKeyNameForAlias(struct xkb_keymap *keymap, unsigned long lname,
887                     unsigned long *real_name)
888 {
889     char name[XKB_KEY_NAME_LENGTH];
890     struct xkb_key_alias *a;
891
892     LongToKeyName(lname, name);
893     darray_foreach(a, keymap->key_aliases) {
894         if (strncmp(name, a->alias, XKB_KEY_NAME_LENGTH) == 0) {
895             *real_name = KeyNameToLong(a->real);
896             return true;
897         }
898     }
899
900     return false;
901 }