Move a couple of general keymap functions from keycodes.c
[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 "include.h"
31
32 /*
33  * The xkb_keycodes section
34  * ========================
35  *
36  * This is the simplest section type, and is the first one to be
37  * compiled. The purpose of this is mostly to map between the
38  * hardware/evdev scancodes and xkb keycodes. Each key is given a name
39  * by which it can be referred to later, e.g. in the symbols section.
40  *
41  * Keycode statements
42  * ------------------
43  * Statements of the form:
44  *      <TLDE> = 49;
45  *      <AE01> = 10;
46  *
47  * The above would let 49 and 10 be valid keycodes in the keymap, and
48  * assign them the names TLDE and AE01 respectively. The format <WXYZ> is
49  * always used to refer to a key by name.
50  *
51  * [ The naming convention <AE01> just denoted the position of the key
52  * in the main alphanumric section of the keyboard, with the two letters
53  * specifying the row and the two digits specifying the column, from
54  * the bottom left.]
55  *
56  * In the common case this just maps to the evdev scancodes from
57  * /usr/include/linux/input.h, e.g. the following definitions:
58  *      #define KEY_GRAVE            41
59  *      #define KEY_1                2
60  * Similar definitions appear in the xf86-input-keyboard driver. Note
61  * that in all current keymaps there's a constant offset of 8 (for
62  * historical reasons).
63  *
64  * If there's a conflict, like the same name given to different keycodes,
65  * or same keycode given different names, it is resolved according to the
66  * merge mode which applies to the definitions.
67  *
68  * Alias statements
69  * ----------------
70  * Statements of the form:
71  *      alias <MENU> = <COMP>;
72  *
73  * Allows to refer to a previously defined key (here <COMP>) by another
74  * name (here <MENU>). Conflicts are handled similarly.
75  *
76  * LED name statements
77  * -------------------------
78  * Statements of the form:
79  *      indicator 1 = "Caps Lock";
80  *      indicator 2 = "Num Lock";
81  *      indicator 3 = "Scroll Lock";
82  *
83  * Assigns a name to the keyboard LED (a.k.a indicator) with the given index.
84  * The led may be referred by this name later in the compat section
85  * and by the user.
86  *
87  * Effect on the keymap
88  * --------------------
89  * After all of the xkb_keycodes sections have been compiled, the
90  * following members of struct xkb_keymap are finalized:
91  *      xkb_keycode_t min_key_code;
92  *      xkb_keycode_t max_key_code;
93  *      darray(struct xkb_key_alias) key_aliases;
94  *      char *keycodes_section_name;
95  * The 'name' field of leds declared in xkb_keycodes:
96  *      darray(struct xkb_led) leds;
97  * Further, the array of keys:
98  *      struct xkb_key *keys;
99  * had been resized to its final size (i.e. all of the xkb_key objects are
100  * referable by their keycode). However the objects themselves do not
101  * contain any useful information besides the key name at this point.
102  */
103
104 typedef struct {
105     enum merge_mode merge;
106
107     xkb_atom_t alias;
108     xkb_atom_t real;
109 } AliasInfo;
110
111 typedef struct {
112     unsigned file_id;
113
114     xkb_atom_t name;
115 } KeyNameInfo;
116
117 typedef struct {
118     enum merge_mode merge;
119     unsigned file_id;
120
121     xkb_atom_t name;
122 } LedNameInfo;
123
124 typedef struct {
125     char *name;
126     int errorCount;
127     enum merge_mode merge;
128     unsigned file_id;
129
130     xkb_keycode_t min_key_code;
131     xkb_keycode_t max_key_code;
132     darray(KeyNameInfo) key_names;
133     darray(LedNameInfo) led_names;
134     darray(AliasInfo) aliases;
135
136     struct xkb_context *ctx;
137 } KeyNamesInfo;
138
139 /***====================================================================***/
140
141 static void
142 InitAliasInfo(AliasInfo *info, enum merge_mode merge,
143               xkb_atom_t alias, xkb_atom_t real)
144 {
145     memset(info, 0, sizeof(*info));
146     info->merge = merge;
147     info->alias = alias;
148     info->real = real;
149 }
150
151 static LedNameInfo *
152 FindLedByName(KeyNamesInfo *info, xkb_atom_t name,
153               xkb_led_index_t *idx_out)
154 {
155     LedNameInfo *ledi;
156     xkb_led_index_t idx;
157
158     darray_enumerate(idx, ledi, info->led_names) {
159         if (ledi->name == name) {
160             *idx_out = idx;
161             return ledi;
162         }
163     }
164
165     return NULL;
166 }
167
168 static bool
169 AddLedName(KeyNamesInfo *info, enum merge_mode merge,
170            LedNameInfo *new, xkb_led_index_t new_idx)
171 {
172     xkb_led_index_t old_idx;
173     LedNameInfo *old;
174     const int verbosity = xkb_context_get_log_verbosity(info->ctx);
175     const bool replace = (merge == MERGE_REPLACE || merge == MERGE_OVERRIDE);
176
177     /* Inidicator with the same name already exists. */
178     old = FindLedByName(info, new->name, &old_idx);
179     if (old) {
180         const bool report = ((old->file_id == new->file_id && verbosity > 0) ||
181                              verbosity > 9);
182
183         if (old_idx == new_idx) {
184             log_warn(info->ctx,
185                      "Multiple indicators named \"%s\"; "
186                      "Identical definitions ignored\n",
187                      xkb_atom_text(info->ctx, new->name));
188             return true;
189         }
190
191         if (report) {
192             xkb_led_index_t use = (replace ? new_idx + 1 : old_idx + 1);
193             xkb_led_index_t ignore = (replace ? old_idx + 1 : new_idx + 1);
194             log_warn(info->ctx,
195                      "Multiple indicators named %s; Using %d, ignoring %d\n",
196                      xkb_atom_text(info->ctx, new->name), use, ignore);
197         }
198
199         if (replace)
200             *old = *new;
201
202         return true;
203     }
204
205     if (new_idx >= darray_size(info->led_names))
206         darray_resize0(info->led_names, new_idx + 1);
207
208     /* Inidicator with the same index already exists. */
209     old = &darray_item(info->led_names, new_idx);
210     if (old->name != XKB_ATOM_NONE) {
211         const bool report = ((old->file_id == new->file_id && verbosity > 0) ||
212                              verbosity > 9);
213
214         /* Same name case already handled above. */
215
216         if (report) {
217             const xkb_atom_t use = (replace ? new->name : old->name);
218             const xkb_atom_t ignore = (replace ? old->name : new->name);
219             log_warn(info->ctx, "Multiple names for indicator %d; "
220                      "Using %s, ignoring %s\n", new_idx + 1,
221                      xkb_atom_text(info->ctx, use),
222                      xkb_atom_text(info->ctx, ignore));
223         }
224
225         if (replace)
226             *old = *new;
227
228         return true;
229     }
230
231     darray_item(info->led_names, new_idx) = *new;
232     return true;
233 }
234
235 static void
236 ClearKeyNamesInfo(KeyNamesInfo *info)
237 {
238     free(info->name);
239     darray_free(info->key_names);
240     darray_free(info->aliases);
241     darray_free(info->led_names);
242 }
243
244 static void
245 InitKeyNamesInfo(KeyNamesInfo *info, struct xkb_context *ctx,
246                  unsigned file_id)
247 {
248     memset(info, 0, sizeof(*info));
249     info->ctx = ctx;
250     info->merge = MERGE_DEFAULT;
251     info->file_id = file_id;
252     info->min_key_code = XKB_KEYCODE_MAX;
253 }
254
255 static xkb_keycode_t
256 FindKeyByName(KeyNamesInfo * info, xkb_atom_t name)
257 {
258     xkb_keycode_t i;
259
260     for (i = info->min_key_code; i <= info->max_key_code; i++)
261         if (darray_item(info->key_names, i).name == name)
262             return i;
263
264     return XKB_KEYCODE_INVALID;
265 }
266
267 static bool
268 AddKeyName(KeyNamesInfo *info, xkb_keycode_t kc, xkb_atom_t name,
269            enum merge_mode merge, unsigned file_id, bool report)
270 {
271     KeyNameInfo *namei;
272     xkb_keycode_t old;
273     const int verbosity = xkb_context_get_log_verbosity(info->ctx);
274
275     if (kc >= darray_size(info->key_names))
276         darray_resize0(info->key_names, kc + 1);
277
278     info->min_key_code = MIN(info->min_key_code, kc);
279     info->max_key_code = MAX(info->max_key_code, kc);
280
281     namei = &darray_item(info->key_names, kc);
282
283     report = report && ((verbosity > 0 && file_id == namei->file_id) ||
284                         verbosity > 7);
285
286     if (namei->name != 0) {
287         const char *lname = KeyNameText(info->ctx, namei->name);
288         const char *kname = KeyNameText(info->ctx, name);
289
290         if (namei->name == name) {
291             if (report)
292                 log_warn(info->ctx,
293                          "Multiple identical key name definitions; "
294                          "Later occurrences of \"%s = %d\" ignored\n",
295                          lname, kc);
296             return true;
297         }
298         else if (merge == MERGE_AUGMENT) {
299             if (report)
300                 log_warn(info->ctx,
301                          "Multiple names for keycode %d; "
302                          "Using %s, ignoring %s\n", kc, lname, kname);
303             return true;
304         }
305         else {
306             if (report)
307                 log_warn(info->ctx,
308                          "Multiple names for keycode %d; "
309                          "Using %s, ignoring %s\n", kc, kname, lname);
310             namei->name = 0;
311             namei->file_id = 0;
312         }
313     }
314
315     old = FindKeyByName(info, name);
316     if (old != XKB_KEYCODE_INVALID && old != kc) {
317         const char *kname = KeyNameText(info->ctx, name);
318
319         if (merge == MERGE_OVERRIDE) {
320             darray_item(info->key_names, old).name = 0;
321             darray_item(info->key_names, old).file_id = 0;
322             if (report)
323                 log_warn(info->ctx,
324                          "Key name %s assigned to multiple keys; "
325                          "Using %d, ignoring %d\n", kname, kc, old);
326         }
327         else {
328             if (report)
329                 log_vrb(info->ctx, 3,
330                         "Key name %s assigned to multiple keys; "
331                         "Using %d, ignoring %d\n", kname, old, kc);
332             return true;
333         }
334     }
335
336     namei->name = name;
337     namei->file_id = file_id;
338     return true;
339 }
340
341 /***====================================================================***/
342
343 static int
344 HandleAliasDef(KeyNamesInfo *info, KeyAliasDef *def, enum merge_mode merge);
345
346 static bool
347 MergeAliases(KeyNamesInfo *into, KeyNamesInfo *from, enum merge_mode merge)
348 {
349     AliasInfo *alias;
350     KeyAliasDef def;
351
352     if (darray_empty(from->aliases))
353         return true;
354
355     if (darray_empty(into->aliases)) {
356         into->aliases = from->aliases;
357         darray_init(from->aliases);
358         return true;
359     }
360
361     memset(&def, 0, sizeof(def));
362
363     darray_foreach(alias, from->aliases) {
364         def.merge = (merge == MERGE_DEFAULT) ? alias->merge : merge;
365         def.alias = alias->alias;
366         def.real = alias->real;
367
368         if (!HandleAliasDef(into, &def, def.merge))
369             return false;
370     }
371
372     return true;
373 }
374
375 static void
376 MergeIncludedKeycodes(KeyNamesInfo *into, KeyNamesInfo *from,
377                       enum merge_mode merge)
378 {
379     xkb_keycode_t i;
380     xkb_led_index_t idx;
381     LedNameInfo *ledi;
382
383     if (from->errorCount > 0) {
384         into->errorCount += from->errorCount;
385         return;
386     }
387
388     if (into->name == NULL) {
389         into->name = from->name;
390         from->name = NULL;
391     }
392
393     if (darray_size(into->key_names) < darray_size(from->key_names))
394         darray_resize0(into->key_names, darray_size(from->key_names));
395
396     for (i = from->min_key_code; i <= from->max_key_code; i++) {
397         xkb_atom_t name = darray_item(from->key_names, i).name;
398         if (name == XKB_ATOM_NONE)
399             continue;
400
401         if (!AddKeyName(into, i, name, merge, from->file_id, false))
402             into->errorCount++;
403     }
404
405     darray_enumerate(idx, ledi, from->led_names) {
406         if (ledi->name == XKB_ATOM_NONE)
407             continue;
408
409         ledi->merge = (merge == MERGE_DEFAULT ? ledi->merge : merge);
410         if (!AddLedName(into, ledi->merge, ledi, idx))
411             into->errorCount++;
412     }
413
414     if (!MergeAliases(into, from, merge))
415         into->errorCount++;
416 }
417
418 static void
419 HandleKeycodesFile(KeyNamesInfo *info, XkbFile *file, enum merge_mode merge);
420
421 static bool
422 HandleIncludeKeycodes(KeyNamesInfo *info, IncludeStmt *include)
423 {
424     KeyNamesInfo included;
425
426     InitKeyNamesInfo(&included, info->ctx, info->file_id);
427     included.name = include->stmt;
428     include->stmt = NULL;
429
430     for (IncludeStmt *stmt = include; stmt; stmt = stmt->next_incl) {
431         KeyNamesInfo next_incl;
432         XkbFile *file;
433
434         file = ProcessIncludeFile(info->ctx, stmt, FILE_TYPE_KEYCODES);
435         if (!file) {
436             info->errorCount += 10;
437             ClearKeyNamesInfo(&included);
438             return false;
439         }
440
441         InitKeyNamesInfo(&next_incl, info->ctx, file->id);
442
443         HandleKeycodesFile(&next_incl, file, MERGE_OVERRIDE);
444
445         MergeIncludedKeycodes(&included, &next_incl, stmt->merge);
446
447         ClearKeyNamesInfo(&next_incl);
448         FreeXkbFile(file);
449     }
450
451     MergeIncludedKeycodes(info, &included, include->merge);
452     ClearKeyNamesInfo(&included);
453
454     return (info->errorCount == 0);
455 }
456
457 static bool
458 HandleKeycodeDef(KeyNamesInfo *info, KeycodeDef *stmt, enum merge_mode merge)
459 {
460     if (stmt->merge != MERGE_DEFAULT) {
461         if (stmt->merge == MERGE_REPLACE)
462             merge = MERGE_OVERRIDE;
463         else
464             merge = stmt->merge;
465     }
466
467     if (stmt->value < 0 || stmt->value > XKB_KEYCODE_MAX) {
468         log_err(info->ctx,
469                 "Illegal keycode %lld: must be between 0..%u; "
470                 "Key ignored\n", (long long) stmt->value, XKB_KEYCODE_MAX);
471         return false;
472     }
473
474     return AddKeyName(info, stmt->value, stmt->name, merge,
475                       info->file_id, true);
476 }
477
478 static int
479 HandleAliasDef(KeyNamesInfo *info, KeyAliasDef *def, enum merge_mode merge)
480 {
481     AliasInfo *old, new;
482
483     darray_foreach(old, info->aliases) {
484         if (old->alias == def->alias) {
485             if (def->real == old->real) {
486                 log_vrb(info->ctx, 1,
487                         "Alias of %s for %s declared more than once; "
488                         "First definition ignored\n",
489                         KeyNameText(info->ctx, def->alias),
490                         KeyNameText(info->ctx, def->real));
491             }
492             else {
493                 xkb_atom_t use, ignore;
494
495                 use = (merge == MERGE_AUGMENT ? old->real : def->real);
496                 ignore = (merge == MERGE_AUGMENT ? def->real : old->real);
497
498                 log_warn(info->ctx,
499                          "Multiple definitions for alias %s; "
500                          "Using %s, ignoring %s\n",
501                          KeyNameText(info->ctx, old->alias),
502                          KeyNameText(info->ctx, use),
503                          KeyNameText(info->ctx, ignore));
504
505                 old->real = use;
506             }
507
508             old->merge = merge;
509             return true;
510         }
511     }
512
513     InitAliasInfo(&new, merge, def->alias, def->real);
514     darray_append(info->aliases, new);
515     return true;
516 }
517
518 static int
519 HandleKeyNameVar(KeyNamesInfo *info, VarDef *stmt)
520 {
521     const char *elem, *field;
522     ExprDef *arrayNdx;
523
524     if (!ExprResolveLhs(info->ctx, stmt->name, &elem, &field, &arrayNdx))
525         return false;
526
527     if (elem) {
528         log_err(info->ctx, "Unknown element %s encountered; "
529                 "Default for field %s ignored\n", elem, field);
530         return false;
531     }
532
533     if (!istreq(field, "minimum") && !istreq(field, "maximum")) {
534         log_err(info->ctx, "Unknown field encountered; "
535                 "Assignment to field %s ignored\n", field);
536         return false;
537     }
538
539     /* We ignore explicit min/max statements, we always use computed. */
540     return true;
541 }
542
543 static int
544 HandleLedNameDef(KeyNamesInfo *info, LedNameDef *def,
545                  enum merge_mode merge)
546 {
547     LedNameInfo ledi;
548     xkb_atom_t name;
549
550     if (def->ndx < 1 || def->ndx > XKB_MAX_LEDS) {
551         info->errorCount++;
552         log_err(info->ctx,
553                 "Illegal indicator index (%d) specified; must be between 1 .. %d; "
554                 "Ignored\n", def->ndx, XKB_MAX_LEDS);
555         return false;
556     }
557
558     if (!ExprResolveString(info->ctx, def->name, &name)) {
559         char buf[20];
560         snprintf(buf, sizeof(buf), "%d", def->ndx);
561         info->errorCount++;
562         return ReportBadType(info->ctx, "indicator", "name", buf, "string");
563     }
564
565     ledi.merge = info->merge;
566     ledi.file_id = info->file_id;
567     ledi.name = name;
568     return AddLedName(info, merge, &ledi, def->ndx - 1);
569 }
570
571 static void
572 HandleKeycodesFile(KeyNamesInfo *info, XkbFile *file, enum merge_mode merge)
573 {
574     bool ok;
575
576     free(info->name);
577     info->name = strdup_safe(file->name);
578
579     for (ParseCommon *stmt = file->defs; stmt; stmt = stmt->next) {
580         switch (stmt->type) {
581         case STMT_INCLUDE:
582             ok = HandleIncludeKeycodes(info, (IncludeStmt *) stmt);
583             break;
584         case STMT_KEYCODE:
585             ok = HandleKeycodeDef(info, (KeycodeDef *) stmt, merge);
586             break;
587         case STMT_ALIAS:
588             ok = HandleAliasDef(info, (KeyAliasDef *) stmt, merge);
589             break;
590         case STMT_VAR:
591             ok = HandleKeyNameVar(info, (VarDef *) stmt);
592             break;
593         case STMT_LED_NAME:
594             ok = HandleLedNameDef(info, (LedNameDef *) stmt, merge);
595             break;
596         default:
597             log_err(info->ctx,
598                     "Keycode files may define key and indicator names only; "
599                     "Ignoring %s\n", stmt_type_to_string(stmt->type));
600             ok = false;
601             break;
602         }
603
604         if (!ok)
605             info->errorCount++;
606
607         if (info->errorCount > 10) {
608             log_err(info->ctx, "Abandoning keycodes file \"%s\"\n",
609                     file->topName);
610             break;
611         }
612     }
613 }
614
615 /***====================================================================***/
616
617 static void
618 CopyAliasesToKeymap(KeyNamesInfo *info, struct xkb_keymap *keymap)
619 {
620     AliasInfo *alias;
621
622     darray_foreach(alias, info->aliases) {
623         struct xkb_key *key;
624         struct xkb_key_alias new;
625
626         /* Check that ->real is a key. */
627         key = XkbKeyByName(keymap, alias->real, false);
628         if (!key) {
629             log_vrb(info->ctx, 5,
630                     "Attempt to alias %s to non-existent key %s; Ignored\n",
631                     KeyNameText(info->ctx, alias->alias),
632                     KeyNameText(info->ctx, alias->real));
633             continue;
634         }
635
636         /* Check that ->alias is not a key. */
637         key = XkbKeyByName(keymap, alias->alias, false);
638         if (key) {
639             log_vrb(info->ctx, 5,
640                     "Attempt to create alias with the name of a real key; "
641                     "Alias \"%s = %s\" ignored\n",
642                     KeyNameText(info->ctx, alias->alias),
643                     KeyNameText(info->ctx, alias->real));
644             continue;
645         }
646
647         /* Add the alias. */
648         new.alias = alias->alias;
649         new.real = alias->real;
650         darray_append(keymap->key_aliases, new);
651     }
652
653     darray_free(info->aliases);
654 }
655
656 static bool
657 CopyKeyNamesToKeymap(struct xkb_keymap *keymap, KeyNamesInfo *info)
658 {
659     xkb_keycode_t kc;
660     xkb_led_index_t idx;
661     LedNameInfo *ledi;
662
663     keymap->keys = calloc(info->max_key_code + 1, sizeof(*keymap->keys));
664     if (!keymap->keys)
665         return false;
666
667     keymap->min_key_code = info->min_key_code;
668     keymap->max_key_code = info->max_key_code;
669
670     for (kc = info->min_key_code; kc <= info->max_key_code; kc++) {
671         keymap->keys[kc].keycode = kc;
672         keymap->keys[kc].name = darray_item(info->key_names, kc).name;
673     }
674
675     keymap->keycodes_section_name = strdup_safe(info->name);
676
677     darray_resize0(keymap->leds, darray_size(info->led_names));
678     darray_enumerate(idx, ledi, info->led_names) {
679         if (ledi->name == XKB_ATOM_NONE)
680             continue;
681
682         darray_item(keymap->leds, idx).name = ledi->name;
683     }
684
685     CopyAliasesToKeymap(info, keymap);
686
687     return true;
688 }
689
690 /***====================================================================***/
691
692 bool
693 CompileKeycodes(XkbFile *file, struct xkb_keymap *keymap,
694                 enum merge_mode merge)
695 {
696     KeyNamesInfo info;
697
698     InitKeyNamesInfo(&info, keymap->ctx, file->id);
699
700     HandleKeycodesFile(&info, file, merge);
701     if (info.errorCount != 0)
702         goto err_info;
703
704     if (!CopyKeyNamesToKeymap(keymap, &info))
705         goto err_info;
706
707     ClearKeyNamesInfo(&info);
708     return true;
709
710 err_info:
711     ClearKeyNamesInfo(&info);
712     return false;
713 }