symbols: fix real/alias key merge ordering bug
[platform/upstream/libxkbcommon.git] / src / xkbcomp / symbols.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 /*
28  * Copyright © 2012 Intel Corporation
29  * Copyright © 2012 Ran Benita <ran234@gmail.com>
30  *
31  * Permission is hereby granted, free of charge, to any person obtaining a
32  * copy of this software and associated documentation files (the "Software"),
33  * to deal in the Software without restriction, including without limitation
34  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
35  * and/or sell copies of the Software, and to permit persons to whom the
36  * Software is furnished to do so, subject to the following conditions:
37  *
38  * The above copyright notice and this permission notice (including the next
39  * paragraph) shall be included in all copies or substantial portions of the
40  * Software.
41  *
42  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
43  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
44  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
45  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
46  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
47  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
48  * DEALINGS IN THE SOFTWARE.
49  *
50  * Author: Daniel Stone <daniel@fooishbar.org>
51  *         Ran Benita <ran234@gmail.com>
52  */
53
54 #include "xkbcomp-priv.h"
55 #include "text.h"
56 #include "expr.h"
57 #include "action.h"
58 #include "vmod.h"
59 #include "keycodes.h"
60 #include "include.h"
61
62 enum key_repeat {
63     KEY_REPEAT_YES = 1,
64     KEY_REPEAT_NO = 0,
65     KEY_REPEAT_UNDEFINED = -1
66 };
67
68 enum group_field {
69     GROUP_FIELD_SYMS = (1 << 0),
70     GROUP_FIELD_ACTS = (1 << 1),
71     GROUP_FIELD_TYPE = (1 << 2),
72 };
73
74 enum key_field {
75     KEY_FIELD_REPEAT    = (1 << 0),
76     KEY_FIELD_TYPE_DFLT = (1 << 1),
77     KEY_FIELD_GROUPINFO = (1 << 2),
78     KEY_FIELD_VMODMAP   = (1 << 3),
79 };
80
81 typedef struct {
82     unsigned int num_syms;
83     unsigned int sym_index;
84     union xkb_action act;
85 } LevelInfo;
86
87 typedef darray(xkb_keysym_t) darray_xkb_keysym_t;
88
89 typedef struct {
90     enum group_field defined;
91     darray_xkb_keysym_t syms;
92     darray(LevelInfo) levels;
93     xkb_atom_t type;
94 } GroupInfo;
95
96 typedef struct _KeyInfo {
97     enum key_field defined;
98     unsigned file_id;
99     enum merge_mode merge;
100
101     unsigned long name; /* the 4 chars of the key name, as long */
102
103     GroupInfo groups[XKB_NUM_GROUPS];
104
105     enum key_repeat repeat;
106     xkb_mod_mask_t vmodmap;
107     xkb_atom_t dfltType;
108
109     enum xkb_range_exceed_type out_of_range_group_action;
110     xkb_group_index_t out_of_range_group_number;
111 } KeyInfo;
112
113 static void
114 InitGroupInfo(GroupInfo *groupi)
115 {
116     memset(groupi, 0, sizeof(*groupi));
117 }
118
119 static void
120 ClearGroupInfo(GroupInfo *groupi)
121 {
122     darray_free(groupi->syms);
123     darray_free(groupi->levels);
124     InitGroupInfo(groupi);
125 }
126
127 static void
128 InitKeyInfo(KeyInfo *keyi, unsigned file_id)
129 {
130     xkb_group_index_t i;
131     static const char dflt[4] = "*";
132
133     keyi->defined = 0;
134     keyi->file_id = file_id;
135     keyi->merge = MERGE_OVERRIDE;
136     keyi->name = KeyNameToLong(dflt);
137     for (i = 0; i < XKB_NUM_GROUPS; i++)
138         InitGroupInfo(&keyi->groups[i]);
139     keyi->dfltType = XKB_ATOM_NONE;
140     keyi->vmodmap = 0;
141     keyi->repeat = KEY_REPEAT_UNDEFINED;
142     keyi->out_of_range_group_action = RANGE_WRAP;
143     keyi->out_of_range_group_number = 0;
144 }
145
146 static void
147 ClearKeyInfo(KeyInfo *keyi)
148 {
149     xkb_group_index_t i;
150
151     for (i = 0; i < XKB_NUM_GROUPS; i++)
152         ClearGroupInfo(&keyi->groups[i]);
153 }
154
155 static bool
156 CopyKeyInfo(KeyInfo * old, KeyInfo * new, bool clearOld)
157 {
158     xkb_group_index_t i;
159
160     *new = *old;
161
162     if (clearOld) {
163         for (i = 0; i < XKB_NUM_GROUPS; i++) {
164             InitGroupInfo(&old->groups[i]);
165         }
166     }
167     else {
168         for (i = 0; i < XKB_NUM_GROUPS; i++) {
169             darray_copy(new->groups[i].syms, old->groups[i].syms);
170             darray_copy(new->groups[i].levels, old->groups[i].levels);
171         }
172     }
173
174     return true;
175 }
176
177 /***====================================================================***/
178
179 typedef struct _ModMapEntry {
180     enum merge_mode merge;
181     bool haveSymbol;
182     int modifier;
183     union {
184         unsigned long keyName;
185         xkb_keysym_t keySym;
186     } u;
187 } ModMapEntry;
188
189 typedef struct _SymbolsInfo {
190     char *name;         /* e.g. pc+us+inet(evdev) */
191     int errorCount;
192     unsigned file_id;
193     enum merge_mode merge;
194     xkb_group_index_t explicit_group;
195     darray(KeyInfo) keys;
196     KeyInfo dflt;
197     VModInfo vmods;
198     ActionsInfo *actions;
199     xkb_atom_t groupNames[XKB_NUM_GROUPS];
200     darray(ModMapEntry) modMaps;
201
202     struct xkb_keymap *keymap;
203 } SymbolsInfo;
204
205 static void
206 InitSymbolsInfo(SymbolsInfo *info, struct xkb_keymap *keymap,
207                 unsigned file_id, ActionsInfo *actions)
208 {
209     xkb_group_index_t i;
210
211     info->name = NULL;
212     info->explicit_group = 0;
213     info->errorCount = 0;
214     info->file_id = file_id;
215     info->merge = MERGE_OVERRIDE;
216     darray_init(info->keys);
217     darray_growalloc(info->keys, 110);
218     darray_init(info->modMaps);
219     for (i = 0; i < XKB_NUM_GROUPS; i++)
220         info->groupNames[i] = XKB_ATOM_NONE;
221     InitKeyInfo(&info->dflt, file_id);
222     InitVModInfo(&info->vmods, keymap);
223     info->actions = actions;
224     info->keymap = keymap;
225 }
226
227 static void
228 ClearSymbolsInfo(SymbolsInfo * info)
229 {
230     KeyInfo *keyi;
231
232     free(info->name);
233     darray_foreach(keyi, info->keys)
234         ClearKeyInfo(keyi);
235     darray_free(info->keys);
236     darray_free(info->modMaps);
237     memset(info, 0, sizeof(SymbolsInfo));
238 }
239
240 static bool
241 MergeGroups(SymbolsInfo *info, GroupInfo *into, GroupInfo *from, bool clobber,
242             bool report, xkb_group_index_t group, unsigned long key_name)
243 {
244     xkb_level_index_t i, numLevels;
245     enum { INTO = (1 << 0), FROM = (1 << 1) } using;
246
247     /* First find the type of the merged group. */
248     if (into->type != from->type) {
249         if (from->type == XKB_ATOM_NONE) {
250         }
251         else if (into->type == XKB_ATOM_NONE) {
252             into->type = from->type;
253         }
254         else {
255             xkb_atom_t use = (clobber ? from->type : into->type);
256             xkb_atom_t ignore = (clobber ? into->type : from->type);
257
258             if (report)
259                 log_warn(info->keymap->ctx,
260                          "Multiple definitions for group %d type of key %s; "
261                          "Using %s, ignoring %s\n",
262                          group + 1, LongKeyNameText(key_name),
263                          xkb_atom_text(info->keymap->ctx, use),
264                          xkb_atom_text(info->keymap->ctx, ignore));
265
266             into->type = use;
267         }
268     }
269     into->defined |= (from->defined & GROUP_FIELD_TYPE);
270
271     /* Now look at the levels. */
272
273     if (darray_empty(from->levels)) {
274         InitGroupInfo(from);
275         return true;
276     }
277
278     if (darray_empty(into->levels)) {
279         from->type = into->type;
280         *into = *from;
281         InitGroupInfo(from);
282         return true;
283     }
284
285     /* First we merge the actions and ensure @into has all the levels. */
286     numLevels = MAX(darray_size(into->levels), darray_size(from->levels));
287     for (i = 0; i < numLevels; i++) {
288         union xkb_action *intoAct, *fromAct;
289
290         if (i >= darray_size(from->levels))
291             continue;
292
293         if (i >= darray_size(into->levels)) {
294             darray_append(into->levels, darray_item(from->levels, i));
295             darray_item(into->levels, i).num_syms = 0;
296             darray_item(into->levels, i).sym_index = 0;
297             continue;
298         }
299
300         intoAct = &darray_item(into->levels, i).act;
301         fromAct = &darray_item(from->levels, i).act;
302
303         if (fromAct->type == ACTION_TYPE_NONE) {
304         }
305         else if (intoAct->type == ACTION_TYPE_NONE) {
306             *intoAct = *fromAct;
307         }
308         else {
309             union xkb_action *use = (clobber ? fromAct : intoAct);
310             union xkb_action *ignore = (clobber ? intoAct : fromAct);
311
312             if (report)
313                 log_warn(info->keymap->ctx,
314                          "Multiple actions for level %d/group %u on key %s; "
315                          "Using %s, ignoring %s\n",
316                          i + 1, group + 1, LongKeyNameText(key_name),
317                          ActionTypeText(use->type),
318                          ActionTypeText(ignore->type));
319
320             *intoAct = *use;
321         }
322     }
323     into->defined |= (from->defined & GROUP_FIELD_ACTS);
324
325     /* Then merge the keysyms. */
326
327     /*
328      * We want to avoid copying and allocating if not necessary. So
329      * here we do a pre-scan of the levels to check if we'll only use
330      * @into's or @from's keysyms, and if so we'll just assign them.
331      * However if one level uses @into's and another uses @from's, we
332      * will need to construct a new syms array.
333      */
334     using = 0;
335     for (i = 0; i < numLevels; i++) {
336         unsigned int intoSize, fromSize;
337
338         intoSize = darray_item(into->levels, i).num_syms;
339         if (i < darray_size(from->levels))
340             fromSize = darray_item(from->levels, i).num_syms;
341         else
342             fromSize = 0;
343
344         if (intoSize == 0 && fromSize == 0)
345             using |= 0;
346         else if (intoSize == 0)
347             using |= FROM;
348         else if (fromSize == 0)
349             using |= INTO;
350         else
351             using |= (clobber ? FROM : INTO);
352     }
353
354     if (using == 0 || using == INTO) {
355     }
356     else if (using == FROM) {
357         darray_free(into->syms);
358         into->syms = from->syms;
359         darray_init(from->syms);
360         for (i = 0; i < darray_size(from->levels); i++) {
361             darray_item(into->levels, i).num_syms =
362                 darray_item(from->levels, i).num_syms;
363             darray_item(into->levels, i).sym_index =
364                 darray_item(from->levels, i).sym_index;
365         }
366     }
367     else {
368         darray_xkb_keysym_t syms = darray_new();
369
370         for (i = 0; i < numLevels; i++) {
371             unsigned int intoSize, fromSize;
372
373             intoSize = darray_item(into->levels, i).num_syms;
374             if (i < darray_size(from->levels))
375                 fromSize = darray_item(from->levels, i).num_syms;
376             else
377                 fromSize = 0;
378
379             /* Empty level. */
380             if (intoSize == 0 && fromSize == 0)
381                 continue;
382
383             if (intoSize != 0 && fromSize != 0 && report)
384                 log_info(info->keymap->ctx,
385                          "Multiple symbols for group %u, level %d on key %s; "
386                          "Using %s, ignoring %s\n",
387                          group + 1, i + 1, LongKeyNameText(key_name),
388                          (clobber ? "from" : "to"),
389                          (clobber ? "to" : "from"));
390
391             if (intoSize == 0 || (fromSize != 0 && clobber)) {
392                 unsigned sym_index = darray_item(from->levels, i).sym_index;
393                 darray_item(into->levels, i).sym_index = darray_size(syms);
394                 darray_item(into->levels, i).num_syms = fromSize;
395                 darray_append_items(syms, &darray_item(from->syms, sym_index),
396                                     fromSize);
397             }
398             else
399             {
400                 unsigned sym_index = darray_item(into->levels, i).sym_index;
401                 darray_item(into->levels, i).sym_index = darray_size(syms);
402                 darray_item(into->levels, i).num_syms = intoSize;
403                 darray_append_items(syms, &darray_item(into->syms, sym_index),
404                                     intoSize);
405             }
406         }
407         darray_free(into->syms);
408         into->syms = syms;
409     }
410     into->defined |= (from->defined & GROUP_FIELD_SYMS);
411
412     return true;
413 }
414
415 static bool
416 UseNewKeyField(enum key_field field, enum key_field old, enum key_field new,
417                bool clobber, bool report, enum key_field *collide)
418 {
419     if (!(old & field))
420         return (new & field);
421
422     if (new & field) {
423         if (report)
424             *collide |= field;
425
426         if (clobber)
427             return true;
428     }
429
430     return false;
431 }
432
433
434 static bool
435 MergeKeys(SymbolsInfo *info, KeyInfo *into, KeyInfo *from)
436 {
437     xkb_group_index_t i;
438     enum key_field collide = 0;
439     bool clobber, report;
440     int verbosity = xkb_get_log_verbosity(info->keymap->ctx);
441
442     if (from->merge == MERGE_REPLACE) {
443         ClearKeyInfo(into);
444         *into = *from;
445         InitKeyInfo(from, info->file_id);
446         return true;
447     }
448
449     clobber = (from->merge != MERGE_AUGMENT);
450     report = (verbosity > 9 ||
451               (into->file_id == from->file_id && verbosity > 0));
452
453     for (i = 0; i < XKB_NUM_GROUPS; i++)
454         MergeGroups(info, &into->groups[i], &from->groups[i], clobber,
455                     report, i, into->name);
456
457     if (UseNewKeyField(KEY_FIELD_VMODMAP, into->defined, from->defined,
458                        clobber, report, &collide)) {
459         into->vmodmap = from->vmodmap;
460         into->defined |= KEY_FIELD_VMODMAP;
461     }
462     if (UseNewKeyField(KEY_FIELD_REPEAT, into->defined, from->defined,
463                        clobber, report, &collide)) {
464         into->repeat = from->repeat;
465         into->defined |= KEY_FIELD_REPEAT;
466     }
467     if (UseNewKeyField(KEY_FIELD_TYPE_DFLT, into->defined, from->defined,
468                        clobber, report, &collide)) {
469         into->dfltType = from->dfltType;
470         into->defined |= KEY_FIELD_TYPE_DFLT;
471     }
472     if (UseNewKeyField(KEY_FIELD_GROUPINFO, into->defined, from->defined,
473                        clobber, report, &collide)) {
474         into->out_of_range_group_action = from->out_of_range_group_action;
475         into->out_of_range_group_number = from->out_of_range_group_number;
476         into->defined |= KEY_FIELD_GROUPINFO;
477     }
478
479     if (collide)
480         log_warn(info->keymap->ctx,
481                  "Symbol map for key %s redefined; "
482                  "Using %s definition for conflicting fields\n",
483                  LongKeyNameText(into->name),
484                  (clobber ? "first" : "last"));
485
486     ClearKeyInfo(from);
487     return true;
488 }
489
490 static bool
491 AddKeySymbols(SymbolsInfo *info, KeyInfo *keyi)
492 {
493     unsigned long real_name;
494     KeyInfo *iter, *new;
495
496     /*
497      * Don't keep aliases in the keys array; this guarantees that
498      * searching for keys to merge with by straight comparison (see the
499      * following loop) is enough, and we won't get multiple KeyInfo's
500      * for the same key because of aliases.
501      */
502     if (FindKeyNameForAlias(info->keymap, keyi->name, &real_name))
503         keyi->name = real_name;
504
505     darray_foreach(iter, info->keys)
506         if (iter->name == keyi->name)
507             return MergeKeys(info, iter, keyi);
508
509     darray_resize0(info->keys, darray_size(info->keys) + 1);
510     new = &darray_item(info->keys, darray_size(info->keys) - 1);
511     return CopyKeyInfo(keyi, new, true);
512 }
513
514 static bool
515 AddModMapEntry(SymbolsInfo * info, ModMapEntry * new)
516 {
517     ModMapEntry *mm;
518     bool clobber;
519
520     clobber = (new->merge != MERGE_AUGMENT);
521     darray_foreach(mm, info->modMaps) {
522         if (new->haveSymbol && mm->haveSymbol
523             && (new->u.keySym == mm->u.keySym)) {
524             unsigned use, ignore;
525             if (mm->modifier != new->modifier) {
526                 if (clobber) {
527                     use = new->modifier;
528                     ignore = mm->modifier;
529                 }
530                 else {
531                     use = mm->modifier;
532                     ignore = new->modifier;
533                 }
534                 log_err(info->keymap->ctx,
535                         "%s added to symbol map for multiple modifiers; "
536                         "Using %s, ignoring %s.\n",
537                         KeysymText(new->u.keySym), ModIndexText(use),
538                         ModIndexText(ignore));
539                 mm->modifier = use;
540             }
541             return true;
542         }
543         if ((!new->haveSymbol) && (!mm->haveSymbol) &&
544             (new->u.keyName == mm->u.keyName)) {
545             unsigned use, ignore;
546             if (mm->modifier != new->modifier) {
547                 if (clobber) {
548                     use = new->modifier;
549                     ignore = mm->modifier;
550                 }
551                 else {
552                     use = mm->modifier;
553                     ignore = new->modifier;
554                 }
555                 log_err(info->keymap->ctx,
556                         "Key %s added to map for multiple modifiers; "
557                         "Using %s, ignoring %s.\n",
558                         LongKeyNameText(new->u.keyName), ModIndexText(use),
559                         ModIndexText(ignore));
560                 mm->modifier = use;
561             }
562             return true;
563         }
564     }
565
566     darray_append(info->modMaps, *new);
567     return true;
568 }
569
570 /***====================================================================***/
571
572 static void
573 MergeIncludedSymbols(SymbolsInfo *into, SymbolsInfo *from,
574                      enum merge_mode merge)
575 {
576     unsigned int i;
577     KeyInfo *keyi;
578     ModMapEntry *mm;
579
580     if (from->errorCount > 0) {
581         into->errorCount += from->errorCount;
582         return;
583     }
584     if (into->name == NULL) {
585         into->name = from->name;
586         from->name = NULL;
587     }
588     for (i = 0; i < XKB_NUM_GROUPS; i++) {
589         if (from->groupNames[i] != XKB_ATOM_NONE) {
590             if ((merge != MERGE_AUGMENT) ||
591                 (into->groupNames[i] == XKB_ATOM_NONE))
592                 into->groupNames[i] = from->groupNames[i];
593         }
594     }
595
596     darray_foreach(keyi, from->keys) {
597         merge = (merge == MERGE_DEFAULT ? keyi->merge : merge);
598         if (!AddKeySymbols(into, keyi))
599             into->errorCount++;
600     }
601
602     darray_foreach(mm, from->modMaps) {
603         mm->merge = (merge == MERGE_DEFAULT ? mm->merge : merge);
604         if (!AddModMapEntry(into, mm))
605             into->errorCount++;
606     }
607 }
608
609 static void
610 HandleSymbolsFile(SymbolsInfo *info, XkbFile *file, enum merge_mode merge);
611
612 static bool
613 HandleIncludeSymbols(SymbolsInfo *info, IncludeStmt *stmt)
614 {
615     enum merge_mode merge = MERGE_DEFAULT;
616     XkbFile *rtrn;
617     SymbolsInfo included, next_incl;
618
619     InitSymbolsInfo(&included, info->keymap, info->file_id, info->actions);
620     if (stmt->stmt) {
621         free(included.name);
622         included.name = stmt->stmt;
623         stmt->stmt = NULL;
624     }
625
626     for (; stmt; stmt = stmt->next_incl) {
627         if (!ProcessIncludeFile(info->keymap->ctx, stmt, FILE_TYPE_SYMBOLS,
628                                 &rtrn, &merge)) {
629             info->errorCount += 10;
630             ClearSymbolsInfo(&included);
631             return false;
632         }
633
634         InitSymbolsInfo(&next_incl, info->keymap, rtrn->id, info->actions);
635         next_incl.merge = next_incl.dflt.merge = MERGE_OVERRIDE;
636         if (stmt->modifier)
637             next_incl.explicit_group = atoi(stmt->modifier) - 1;
638         else
639             next_incl.explicit_group = info->explicit_group;
640
641         HandleSymbolsFile(&next_incl, rtrn, MERGE_OVERRIDE);
642
643         MergeIncludedSymbols(&included, &next_incl, merge);
644
645         ClearSymbolsInfo(&next_incl);
646         FreeXkbFile(rtrn);
647     }
648
649     MergeIncludedSymbols(info, &included, merge);
650     ClearSymbolsInfo(&included);
651
652     return (info->errorCount == 0);
653 }
654
655 #define SYMBOLS 1
656 #define ACTIONS 2
657
658 static bool
659 GetGroupIndex(SymbolsInfo *info, KeyInfo *keyi, ExprDef *arrayNdx,
660               unsigned what, xkb_group_index_t *ndx_rtrn)
661 {
662     const char *name = (what == SYMBOLS ? "symbols" : "actions");
663
664     if (arrayNdx == NULL) {
665         xkb_group_index_t i;
666         enum group_field field = (what == SYMBOLS ?
667                                   GROUP_FIELD_SYMS : GROUP_FIELD_ACTS);
668
669         for (i = 0; i < XKB_NUM_GROUPS; i++) {
670             if (!(keyi->groups[i].defined & field)) {
671                 *ndx_rtrn = i;
672                 return true;
673             }
674         }
675
676         log_err(info->keymap->ctx,
677                 "Too many groups of %s for key %s (max %u); "
678                 "Ignoring %s defined for extra groups\n",
679                 name, LongKeyNameText(keyi->name), XKB_NUM_GROUPS + 1, name);
680         return false;
681     }
682
683     if (!ExprResolveGroup(info->keymap->ctx, arrayNdx, ndx_rtrn)) {
684         log_err(info->keymap->ctx,
685                 "Illegal group index for %s of key %s\n"
686                 "Definition with non-integer array index ignored\n",
687                 name, LongKeyNameText(keyi->name));
688         return false;
689     }
690
691     (*ndx_rtrn)--;
692     return true;
693 }
694
695 bool
696 LookupKeysym(const char *str, xkb_keysym_t *sym_rtrn)
697 {
698     xkb_keysym_t sym;
699
700     if (!str || istreq(str, "any") || istreq(str, "nosymbol")) {
701         *sym_rtrn = XKB_KEY_NoSymbol;
702         return 1;
703     }
704
705     if (istreq(str, "none") || istreq(str, "voidsymbol")) {
706         *sym_rtrn = XKB_KEY_VoidSymbol;
707         return 1;
708     }
709
710     sym = xkb_keysym_from_name(str);
711     if (sym != XKB_KEY_NoSymbol) {
712         *sym_rtrn = sym;
713         return 1;
714     }
715
716     return 0;
717 }
718
719 static bool
720 AddSymbolsToKey(SymbolsInfo *info, KeyInfo *keyi, ExprDef *arrayNdx,
721                 ExprDef *value)
722 {
723     xkb_group_index_t ndx;
724     GroupInfo *groupi;
725     unsigned int nSyms;
726     xkb_level_index_t nLevels;
727     xkb_level_index_t i;
728     int j;
729
730     if (!GetGroupIndex(info, keyi, arrayNdx, SYMBOLS, &ndx))
731         return false;
732
733     groupi = &keyi->groups[ndx];
734
735     if (value == NULL) {
736         groupi->defined |= GROUP_FIELD_SYMS;
737         return true;
738     }
739
740     if (value->op != EXPR_KEYSYM_LIST) {
741         log_err(info->keymap->ctx,
742                 "Expected a list of symbols, found %s; "
743                 "Ignoring symbols for group %u of %s\n",
744                 expr_op_type_to_string(value->op), ndx + 1,
745                 LongKeyNameText(keyi->name));
746         return false;
747     }
748
749     if (groupi->defined & GROUP_FIELD_SYMS) {
750         log_err(info->keymap->ctx,
751                 "Symbols for key %s, group %u already defined; "
752                 "Ignoring duplicate definition\n",
753                 LongKeyNameText(keyi->name), ndx + 1);
754         return false;
755     }
756
757     nSyms = darray_size(value->value.list.syms);
758     nLevels = darray_size(value->value.list.symsMapIndex);
759
760     if (darray_size(groupi->syms) < nSyms)
761         darray_resize0(groupi->syms, nSyms);
762
763     if (darray_size(groupi->levels) < nLevels)
764         darray_resize0(groupi->levels, nLevels);
765
766     groupi->defined |= GROUP_FIELD_SYMS;
767
768     for (i = 0; i < nLevels; i++) {
769         LevelInfo *leveli = &darray_item(groupi->levels, i);
770
771         leveli->sym_index = darray_item(value->value.list.symsMapIndex, i);
772         leveli->num_syms = darray_item(value->value.list.symsNumEntries, i);
773
774         for (j = 0; j < leveli->num_syms; j++) {
775             if (!LookupKeysym(darray_item(value->value.list.syms,
776                                           leveli->sym_index + j),
777                               &darray_item(groupi->syms,
778                                            leveli->sym_index + j))) {
779                 log_warn(info->keymap->ctx,
780                          "Could not resolve keysym %s for key %s, group %u (%s), level %u\n",
781                          darray_item(value->value.list.syms, i),
782                          LongKeyNameText(keyi->name),
783                          ndx + 1,
784                          xkb_atom_text(info->keymap->ctx,
785                                        info->groupNames[ndx]),
786                          nSyms);
787                 leveli->sym_index = 0;
788                 leveli->num_syms = 0;
789                 break;
790             }
791
792             if (leveli->num_syms == 1 &&
793                 darray_item(groupi->syms,
794                             leveli->sym_index + j) == XKB_KEY_NoSymbol) {
795                 leveli->sym_index = 0;
796                 leveli->num_syms = 0;
797             }
798         }
799     }
800
801     for (j = darray_size(groupi->levels) - 1;
802          j >= 0 && darray_item(groupi->levels, j).num_syms == 0; j--)
803         (void) darray_pop(groupi->levels);
804
805     return true;
806 }
807
808 static bool
809 AddActionsToKey(SymbolsInfo *info, KeyInfo *keyi, ExprDef *arrayNdx,
810                 ExprDef *value)
811 {
812     unsigned int i;
813     xkb_group_index_t ndx;
814     GroupInfo *groupi;
815     unsigned int nActs;
816     ExprDef *act;
817     union xkb_action *toAct;
818
819     if (!GetGroupIndex(info, keyi, arrayNdx, ACTIONS, &ndx))
820         return false;
821
822     groupi = &keyi->groups[ndx];
823
824     if (value == NULL) {
825         groupi->defined |= GROUP_FIELD_ACTS;
826         return true;
827     }
828
829     if (value->op != EXPR_ACTION_LIST) {
830         log_wsgo(info->keymap->ctx,
831                  "Bad expression type (%d) for action list value; "
832                  "Ignoring actions for group %u of %s\n",
833                  value->op, ndx, LongKeyNameText(keyi->name));
834         return false;
835     }
836
837     if (groupi->defined & GROUP_FIELD_ACTS) {
838         log_wsgo(info->keymap->ctx,
839                  "Actions for key %s, group %u already defined\n",
840                  LongKeyNameText(keyi->name), ndx);
841         return false;
842     }
843
844     nActs = 0;
845     for (act = value->value.child; act; act = (ExprDef *) act->common.next)
846         nActs++;
847
848     if (darray_size(groupi->levels) < nActs)
849         darray_resize0(groupi->levels, nActs);
850
851     groupi->defined |= GROUP_FIELD_ACTS;
852
853     act = value->value.child;
854     for (i = 0; i < nActs; i++) {
855         toAct = &darray_item(groupi->levels, i).act;
856
857         if (!HandleActionDef(act, info->keymap, toAct, info->actions))
858             log_err(info->keymap->ctx,
859                     "Illegal action definition for %s; "
860                     "Action for group %u/level %u ignored\n",
861                     LongKeyNameText(keyi->name), ndx + 1, i + 1);
862
863         act = (ExprDef *) act->common.next;
864     }
865
866     return true;
867 }
868
869 static const LookupEntry repeatEntries[] = {
870     { "true", KEY_REPEAT_YES },
871     { "yes", KEY_REPEAT_YES },
872     { "on", KEY_REPEAT_YES },
873     { "false", KEY_REPEAT_NO },
874     { "no", KEY_REPEAT_NO },
875     { "off", KEY_REPEAT_NO },
876     { "default", KEY_REPEAT_UNDEFINED },
877     { NULL, 0 }
878 };
879
880 static bool
881 SetSymbolsField(SymbolsInfo *info, KeyInfo *keyi, const char *field,
882                 ExprDef *arrayNdx, ExprDef *value)
883 {
884     bool ok = true;
885     struct xkb_context *ctx = info->keymap->ctx;
886
887     if (istreq(field, "type")) {
888         xkb_group_index_t ndx;
889         xkb_atom_t val;
890
891         if (!ExprResolveString(ctx, value, &val))
892             log_vrb(ctx, 1,
893                     "The type field of a key symbol map must be a string; "
894                     "Ignoring illegal type definition\n");
895
896         if (arrayNdx == NULL) {
897             keyi->dfltType = val;
898             keyi->defined |= KEY_FIELD_TYPE_DFLT;
899         }
900         else if (!ExprResolveGroup(ctx, arrayNdx, &ndx)) {
901             log_err(ctx,
902                     "Illegal group index for type of key %s; "
903                     "Definition with non-integer array index ignored\n",
904                     LongKeyNameText(keyi->name));
905             return false;
906         }
907         else {
908             ndx--;
909             keyi->groups[ndx].type = val;
910             keyi->groups[ndx].defined |= GROUP_FIELD_TYPE;
911         }
912     }
913     else if (istreq(field, "symbols"))
914         return AddSymbolsToKey(info, keyi, arrayNdx, value);
915     else if (istreq(field, "actions"))
916         return AddActionsToKey(info, keyi, arrayNdx, value);
917     else if (istreq(field, "vmods") ||
918              istreq(field, "virtualmods") ||
919              istreq(field, "virtualmodifiers")) {
920         xkb_mod_mask_t mask;
921
922         ok = ExprResolveVModMask(info->keymap, value, &mask);
923         if (ok) {
924             keyi->vmodmap = (mask >> XKB_NUM_CORE_MODS) & 0xffff;
925             keyi->defined |= KEY_FIELD_VMODMAP;
926         }
927         else {
928             log_err(info->keymap->ctx,
929                     "Expected a virtual modifier mask, found %s; "
930                     "Ignoring virtual modifiers definition for key %s\n",
931                     expr_op_type_to_string(value->op),
932                     LongKeyNameText(keyi->name));
933         }
934     }
935     else if (istreq(field, "locking") ||
936              istreq(field, "lock") ||
937              istreq(field, "locks")) {
938         log_err(info->keymap->ctx,
939                 "Key behaviors not supported; "
940                 "Ignoring locking specification for key %s\n",
941                 LongKeyNameText(keyi->name));
942     }
943     else if (istreq(field, "radiogroup") ||
944              istreq(field, "permanentradiogroup") ||
945              istreq(field, "allownone")) {
946         log_err(info->keymap->ctx,
947                 "Radio groups not supported; "
948                 "Ignoring radio group specification for key %s\n",
949                 LongKeyNameText(keyi->name));
950     }
951     else if (istreq_prefix("overlay", field) ||
952              istreq_prefix("permanentoverlay", field)) {
953         log_err(info->keymap->ctx,
954                 "Overlays not supported; "
955                 "Ignoring overlay specification for key %s\n",
956                 LongKeyNameText(keyi->name));
957     }
958     else if (istreq(field, "repeating") ||
959              istreq(field, "repeats") ||
960              istreq(field, "repeat")) {
961         unsigned int val;
962
963         ok = ExprResolveEnum(ctx, value, &val, repeatEntries);
964         if (!ok) {
965             log_err(info->keymap->ctx,
966                     "Illegal repeat setting for %s; "
967                     "Non-boolean repeat setting ignored\n",
968                     LongKeyNameText(keyi->name));
969             return false;
970         }
971         keyi->repeat = val;
972         keyi->defined |= KEY_FIELD_REPEAT;
973     }
974     else if (istreq(field, "groupswrap") ||
975              istreq(field, "wrapgroups")) {
976         bool set;
977
978         if (!ExprResolveBoolean(ctx, value, &set)) {
979             log_err(info->keymap->ctx,
980                     "Illegal groupsWrap setting for %s; "
981                     "Non-boolean value ignored\n",
982                     LongKeyNameText(keyi->name));
983             return false;
984         }
985
986         if (set)
987             keyi->out_of_range_group_action = RANGE_WRAP;
988         else
989             keyi->out_of_range_group_action = RANGE_SATURATE;
990
991         keyi->defined |= KEY_FIELD_GROUPINFO;
992     }
993     else if (istreq(field, "groupsclamp") ||
994              istreq(field, "clampgroups")) {
995         bool set;
996
997         if (!ExprResolveBoolean(ctx, value, &set)) {
998             log_err(info->keymap->ctx,
999                     "Illegal groupsClamp setting for %s; "
1000                     "Non-boolean value ignored\n",
1001                     LongKeyNameText(keyi->name));
1002             return false;
1003         }
1004
1005         if (set)
1006             keyi->out_of_range_group_action = RANGE_SATURATE;
1007         else
1008             keyi->out_of_range_group_action = RANGE_WRAP;
1009
1010         keyi->defined |= KEY_FIELD_GROUPINFO;
1011     }
1012     else if (istreq(field, "groupsredirect") ||
1013              istreq(field, "redirectgroups")) {
1014         xkb_group_index_t grp;
1015
1016         if (!ExprResolveGroup(ctx, value, &grp)) {
1017             log_err(info->keymap->ctx,
1018                     "Illegal group index for redirect of key %s; "
1019                     "Definition with non-integer group ignored\n",
1020                     LongKeyNameText(keyi->name));
1021             return false;
1022         }
1023
1024         keyi->out_of_range_group_action = RANGE_REDIRECT;
1025         keyi->out_of_range_group_number = grp - 1;
1026         keyi->defined |= KEY_FIELD_GROUPINFO;
1027     }
1028     else {
1029         log_err(info->keymap->ctx,
1030                 "Unknown field %s in a symbol interpretation; "
1031                 "Definition ignored\n",
1032                 field);
1033         ok = false;
1034     }
1035
1036     return ok;
1037 }
1038
1039 static int
1040 SetGroupName(SymbolsInfo *info, ExprDef *arrayNdx, ExprDef *value)
1041 {
1042     xkb_group_index_t grp;
1043     xkb_atom_t name;
1044
1045     if (!arrayNdx) {
1046         log_vrb(info->keymap->ctx, 1,
1047                 "You must specify an index when specifying a group name; "
1048                 "Group name definition without array subscript ignored\n");
1049         return false;
1050     }
1051
1052     if (!ExprResolveGroup(info->keymap->ctx, arrayNdx, &grp)) {
1053         log_err(info->keymap->ctx,
1054                 "Illegal index in group name definition; "
1055                 "Definition with non-integer array index ignored\n");
1056         return false;
1057     }
1058
1059     if (!ExprResolveString(info->keymap->ctx, value, &name)) {
1060         log_err(info->keymap->ctx,
1061                 "Group name must be a string; "
1062                 "Illegal name for group %d ignored\n", grp);
1063         return false;
1064     }
1065
1066     info->groupNames[grp - 1 + info->explicit_group] = name;
1067     return true;
1068 }
1069
1070 static int
1071 HandleSymbolsVar(SymbolsInfo *info, VarDef *stmt)
1072 {
1073     const char *elem, *field;
1074     ExprDef *arrayNdx;
1075     bool ret;
1076
1077     if (ExprResolveLhs(info->keymap->ctx, stmt->name, &elem, &field,
1078                        &arrayNdx) == 0)
1079         return 0;               /* internal error, already reported */
1080     if (elem && istreq(elem, "key")) {
1081         ret = SetSymbolsField(info, &info->dflt, field, arrayNdx,
1082                               stmt->value);
1083     }
1084     else if (!elem && (istreq(field, "name") ||
1085                        istreq(field, "groupname"))) {
1086         ret = SetGroupName(info, arrayNdx, stmt->value);
1087     }
1088     else if (!elem && (istreq(field, "groupswrap") ||
1089                        istreq(field, "wrapgroups"))) {
1090         log_err(info->keymap->ctx,
1091                 "Global \"groupswrap\" not supported; Ignored\n");
1092         ret = true;
1093     }
1094     else if (!elem && (istreq(field, "groupsclamp") ||
1095                        istreq(field, "clampgroups"))) {
1096         log_err(info->keymap->ctx,
1097                 "Global \"groupsclamp\" not supported; Ignored\n");
1098         ret = true;
1099     }
1100     else if (!elem && (istreq(field, "groupsredirect") ||
1101                        istreq(field, "redirectgroups"))) {
1102         log_err(info->keymap->ctx,
1103                 "Global \"groupsredirect\" not supported; Ignored\n");
1104         ret = true;
1105     }
1106     else if (!elem && istreq(field, "allownone")) {
1107         log_err(info->keymap->ctx,
1108                 "Radio groups not supported; "
1109                 "Ignoring \"allownone\" specification\n");
1110         ret = true;
1111     }
1112     else {
1113         ret = SetActionField(info->keymap, elem, field, arrayNdx, stmt->value,
1114                              info->actions);
1115     }
1116
1117     return ret;
1118 }
1119
1120 static bool
1121 HandleSymbolsBody(SymbolsInfo *info, VarDef *def, KeyInfo *keyi)
1122 {
1123     bool ok = true;
1124     const char *elem, *field;
1125     ExprDef *arrayNdx;
1126
1127     for (; def; def = (VarDef *) def->common.next) {
1128         if (def->name && def->name->op == EXPR_FIELD_REF) {
1129             ok = HandleSymbolsVar(info, def);
1130             continue;
1131         }
1132
1133         if (!def->name) {
1134             if (!def->value || def->value->op == EXPR_KEYSYM_LIST)
1135                 field = "symbols";
1136             else
1137                 field = "actions";
1138             arrayNdx = NULL;
1139         }
1140         else {
1141             ok = ExprResolveLhs(info->keymap->ctx, def->name, &elem, &field,
1142                                 &arrayNdx);
1143         }
1144
1145         if (ok)
1146             ok = SetSymbolsField(info, keyi, field, arrayNdx, def->value);
1147     }
1148
1149     return ok;
1150 }
1151
1152 static bool
1153 SetExplicitGroup(SymbolsInfo *info, KeyInfo *keyi)
1154 {
1155     xkb_group_index_t i;
1156
1157     if (info->explicit_group == 0)
1158         return true;
1159
1160     for (i = 1; i < XKB_NUM_GROUPS; i++) {
1161         if (keyi->groups[i].defined) {
1162             log_warn(info->keymap->ctx,
1163                      "For the map %s an explicit group specified, "
1164                      "but key %s has more than one group defined; "
1165                      "All groups except first one will be ignored\n",
1166                      info->name, LongKeyNameText(keyi->name));
1167             break;
1168         }
1169     }
1170     if (i < XKB_NUM_GROUPS)
1171         for (i = 1; i < XKB_NUM_GROUPS; i++)
1172             ClearGroupInfo(&keyi->groups[i]);
1173
1174     keyi->groups[info->explicit_group] = keyi->groups[0];
1175     InitGroupInfo(&keyi->groups[0]);
1176     return true;
1177 }
1178
1179 static int
1180 HandleSymbolsDef(SymbolsInfo *info, SymbolsDef *stmt)
1181 {
1182     KeyInfo keyi;
1183
1184     InitKeyInfo(&keyi, info->file_id);
1185     CopyKeyInfo(&info->dflt, &keyi, false);
1186     keyi.merge = stmt->merge;
1187     keyi.name = KeyNameToLong(stmt->keyName);
1188     if (!HandleSymbolsBody(info, (VarDef *) stmt->symbols, &keyi)) {
1189         info->errorCount++;
1190         return false;
1191     }
1192
1193     if (!SetExplicitGroup(info, &keyi)) {
1194         info->errorCount++;
1195         return false;
1196     }
1197
1198     if (!AddKeySymbols(info, &keyi)) {
1199         info->errorCount++;
1200         return false;
1201     }
1202     return true;
1203 }
1204
1205 static bool
1206 HandleModMapDef(SymbolsInfo *info, ModMapDef *def)
1207 {
1208     ExprDef *key;
1209     ModMapEntry tmp;
1210     xkb_mod_index_t ndx;
1211     bool ok;
1212     struct xkb_context *ctx = info->keymap->ctx;
1213
1214     if (!LookupModIndex(ctx, NULL, def->modifier, EXPR_TYPE_INT, &ndx)) {
1215         log_err(info->keymap->ctx,
1216                 "Illegal modifier map definition; "
1217                 "Ignoring map for non-modifier \"%s\"\n",
1218                 xkb_atom_text(ctx, def->modifier));
1219         return false;
1220     }
1221
1222     ok = true;
1223     tmp.modifier = ndx;
1224
1225     for (key = def->keys; key != NULL; key = (ExprDef *) key->common.next) {
1226         xkb_keysym_t sym;
1227
1228         if (key->op == EXPR_VALUE && key->value_type == EXPR_TYPE_KEYNAME) {
1229             tmp.haveSymbol = false;
1230             tmp.u.keyName = KeyNameToLong(key->value.keyName);
1231         }
1232         else if (ExprResolveKeySym(ctx, key, &sym)) {
1233             tmp.haveSymbol = true;
1234             tmp.u.keySym = sym;
1235         }
1236         else {
1237             log_err(info->keymap->ctx,
1238                     "Modmap entries may contain only key names or keysyms; "
1239                     "Illegal definition for %s modifier ignored\n",
1240                     ModIndexText(tmp.modifier));
1241             continue;
1242         }
1243
1244         ok = AddModMapEntry(info, &tmp) && ok;
1245     }
1246     return ok;
1247 }
1248
1249 static void
1250 HandleSymbolsFile(SymbolsInfo *info, XkbFile *file, enum merge_mode merge)
1251 {
1252     bool ok;
1253     ParseCommon *stmt;
1254
1255     free(info->name);
1256     info->name = strdup_safe(file->name);
1257
1258     stmt = file->defs;
1259     for (stmt = file->defs; stmt; stmt = stmt->next) {
1260         switch (stmt->type) {
1261         case STMT_INCLUDE:
1262             ok = HandleIncludeSymbols(info, (IncludeStmt *) stmt);
1263             break;
1264         case STMT_SYMBOLS:
1265             ok = HandleSymbolsDef(info, (SymbolsDef *) stmt);
1266             break;
1267         case STMT_VAR:
1268             ok = HandleSymbolsVar(info, (VarDef *) stmt);
1269             break;
1270         case STMT_VMOD:
1271             ok = HandleVModDef((VModDef *) stmt, info->keymap, merge,
1272                                &info->vmods);
1273             break;
1274         case STMT_MODMAP:
1275             ok = HandleModMapDef(info, (ModMapDef *) stmt);
1276             break;
1277         default:
1278             log_err(info->keymap->ctx,
1279                     "Interpretation files may not include other types; "
1280                     "Ignoring %s\n", stmt_type_to_string(stmt->type));
1281             ok = false;
1282             break;
1283         }
1284
1285         if (!ok)
1286             info->errorCount++;
1287
1288         if (info->errorCount > 10) {
1289             log_err(info->keymap->ctx, "Abandoning symbols file \"%s\"\n",
1290                     file->topName);
1291             break;
1292         }
1293     }
1294 }
1295
1296 /**
1297  * Given a keysym @sym, return a key which generates it, or NULL.
1298  * This is used for example in a modifier map definition, such as:
1299  *      modifier_map Lock           { Caps_Lock };
1300  * where we want to add the Lock modifier to the modmap of the key
1301  * which matches the keysym Caps_Lock.
1302  * Since there can be many keys which generates the keysym, the key
1303  * is chosen first by lowest group in which the keysym appears, than
1304  * by lowest level and than by lowest key code.
1305  */
1306 static struct xkb_key *
1307 FindKeyForSymbol(struct xkb_keymap *keymap, xkb_keysym_t sym)
1308 {
1309     struct xkb_key *key, *ret = NULL;
1310     xkb_group_index_t group, min_group = UINT32_MAX;
1311     xkb_level_index_t level, min_level = UINT16_MAX;
1312
1313     xkb_foreach_key(key, keymap) {
1314         for (group = 0; group < key->num_groups; group++) {
1315             for (level = 0; level < XkbKeyGroupWidth(keymap, key, group);
1316                  level++) {
1317                 if (XkbKeyNumSyms(key, group, level) != 1 ||
1318                     (XkbKeySymEntry(key, group, level))[0] != sym)
1319                     continue;
1320
1321                 /*
1322                  * If the keysym was found in a group or level > 0, we must
1323                  * keep looking since we might find a key in which the keysym
1324                  * is in a lower group or level.
1325                  */
1326                 if (group < min_group ||
1327                     (group == min_group && level < min_level)) {
1328                     ret = key;
1329                     if (group == 0 && level == 0) {
1330                         return ret;
1331                     }
1332                     else {
1333                         min_group = group;
1334                         min_level = level;
1335                     }
1336                 }
1337             }
1338         }
1339     }
1340
1341     return ret;
1342 }
1343
1344 static bool
1345 FindNamedType(struct xkb_keymap *keymap, xkb_atom_t name, unsigned *type_rtrn)
1346 {
1347     unsigned int i;
1348
1349     for (i = 0; i < keymap->num_types; i++) {
1350         if (keymap->types[i].name == name) {
1351             *type_rtrn = i;
1352             return true;
1353         }
1354     }
1355
1356     return false;
1357 }
1358
1359 /**
1360  * Assign a type to the given sym and return the Atom for the type assigned.
1361  *
1362  * Simple recipe:
1363  * - ONE_LEVEL for width 0/1
1364  * - ALPHABETIC for 2 shift levels, with lower/upercase
1365  * - KEYPAD for keypad keys.
1366  * - TWO_LEVEL for other 2 shift level keys.
1367  * and the same for four level keys.
1368  *
1369  * @param width Number of sysms in syms.
1370  * @param syms The keysyms for the given key (must be size width).
1371  * @param typeNameRtrn Set to the Atom of the type name.
1372  *
1373  * @returns true if a type could be found, false otherwise.
1374  *
1375  * FIXME: I need to take the KeyInfo so I can look at symsMapIndex and
1376  *        all that fun stuff rather than just assuming there's always one
1377  *        symbol per level.
1378  */
1379 static bool
1380 FindAutomaticType(struct xkb_keymap *keymap, xkb_level_index_t width,
1381                   const xkb_keysym_t *syms, xkb_atom_t *typeNameRtrn,
1382                   bool *autoType)
1383 {
1384     *autoType = false;
1385     if ((width == 1) || (width == 0)) {
1386         *typeNameRtrn = xkb_atom_intern(keymap->ctx, "ONE_LEVEL");
1387         *autoType = true;
1388     }
1389     else if (width == 2) {
1390         if (syms && xkb_keysym_is_lower(syms[0]) &&
1391             xkb_keysym_is_upper(syms[1])) {
1392             *typeNameRtrn = xkb_atom_intern(keymap->ctx, "ALPHABETIC");
1393         }
1394         else if (syms && (xkb_keysym_is_keypad(syms[0]) ||
1395                           xkb_keysym_is_keypad(syms[1]))) {
1396             *typeNameRtrn = xkb_atom_intern(keymap->ctx, "KEYPAD");
1397             *autoType = true;
1398         }
1399         else {
1400             *typeNameRtrn = xkb_atom_intern(keymap->ctx, "TWO_LEVEL");
1401             *autoType = true;
1402         }
1403     }
1404     else if (width <= 4) {
1405         if (syms && xkb_keysym_is_lower(syms[0]) &&
1406             xkb_keysym_is_upper(syms[1]))
1407             if (xkb_keysym_is_lower(syms[2]) && xkb_keysym_is_upper(syms[3]))
1408                 *typeNameRtrn =
1409                     xkb_atom_intern(keymap->ctx, "FOUR_LEVEL_ALPHABETIC");
1410             else
1411                 *typeNameRtrn = xkb_atom_intern(keymap->ctx,
1412                                                 "FOUR_LEVEL_SEMIALPHABETIC");
1413
1414         else if (syms && (xkb_keysym_is_keypad(syms[0]) ||
1415                           xkb_keysym_is_keypad(syms[1])))
1416             *typeNameRtrn = xkb_atom_intern(keymap->ctx, "FOUR_LEVEL_KEYPAD");
1417         else
1418             *typeNameRtrn = xkb_atom_intern(keymap->ctx, "FOUR_LEVEL");
1419         /* XXX: why not set autoType here? */
1420     }
1421     return width <= 4;
1422 }
1423
1424 /**
1425  * Ensure the given KeyInfo is in a coherent state, i.e. no gaps between the
1426  * groups, and reduce to one group if all groups are identical anyway.
1427  */
1428 static void
1429 PrepareKeyDef(KeyInfo *keyi)
1430 {
1431     xkb_group_index_t i, lastGroup;
1432     const GroupInfo *group0;
1433     bool identical;
1434
1435     /* get highest group number */
1436     for (i = XKB_NUM_GROUPS - 1; i > 0; i--)
1437         if (keyi->groups[i].defined)
1438             break;
1439     lastGroup = i;
1440
1441     if (lastGroup == 0)
1442         return;
1443
1444     group0 = &keyi->groups[0];
1445
1446     /* If there are empty groups between non-empty ones fill them with data */
1447     /* from the first group. */
1448     /* We can make a wrong assumption here. But leaving gaps is worse. */
1449     for (i = lastGroup; i > 0; i--) {
1450         GroupInfo *groupi = &keyi->groups[i];
1451
1452         if (groupi->defined)
1453             continue;
1454
1455         groupi->type = group0->type;
1456         darray_copy(groupi->syms, group0->syms);
1457         darray_copy(groupi->levels, group0->levels);
1458         groupi->defined = group0->defined;
1459     }
1460
1461     /* If all groups are completely identical remove them all */
1462     /* exept the first one. */
1463     /* XXX: This code needs testing... or removal. */
1464     identical = true;
1465     for (i = lastGroup; i > 0; i--) {
1466         GroupInfo *groupi = &keyi->groups[i];
1467
1468         if (groupi->type != group0->type) {
1469             identical = false;
1470             break;
1471         }
1472         if (!darray_same(groupi->levels, group0->levels) &&
1473             (darray_empty(groupi->levels) || darray_empty(group0->levels) ||
1474              darray_size(groupi->levels) != darray_size(group0->levels) ||
1475              memcmp(darray_mem(groupi->levels, 0),
1476                     darray_mem(group0->levels, 0),
1477                     darray_size(group0->levels) * sizeof(LevelInfo)))) {
1478             identical = false;
1479             break;
1480         }
1481         if (!darray_same(groupi->syms, group0->syms) &&
1482             (darray_empty(groupi->syms) || darray_empty(group0->syms) ||
1483              darray_size(groupi->syms) != darray_size(group0->syms) ||
1484              memcmp(darray_mem(groupi->syms, 0),
1485                     darray_mem(group0->syms, 0),
1486                     darray_size(group0->syms) * sizeof(xkb_keysym_t)))) {
1487             identical = false;
1488             break;
1489         }
1490     }
1491
1492     if (identical)
1493         for (i = lastGroup; i > 0; i--)
1494             ClearGroupInfo(&keyi->groups[i]);
1495 }
1496
1497 static bool
1498 CopySymbolsDef(SymbolsInfo *info, KeyInfo *keyi)
1499 {
1500     struct xkb_keymap *keymap = info->keymap;
1501     struct xkb_key *key;
1502     unsigned int sizeSyms = 0;
1503     xkb_group_index_t i, nGroups;
1504     xkb_level_index_t width, tmp;
1505     struct xkb_key_type * type;
1506     bool haveActions;
1507     unsigned int symIndex = 0;
1508
1509     /*
1510      * The name is guaranteed to be real and not an alias (see
1511      * AddKeySymbols), so 'false' is safe here.
1512      */
1513     key = FindNamedKey(keymap, keyi->name, false);
1514     if (!key) {
1515         log_vrb(info->keymap->ctx, 5,
1516                 "Key %s not found in keycodes; Symbols ignored\n",
1517                 LongKeyNameText(keyi->name));
1518         return false;
1519     }
1520
1521     haveActions = false;
1522     width = 0;
1523     for (i = nGroups = 0; i < XKB_NUM_GROUPS; i++) {
1524         GroupInfo *groupi = &keyi->groups[i];
1525         bool autoType = false;
1526
1527         if (i + 1 > nGroups && groupi->defined)
1528             nGroups = i + 1;
1529
1530         if (!haveActions) {
1531             LevelInfo *leveli;
1532             darray_foreach(leveli, groupi->levels) {
1533                 if (leveli->act.type != ACTION_TYPE_NONE) {
1534                     haveActions = true;
1535                     break;
1536                 }
1537             }
1538         }
1539
1540         /* Assign the type to the key, if it is missing. */
1541         if (groupi->type == XKB_ATOM_NONE) {
1542             if (keyi->dfltType != XKB_ATOM_NONE)
1543                 groupi->type = keyi->dfltType;
1544             else if (FindAutomaticType(keymap, darray_size(groupi->levels),
1545                                        darray_mem(groupi->syms, 0),
1546                                        &groupi->type, &autoType)) { }
1547             else
1548                 log_vrb(info->keymap->ctx, 5,
1549                         "No automatic type for %d levels; "
1550                         "Using %s for the %s key\n",
1551                         darray_size(groupi->levels),
1552                         xkb_atom_text(keymap->ctx, groupi->type),
1553                         LongKeyNameText(keyi->name));
1554         }
1555
1556         if (FindNamedType(keymap, groupi->type, &key->kt_index[i])) {
1557             if (!autoType || darray_size(groupi->levels) > 2)
1558                 key->explicit_groups |= (1 << i);
1559         }
1560         else {
1561             log_vrb(info->keymap->ctx, 3,
1562                     "Type \"%s\" is not defined; "
1563                     "Using default type for the %s key\n",
1564                     xkb_atom_text(keymap->ctx, groupi->type),
1565                     LongKeyNameText(keyi->name));
1566             /*
1567              * Index 0 is guaranteed to contain something, usually
1568              * ONE_LEVEL or at least some default one-level type.
1569              */
1570             key->kt_index[i] = 0;
1571         }
1572
1573         /* if the type specifies fewer levels than the key has, shrink the key */
1574         type = &keymap->types[key->kt_index[i]];
1575         if (type->num_levels < darray_size(groupi->levels)) {
1576             log_vrb(info->keymap->ctx, 1,
1577                     "Type \"%s\" has %d levels, but %s has %d levels; "
1578                     "Ignoring extra symbols\n",
1579                     xkb_atom_text(keymap->ctx, type->name),
1580                     type->num_levels,
1581                     LongKeyNameText(keyi->name),
1582                     darray_size(groupi->levels));
1583             darray_resize(groupi->levels, type->num_levels);
1584         }
1585
1586         width = MAX(width, type->num_levels);
1587         sizeSyms += darray_size(groupi->syms);
1588     }
1589
1590     key->syms = calloc(sizeSyms, sizeof(*key->syms));
1591     key->num_groups = nGroups;
1592     key->width = width;
1593     key->sym_index = calloc(nGroups * width, sizeof(*key->sym_index));
1594     key->num_syms = calloc(nGroups * width, sizeof(*key->num_syms));
1595
1596     if (haveActions) {
1597         key->actions = calloc(nGroups * width, sizeof(*key->actions));
1598         key->explicit |= EXPLICIT_INTERP;
1599     }
1600
1601     key->out_of_range_group_number = keyi->out_of_range_group_number;
1602     key->out_of_range_group_action = keyi->out_of_range_group_action;
1603
1604     for (i = 0; i < nGroups; i++) {
1605         GroupInfo *groupi = &keyi->groups[i];
1606
1607         if (!darray_empty(groupi->syms)) {
1608             /* fill key to "width" symbols*/
1609             for (tmp = 0; tmp < width; tmp++) {
1610                 LevelInfo *leveli = NULL;
1611
1612                 if (tmp < darray_size(groupi->levels))
1613                     leveli = &darray_item(groupi->levels, tmp);
1614
1615                 if (leveli && leveli->num_syms != 0) {
1616                     memcpy(&key->syms[symIndex],
1617                            &darray_item(groupi->syms, leveli->sym_index),
1618                            leveli->num_syms * sizeof(*key->syms));
1619                     key->sym_index[(i * width) + tmp] = symIndex;
1620                     key->num_syms[(i * width) + tmp] = leveli->num_syms;
1621                     symIndex += key->num_syms[(i * width) + tmp];
1622                 }
1623                 else {
1624                     key->sym_index[(i * width) + tmp] = 0;
1625                     key->num_syms[(i * width) + tmp] = 0;
1626                 }
1627
1628                 if (key->actions && leveli &&
1629                     leveli->act.type != ACTION_TYPE_NONE)
1630                     key->actions[tmp] = leveli->act;
1631             }
1632         }
1633     }
1634
1635     if (keyi->defined & KEY_FIELD_VMODMAP) {
1636         key->vmodmap = keyi->vmodmap;
1637         key->explicit |= EXPLICIT_VMODMAP;
1638     }
1639
1640     if (keyi->repeat != KEY_REPEAT_UNDEFINED) {
1641         key->repeats = (keyi->repeat == KEY_REPEAT_YES);
1642         key->explicit |= EXPLICIT_REPEAT;
1643     }
1644
1645     return true;
1646 }
1647
1648 static bool
1649 CopyModMapDef(SymbolsInfo *info, ModMapEntry *entry)
1650 {
1651     struct xkb_key *key;
1652     struct xkb_keymap *keymap = info->keymap;
1653
1654     if (!entry->haveSymbol) {
1655         key = FindNamedKey(keymap, entry->u.keyName, true);
1656         if (!key) {
1657             log_vrb(info->keymap->ctx, 5,
1658                     "Key %s not found in keycodes; "
1659                     "Modifier map entry for %s not updated\n",
1660                     LongKeyNameText(entry->u.keyName),
1661                     ModIndexText(entry->modifier));
1662             return false;
1663         }
1664     }
1665     else {
1666         key = FindKeyForSymbol(keymap, entry->u.keySym);
1667         if (!key) {
1668             log_vrb(info->keymap->ctx, 5,
1669                     "Key \"%s\" not found in symbol map; "
1670                     "Modifier map entry for %s not updated\n",
1671                     KeysymText(entry->u.keySym),
1672                     ModIndexText(entry->modifier));
1673             return false;
1674         }
1675     }
1676
1677     key->modmap |= (1 << entry->modifier);
1678     return true;
1679 }
1680
1681 static bool
1682 CopySymbolsToKeymap(struct xkb_keymap *keymap, SymbolsInfo *info)
1683 {
1684     KeyInfo *keyi;
1685     ModMapEntry *mm;
1686     xkb_group_index_t i;
1687     struct xkb_key *key;
1688
1689     keymap->symbols_section_name = strdup_safe(info->name);
1690
1691     for (i = 0; i < XKB_NUM_GROUPS; i++)
1692         if (info->groupNames[i] != XKB_ATOM_NONE)
1693             keymap->group_names[i] = info->groupNames[i];
1694
1695     darray_foreach(keyi, info->keys) {
1696         PrepareKeyDef(keyi);
1697         if (!CopySymbolsDef(info, keyi))
1698             info->errorCount++;
1699     }
1700
1701     if (xkb_get_log_verbosity(keymap->ctx) > 3) {
1702         xkb_foreach_key(key, keymap) {
1703             if (key->name[0] == '\0')
1704                 continue;
1705
1706             if (key->num_groups < 1)
1707                 log_info(keymap->ctx,
1708                          "No symbols defined for %s\n",
1709                          KeyNameText(key->name));
1710         }
1711     }
1712
1713     darray_foreach(mm, info->modMaps)
1714         if (!CopyModMapDef(info, mm))
1715             info->errorCount++;
1716
1717     /* XXX: If we don't ignore errorCount, things break. */
1718     return true;
1719 }
1720
1721 bool
1722 CompileSymbols(XkbFile *file, struct xkb_keymap *keymap,
1723                enum merge_mode merge)
1724 {
1725     SymbolsInfo info;
1726     ActionsInfo *actions;
1727
1728     actions = NewActionsInfo();
1729     if (!actions)
1730         return false;
1731
1732     InitSymbolsInfo(&info, keymap, file->id, actions);
1733     info.dflt.merge = merge;
1734
1735     HandleSymbolsFile(&info, file, merge);
1736
1737     if (darray_empty(info.keys))
1738         goto err_info;
1739
1740     if (info.errorCount != 0)
1741         goto err_info;
1742
1743     if (!CopySymbolsToKeymap(keymap, &info))
1744         goto err_info;
1745
1746     ClearSymbolsInfo(&info);
1747     FreeActionsInfo(actions);
1748     return true;
1749
1750 err_info:
1751     FreeActionsInfo(actions);
1752     ClearSymbolsInfo(&info);
1753     return false;
1754 }