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