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