keycodes: don't do unnecessary copies while merging
[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 void
347 MergeIncludedKeycodes(KeyNamesInfo *into, KeyNamesInfo *from,
348                       enum merge_mode merge)
349 {
350     if (from->errorCount > 0) {
351         into->errorCount += from->errorCount;
352         return;
353     }
354
355     if (into->name == NULL) {
356         into->name = from->name;
357         from->name = NULL;
358     }
359
360     /* Merge key names. */
361     if (darray_empty(into->key_names)) {
362         into->key_names = from->key_names;
363         darray_init(from->key_names);
364         into->min_key_code = from->min_key_code;
365         into->max_key_code = from->max_key_code;
366     }
367     else {
368         if (darray_size(into->key_names) < darray_size(from->key_names))
369             darray_resize0(into->key_names, darray_size(from->key_names));
370
371         for (unsigned i = from->min_key_code; i <= from->max_key_code; i++) {
372             xkb_atom_t name = darray_item(from->key_names, i).name;
373             if (name == XKB_ATOM_NONE)
374                 continue;
375
376             if (!AddKeyName(into, i, name, merge, from->file_id, false))
377                 into->errorCount++;
378         }
379     }
380
381     /* Merge key aliases. */
382     if (darray_empty(into->aliases)) {
383         into->aliases = from->aliases;
384         darray_init(from->aliases);
385     }
386     else {
387         AliasInfo *alias;
388
389         darray_foreach(alias, from->aliases) {
390             KeyAliasDef def;
391
392             def.merge = (merge == MERGE_DEFAULT ? alias->merge : merge);
393             def.alias = alias->alias;
394             def.real = alias->real;
395
396             if (!HandleAliasDef(into, &def, def.merge))
397                 into->errorCount++;
398         }
399     }
400
401     /* Merge LED names. */
402     if (darray_empty(into->led_names)) {
403         into->led_names = from->led_names;
404         darray_init(from->led_names);
405     }
406     else {
407         xkb_led_index_t idx;
408         LedNameInfo *ledi;
409
410         darray_enumerate(idx, ledi, from->led_names) {
411             if (ledi->name == XKB_ATOM_NONE)
412                 continue;
413
414             ledi->merge = (merge == MERGE_DEFAULT ? ledi->merge : merge);
415             if (!AddLedName(into, ledi->merge, ledi, idx))
416                 into->errorCount++;
417         }
418     }
419 }
420
421 static void
422 HandleKeycodesFile(KeyNamesInfo *info, XkbFile *file, enum merge_mode merge);
423
424 static bool
425 HandleIncludeKeycodes(KeyNamesInfo *info, IncludeStmt *include)
426 {
427     KeyNamesInfo included;
428
429     InitKeyNamesInfo(&included, info->ctx, info->file_id);
430     included.name = include->stmt;
431     include->stmt = NULL;
432
433     for (IncludeStmt *stmt = include; stmt; stmt = stmt->next_incl) {
434         KeyNamesInfo next_incl;
435         XkbFile *file;
436
437         file = ProcessIncludeFile(info->ctx, stmt, FILE_TYPE_KEYCODES);
438         if (!file) {
439             info->errorCount += 10;
440             ClearKeyNamesInfo(&included);
441             return false;
442         }
443
444         InitKeyNamesInfo(&next_incl, info->ctx, file->id);
445
446         HandleKeycodesFile(&next_incl, file, MERGE_OVERRIDE);
447
448         MergeIncludedKeycodes(&included, &next_incl, stmt->merge);
449
450         ClearKeyNamesInfo(&next_incl);
451         FreeXkbFile(file);
452     }
453
454     MergeIncludedKeycodes(info, &included, include->merge);
455     ClearKeyNamesInfo(&included);
456
457     return (info->errorCount == 0);
458 }
459
460 static bool
461 HandleKeycodeDef(KeyNamesInfo *info, KeycodeDef *stmt, enum merge_mode merge)
462 {
463     if (stmt->merge != MERGE_DEFAULT) {
464         if (stmt->merge == MERGE_REPLACE)
465             merge = MERGE_OVERRIDE;
466         else
467             merge = stmt->merge;
468     }
469
470     if (stmt->value < 0 || stmt->value > XKB_KEYCODE_MAX) {
471         log_err(info->ctx,
472                 "Illegal keycode %lld: must be between 0..%u; "
473                 "Key ignored\n", (long long) stmt->value, XKB_KEYCODE_MAX);
474         return false;
475     }
476
477     return AddKeyName(info, stmt->value, stmt->name, merge,
478                       info->file_id, true);
479 }
480
481 static int
482 HandleAliasDef(KeyNamesInfo *info, KeyAliasDef *def, enum merge_mode merge)
483 {
484     AliasInfo *old, new;
485
486     darray_foreach(old, info->aliases) {
487         if (old->alias == def->alias) {
488             if (def->real == old->real) {
489                 log_vrb(info->ctx, 1,
490                         "Alias of %s for %s declared more than once; "
491                         "First definition ignored\n",
492                         KeyNameText(info->ctx, def->alias),
493                         KeyNameText(info->ctx, def->real));
494             }
495             else {
496                 xkb_atom_t use, ignore;
497
498                 use = (merge == MERGE_AUGMENT ? old->real : def->real);
499                 ignore = (merge == MERGE_AUGMENT ? def->real : old->real);
500
501                 log_warn(info->ctx,
502                          "Multiple definitions for alias %s; "
503                          "Using %s, ignoring %s\n",
504                          KeyNameText(info->ctx, old->alias),
505                          KeyNameText(info->ctx, use),
506                          KeyNameText(info->ctx, ignore));
507
508                 old->real = use;
509             }
510
511             old->merge = merge;
512             return true;
513         }
514     }
515
516     InitAliasInfo(&new, merge, def->alias, def->real);
517     darray_append(info->aliases, new);
518     return true;
519 }
520
521 static int
522 HandleKeyNameVar(KeyNamesInfo *info, VarDef *stmt)
523 {
524     const char *elem, *field;
525     ExprDef *arrayNdx;
526
527     if (!ExprResolveLhs(info->ctx, stmt->name, &elem, &field, &arrayNdx))
528         return false;
529
530     if (elem) {
531         log_err(info->ctx, "Unknown element %s encountered; "
532                 "Default for field %s ignored\n", elem, field);
533         return false;
534     }
535
536     if (!istreq(field, "minimum") && !istreq(field, "maximum")) {
537         log_err(info->ctx, "Unknown field encountered; "
538                 "Assignment to field %s ignored\n", field);
539         return false;
540     }
541
542     /* We ignore explicit min/max statements, we always use computed. */
543     return true;
544 }
545
546 static int
547 HandleLedNameDef(KeyNamesInfo *info, LedNameDef *def,
548                  enum merge_mode merge)
549 {
550     LedNameInfo ledi;
551     xkb_atom_t name;
552
553     if (def->ndx < 1 || def->ndx > XKB_MAX_LEDS) {
554         info->errorCount++;
555         log_err(info->ctx,
556                 "Illegal indicator index (%d) specified; must be between 1 .. %d; "
557                 "Ignored\n", def->ndx, XKB_MAX_LEDS);
558         return false;
559     }
560
561     if (!ExprResolveString(info->ctx, def->name, &name)) {
562         char buf[20];
563         snprintf(buf, sizeof(buf), "%d", def->ndx);
564         info->errorCount++;
565         return ReportBadType(info->ctx, "indicator", "name", buf, "string");
566     }
567
568     ledi.merge = info->merge;
569     ledi.file_id = info->file_id;
570     ledi.name = name;
571     return AddLedName(info, merge, &ledi, def->ndx - 1);
572 }
573
574 static void
575 HandleKeycodesFile(KeyNamesInfo *info, XkbFile *file, enum merge_mode merge)
576 {
577     bool ok;
578
579     free(info->name);
580     info->name = strdup_safe(file->name);
581
582     for (ParseCommon *stmt = file->defs; stmt; stmt = stmt->next) {
583         switch (stmt->type) {
584         case STMT_INCLUDE:
585             ok = HandleIncludeKeycodes(info, (IncludeStmt *) stmt);
586             break;
587         case STMT_KEYCODE:
588             ok = HandleKeycodeDef(info, (KeycodeDef *) stmt, merge);
589             break;
590         case STMT_ALIAS:
591             ok = HandleAliasDef(info, (KeyAliasDef *) stmt, merge);
592             break;
593         case STMT_VAR:
594             ok = HandleKeyNameVar(info, (VarDef *) stmt);
595             break;
596         case STMT_LED_NAME:
597             ok = HandleLedNameDef(info, (LedNameDef *) stmt, merge);
598             break;
599         default:
600             log_err(info->ctx,
601                     "Keycode files may define key and indicator names only; "
602                     "Ignoring %s\n", stmt_type_to_string(stmt->type));
603             ok = false;
604             break;
605         }
606
607         if (!ok)
608             info->errorCount++;
609
610         if (info->errorCount > 10) {
611             log_err(info->ctx, "Abandoning keycodes file \"%s\"\n",
612                     file->topName);
613             break;
614         }
615     }
616 }
617
618 /***====================================================================***/
619
620 static void
621 CopyAliasesToKeymap(KeyNamesInfo *info, struct xkb_keymap *keymap)
622 {
623     AliasInfo *alias;
624
625     darray_foreach(alias, info->aliases) {
626         struct xkb_key *key;
627         struct xkb_key_alias new;
628
629         /* Check that ->real is a key. */
630         key = XkbKeyByName(keymap, alias->real, false);
631         if (!key) {
632             log_vrb(info->ctx, 5,
633                     "Attempt to alias %s to non-existent key %s; Ignored\n",
634                     KeyNameText(info->ctx, alias->alias),
635                     KeyNameText(info->ctx, alias->real));
636             continue;
637         }
638
639         /* Check that ->alias is not a key. */
640         key = XkbKeyByName(keymap, alias->alias, false);
641         if (key) {
642             log_vrb(info->ctx, 5,
643                     "Attempt to create alias with the name of a real key; "
644                     "Alias \"%s = %s\" ignored\n",
645                     KeyNameText(info->ctx, alias->alias),
646                     KeyNameText(info->ctx, alias->real));
647             continue;
648         }
649
650         /* Add the alias. */
651         new.alias = alias->alias;
652         new.real = alias->real;
653         darray_append(keymap->key_aliases, new);
654     }
655
656     darray_free(info->aliases);
657 }
658
659 static bool
660 CopyKeyNamesToKeymap(struct xkb_keymap *keymap, KeyNamesInfo *info)
661 {
662     xkb_keycode_t kc;
663     xkb_led_index_t idx;
664     LedNameInfo *ledi;
665
666     keymap->keys = calloc(info->max_key_code + 1, sizeof(*keymap->keys));
667     if (!keymap->keys)
668         return false;
669
670     keymap->min_key_code = info->min_key_code;
671     keymap->max_key_code = info->max_key_code;
672
673     for (kc = info->min_key_code; kc <= info->max_key_code; kc++) {
674         keymap->keys[kc].keycode = kc;
675         keymap->keys[kc].name = darray_item(info->key_names, kc).name;
676     }
677
678     keymap->keycodes_section_name = strdup_safe(info->name);
679
680     darray_resize0(keymap->leds, darray_size(info->led_names));
681     darray_enumerate(idx, ledi, info->led_names) {
682         if (ledi->name == XKB_ATOM_NONE)
683             continue;
684
685         darray_item(keymap->leds, idx).name = ledi->name;
686     }
687
688     CopyAliasesToKeymap(info, keymap);
689
690     return true;
691 }
692
693 /***====================================================================***/
694
695 bool
696 CompileKeycodes(XkbFile *file, struct xkb_keymap *keymap,
697                 enum merge_mode merge)
698 {
699     KeyNamesInfo info;
700
701     InitKeyNamesInfo(&info, keymap->ctx, file->id);
702
703     HandleKeycodesFile(&info, file, merge);
704     if (info.errorCount != 0)
705         goto err_info;
706
707     if (!CopyKeyNamesToKeymap(keymap, &info))
708         goto err_info;
709
710     ClearKeyNamesInfo(&info);
711     return true;
712
713 err_info:
714     ClearKeyNamesInfo(&info);
715     return false;
716 }