Use our types instead of int/uint32_t in a few places
[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 #include "keysym.h"
62
63 enum key_repeat {
64     KEY_REPEAT_UNDEFINED = 0,
65     KEY_REPEAT_YES = 1,
66     KEY_REPEAT_NO = 2,
67 };
68
69 enum group_field {
70     GROUP_FIELD_SYMS = (1 << 0),
71     GROUP_FIELD_ACTS = (1 << 1),
72     GROUP_FIELD_TYPE = (1 << 2),
73 };
74
75 enum key_field {
76     KEY_FIELD_REPEAT    = (1 << 0),
77     KEY_FIELD_TYPE_DFLT = (1 << 1),
78     KEY_FIELD_GROUPINFO = (1 << 2),
79     KEY_FIELD_VMODMAP   = (1 << 3),
80 };
81
82 typedef struct {
83     enum group_field defined;
84     darray(struct xkb_level) levels;
85     xkb_atom_t type;
86 } GroupInfo;
87
88 typedef struct _KeyInfo {
89     enum key_field defined;
90     unsigned file_id;
91     enum merge_mode merge;
92
93     xkb_atom_t name;
94
95     darray(GroupInfo) groups;
96
97     enum key_repeat repeat;
98     xkb_mod_mask_t vmodmap;
99     xkb_atom_t dfltType;
100
101     enum xkb_range_exceed_type out_of_range_group_action;
102     xkb_layout_index_t out_of_range_group_number;
103 } KeyInfo;
104
105 static void
106 ClearLevelInfo(struct xkb_level *leveli)
107 {
108     if (leveli->num_syms > 1)
109         free(leveli->u.syms);
110 }
111
112 static void
113 InitGroupInfo(GroupInfo *groupi)
114 {
115     memset(groupi, 0, sizeof(*groupi));
116 }
117
118 static void
119 ClearGroupInfo(GroupInfo *groupi)
120 {
121     struct xkb_level *leveli;
122     darray_foreach(leveli, groupi->levels)
123         ClearLevelInfo(leveli);
124     darray_free(groupi->levels);
125 }
126
127 static void
128 CopyGroupInfo(GroupInfo *to, const GroupInfo *from)
129 {
130     xkb_level_index_t j;
131     to->defined = from->defined;
132     to->type = from->type;
133     darray_init(to->levels);
134     darray_copy(to->levels, from->levels);
135     for (j = 0; j < darray_size(to->levels); j++)
136         if (darray_item(from->levels, j).num_syms > 1)
137             darray_item(to->levels, j).u.syms =
138                 memdup(darray_item(from->levels, j).u.syms,
139                        darray_item(from->levels, j).num_syms,
140                        sizeof(xkb_keysym_t));
141 }
142
143 static void
144 InitKeyInfo(struct xkb_context *ctx, KeyInfo *keyi, unsigned file_id)
145 {
146     memset(keyi, 0, sizeof(*keyi));
147     keyi->file_id = file_id;
148     keyi->merge = MERGE_OVERRIDE;
149     keyi->name = xkb_atom_intern(ctx, "*");
150     keyi->out_of_range_group_action = RANGE_WRAP;
151 }
152
153 static void
154 ClearKeyInfo(KeyInfo *keyi)
155 {
156     GroupInfo *groupi;
157     darray_foreach(groupi, keyi->groups)
158         ClearGroupInfo(groupi);
159     darray_free(keyi->groups);
160 }
161
162 /***====================================================================***/
163
164 typedef struct _ModMapEntry {
165     enum merge_mode merge;
166     bool haveSymbol;
167     xkb_mod_index_t modifier;
168     union {
169         xkb_atom_t keyName;
170         xkb_keysym_t keySym;
171     } u;
172 } ModMapEntry;
173
174 typedef struct _SymbolsInfo {
175     char *name;         /* e.g. pc+us+inet(evdev) */
176     int errorCount;
177     unsigned file_id;
178     enum merge_mode merge;
179     xkb_layout_index_t explicit_group;
180     darray(KeyInfo) keys;
181     KeyInfo dflt;
182     VModInfo vmods;
183     ActionsInfo *actions;
184     darray_xkb_atom_t group_names;
185     darray(ModMapEntry) modMaps;
186
187     struct xkb_keymap *keymap;
188 } SymbolsInfo;
189
190 static void
191 InitSymbolsInfo(SymbolsInfo *info, struct xkb_keymap *keymap,
192                 unsigned file_id, ActionsInfo *actions)
193 {
194     memset(info, 0, sizeof(*info));
195     info->keymap = keymap;
196     info->file_id = file_id;
197     info->merge = MERGE_OVERRIDE;
198     InitKeyInfo(keymap->ctx, &info->dflt, file_id);
199     InitVModInfo(&info->vmods, keymap);
200     info->actions = actions;
201     info->explicit_group = XKB_LAYOUT_INVALID;
202 }
203
204 static void
205 ClearSymbolsInfo(SymbolsInfo * info)
206 {
207     KeyInfo *keyi;
208     free(info->name);
209     darray_foreach(keyi, info->keys)
210         ClearKeyInfo(keyi);
211     darray_free(info->keys);
212     darray_free(info->group_names);
213     darray_free(info->modMaps);
214     ClearKeyInfo(&info->dflt);
215 }
216
217 static const char *
218 KeyInfoText(SymbolsInfo *info, KeyInfo *keyi)
219 {
220     return KeyNameText(info->keymap->ctx, keyi->name);
221 }
222
223 static bool
224 MergeGroups(SymbolsInfo *info, GroupInfo *into, GroupInfo *from, bool clobber,
225             bool report, xkb_layout_index_t group, xkb_atom_t key_name)
226 {
227     xkb_level_index_t i, levels_in_both;
228     struct xkb_context *ctx = info->keymap->ctx;
229
230     /* First find the type of the merged group. */
231     if (into->type != from->type) {
232         if (from->type == XKB_ATOM_NONE) {
233         }
234         else if (into->type == XKB_ATOM_NONE) {
235             into->type = from->type;
236         }
237         else {
238             xkb_atom_t use = (clobber ? from->type : into->type);
239             xkb_atom_t ignore = (clobber ? into->type : from->type);
240
241             if (report)
242                 log_warn(info->keymap->ctx,
243                          "Multiple definitions for group %d type of key %s; "
244                          "Using %s, ignoring %s\n",
245                          group + 1, KeyNameText(ctx, key_name),
246                          xkb_atom_text(ctx, use), xkb_atom_text(ctx, ignore));
247
248             into->type = use;
249         }
250     }
251     into->defined |= (from->defined & GROUP_FIELD_TYPE);
252
253     /* Now look at the levels. */
254
255     if (darray_empty(from->levels)) {
256         InitGroupInfo(from);
257         return true;
258     }
259
260     if (darray_empty(into->levels)) {
261         from->type = into->type;
262         *into = *from;
263         InitGroupInfo(from);
264         return true;
265     }
266
267     /* Merge the actions and syms. */
268     levels_in_both = MIN(darray_size(into->levels), darray_size(from->levels));
269     for (i = 0; i < levels_in_both; i++) {
270         struct xkb_level *intoLevel = &darray_item(into->levels, i);
271         struct xkb_level *fromLevel = &darray_item(from->levels, i);
272
273         if (fromLevel->action.type == ACTION_TYPE_NONE) {
274         }
275         else if (intoLevel->action.type == ACTION_TYPE_NONE) {
276             intoLevel->action = fromLevel->action;
277         }
278         else {
279             union xkb_action *use, *ignore;
280             use = (clobber ? &fromLevel->action : &intoLevel->action);
281             ignore = (clobber ? &intoLevel->action : &fromLevel->action);
282
283             if (report)
284                 log_warn(ctx,
285                          "Multiple actions for level %d/group %u on key %s; "
286                          "Using %s, ignoring %s\n",
287                          i + 1, group + 1, KeyNameText(ctx, key_name),
288                          ActionTypeText(use->type),
289                          ActionTypeText(ignore->type));
290
291             intoLevel->action = *use;
292         }
293
294         if (fromLevel->num_syms == 0) {
295         }
296         else if (intoLevel->num_syms == 0) {
297             intoLevel->num_syms = fromLevel->num_syms;
298             if (fromLevel->num_syms > 1)
299                 intoLevel->u.syms = fromLevel->u.syms;
300             else
301                 intoLevel->u.sym = fromLevel->u.sym;
302             fromLevel->num_syms = 0;
303         }
304         else {
305             if (report)
306                 log_warn(ctx,
307                          "Multiple symbols for level %d/group %u on key %s; "
308                          "Using %s, ignoring %s\n",
309                          i + 1, group + 1, KeyNameText(ctx, key_name),
310                          (clobber ? "from" : "to"),
311                          (clobber ? "to" : "from"));
312
313             if (clobber) {
314                 ClearLevelInfo(intoLevel);
315                 intoLevel->num_syms = fromLevel->num_syms;
316                 if (fromLevel->num_syms > 1)
317                     intoLevel->u.syms = fromLevel->u.syms;
318                 else
319                     intoLevel->u.sym = fromLevel->u.sym;
320                 fromLevel->num_syms = 0;
321             }
322         }
323     }
324     /* If @from has extra levels, get them as well. */
325     for (i = levels_in_both; i < darray_size(from->levels); i++) {
326         darray_append(into->levels, darray_item(from->levels, i));
327         darray_item(from->levels, i).num_syms = 0;
328     }
329     into->defined |= (from->defined & GROUP_FIELD_ACTS);
330     into->defined |= (from->defined & GROUP_FIELD_SYMS);
331
332     return true;
333 }
334
335 static bool
336 UseNewKeyField(enum key_field field, enum key_field old, enum key_field new,
337                bool clobber, bool report, enum key_field *collide)
338 {
339     if (!(old & field))
340         return (new & field);
341
342     if (new & field) {
343         if (report)
344             *collide |= field;
345
346         if (clobber)
347             return true;
348     }
349
350     return false;
351 }
352
353 static bool
354 MergeKeys(SymbolsInfo *info, KeyInfo *into, KeyInfo *from)
355 {
356     xkb_layout_index_t i;
357     xkb_layout_index_t groups_in_both;
358     enum key_field collide = 0;
359     bool clobber, report;
360     int verbosity = xkb_context_get_log_verbosity(info->keymap->ctx);
361
362     if (from->merge == MERGE_REPLACE) {
363         ClearKeyInfo(into);
364         *into = *from;
365         InitKeyInfo(info->keymap->ctx, from, info->file_id);
366         return true;
367     }
368
369     clobber = (from->merge != MERGE_AUGMENT);
370     report = (verbosity > 9 ||
371               (into->file_id == from->file_id && verbosity > 0));
372
373     groups_in_both = MIN(darray_size(into->groups),
374                          darray_size(from->groups));
375     for (i = 0; i < groups_in_both; i++)
376         MergeGroups(info,
377                     &darray_item(into->groups, i),
378                     &darray_item(from->groups, i),
379                     clobber, report, i, into->name);
380     /* If @from has extra groups, just move them to @into. */
381     for (i = groups_in_both; i < darray_size(from->groups); i++) {
382         darray_append(into->groups, darray_item(from->groups, i));
383         InitGroupInfo(&darray_item(from->groups, i));
384     }
385
386     if (UseNewKeyField(KEY_FIELD_VMODMAP, into->defined, from->defined,
387                        clobber, report, &collide)) {
388         into->vmodmap = from->vmodmap;
389         into->defined |= KEY_FIELD_VMODMAP;
390     }
391     if (UseNewKeyField(KEY_FIELD_REPEAT, into->defined, from->defined,
392                        clobber, report, &collide)) {
393         into->repeat = from->repeat;
394         into->defined |= KEY_FIELD_REPEAT;
395     }
396     if (UseNewKeyField(KEY_FIELD_TYPE_DFLT, into->defined, from->defined,
397                        clobber, report, &collide)) {
398         into->dfltType = from->dfltType;
399         into->defined |= KEY_FIELD_TYPE_DFLT;
400     }
401     if (UseNewKeyField(KEY_FIELD_GROUPINFO, into->defined, from->defined,
402                        clobber, report, &collide)) {
403         into->out_of_range_group_action = from->out_of_range_group_action;
404         into->out_of_range_group_number = from->out_of_range_group_number;
405         into->defined |= KEY_FIELD_GROUPINFO;
406     }
407
408     if (collide)
409         log_warn(info->keymap->ctx,
410                  "Symbol map for key %s redefined; "
411                  "Using %s definition for conflicting fields\n",
412                  KeyNameText(info->keymap->ctx, into->name),
413                  (clobber ? "first" : "last"));
414
415     ClearKeyInfo(from);
416     InitKeyInfo(info->keymap->ctx, from, info->file_id);
417     return true;
418 }
419
420 static bool
421 AddKeySymbols(SymbolsInfo *info, KeyInfo *keyi)
422 {
423     xkb_atom_t real_name;
424     KeyInfo *iter;
425
426     /*
427      * Don't keep aliases in the keys array; this guarantees that
428      * searching for keys to merge with by straight comparison (see the
429      * following loop) is enough, and we won't get multiple KeyInfo's
430      * for the same key because of aliases.
431      */
432     if (FindKeyNameForAlias(info->keymap, keyi->name, &real_name))
433         keyi->name = real_name;
434
435     darray_foreach(iter, info->keys)
436         if (iter->name == keyi->name)
437             return MergeKeys(info, iter, keyi);
438
439     darray_append(info->keys, *keyi);
440     InitKeyInfo(info->keymap->ctx, keyi, info->file_id);
441     return true;
442 }
443
444 static bool
445 AddModMapEntry(SymbolsInfo * info, ModMapEntry * new)
446 {
447     ModMapEntry *mm;
448     bool clobber;
449
450     clobber = (new->merge != MERGE_AUGMENT);
451     darray_foreach(mm, info->modMaps) {
452         if (new->haveSymbol && mm->haveSymbol
453             && (new->u.keySym == mm->u.keySym)) {
454             xkb_mod_index_t use, ignore;
455             if (mm->modifier != new->modifier) {
456                 if (clobber) {
457                     use = new->modifier;
458                     ignore = mm->modifier;
459                 }
460                 else {
461                     use = mm->modifier;
462                     ignore = new->modifier;
463                 }
464                 log_err(info->keymap->ctx,
465                         "%s added to symbol map for multiple modifiers; "
466                         "Using %s, ignoring %s.\n",
467                         KeysymText(new->u.keySym), ModIndexText(use),
468                         ModIndexText(ignore));
469                 mm->modifier = use;
470             }
471             return true;
472         }
473         if ((!new->haveSymbol) && (!mm->haveSymbol) &&
474             (new->u.keyName == mm->u.keyName)) {
475             xkb_mod_index_t use, ignore;
476             if (mm->modifier != new->modifier) {
477                 if (clobber) {
478                     use = new->modifier;
479                     ignore = mm->modifier;
480                 }
481                 else {
482                     use = mm->modifier;
483                     ignore = new->modifier;
484                 }
485                 log_err(info->keymap->ctx,
486                         "Key %s added to map for multiple modifiers; "
487                         "Using %s, ignoring %s.\n",
488                         KeyNameText(info->keymap->ctx, new->u.keyName),
489                         ModIndexText(use), ModIndexText(ignore));
490                 mm->modifier = use;
491             }
492             return true;
493         }
494     }
495
496     darray_append(info->modMaps, *new);
497     return true;
498 }
499
500 /***====================================================================***/
501
502 static void
503 MergeIncludedSymbols(SymbolsInfo *into, SymbolsInfo *from,
504                      enum merge_mode merge)
505 {
506     unsigned int i;
507     KeyInfo *keyi;
508     ModMapEntry *mm;
509     xkb_atom_t *group_name;
510     xkb_layout_index_t group_names_in_both;
511
512     if (from->errorCount > 0) {
513         into->errorCount += from->errorCount;
514         return;
515     }
516
517     if (into->name == NULL) {
518         into->name = from->name;
519         from->name = NULL;
520     }
521
522     group_names_in_both = MIN(darray_size(into->group_names),
523                               darray_size(from->group_names));
524     for (i = 0; i < group_names_in_both; i++) {
525         if (!darray_item(from->group_names, i))
526             continue;
527
528         if (merge == MERGE_AUGMENT && darray_item(into->group_names, i))
529             continue;
530
531         darray_item(into->group_names, i) = darray_item(from->group_names, i);
532     }
533     /* If @from has more, get them as well. */
534     darray_foreach_from(group_name, from->group_names, group_names_in_both)
535         darray_append(into->group_names, *group_name);
536
537     darray_foreach(keyi, from->keys) {
538         merge = (merge == MERGE_DEFAULT ? keyi->merge : merge);
539         if (!AddKeySymbols(into, keyi))
540             into->errorCount++;
541     }
542
543     darray_foreach(mm, from->modMaps) {
544         mm->merge = (merge == MERGE_DEFAULT ? mm->merge : merge);
545         if (!AddModMapEntry(into, mm))
546             into->errorCount++;
547     }
548 }
549
550 static void
551 HandleSymbolsFile(SymbolsInfo *info, XkbFile *file, enum merge_mode merge);
552
553 static bool
554 HandleIncludeSymbols(SymbolsInfo *info, IncludeStmt *stmt)
555 {
556     enum merge_mode merge = MERGE_DEFAULT;
557     XkbFile *rtrn;
558     SymbolsInfo included, next_incl;
559
560     InitSymbolsInfo(&included, info->keymap, info->file_id, info->actions);
561     if (stmt->stmt) {
562         free(included.name);
563         included.name = stmt->stmt;
564         stmt->stmt = NULL;
565     }
566
567     for (; stmt; stmt = stmt->next_incl) {
568         if (!ProcessIncludeFile(info->keymap->ctx, stmt, FILE_TYPE_SYMBOLS,
569                                 &rtrn, &merge)) {
570             info->errorCount += 10;
571             ClearSymbolsInfo(&included);
572             return false;
573         }
574
575         InitSymbolsInfo(&next_incl, info->keymap, rtrn->id, info->actions);
576         next_incl.merge = next_incl.dflt.merge = MERGE_OVERRIDE;
577         if (stmt->modifier) {
578             next_incl.explicit_group = atoi(stmt->modifier) - 1;
579             if (next_incl.explicit_group >= XKB_NUM_GROUPS) {
580                 log_err(info->keymap->ctx,
581                         "Cannot set explicit group to %d - must be between 1..%d; "
582                         "Ignoring group number\n",
583                         next_incl.explicit_group + 1, XKB_NUM_GROUPS);
584                 next_incl.explicit_group = info->explicit_group;
585             }
586         }
587         else {
588             next_incl.explicit_group = info->explicit_group;
589         }
590
591         HandleSymbolsFile(&next_incl, rtrn, MERGE_OVERRIDE);
592
593         MergeIncludedSymbols(&included, &next_incl, merge);
594
595         ClearSymbolsInfo(&next_incl);
596         FreeXkbFile(rtrn);
597     }
598
599     MergeIncludedSymbols(info, &included, merge);
600     ClearSymbolsInfo(&included);
601
602     return (info->errorCount == 0);
603 }
604
605 #define SYMBOLS 1
606 #define ACTIONS 2
607
608 static bool
609 GetGroupIndex(SymbolsInfo *info, KeyInfo *keyi, ExprDef *arrayNdx,
610               unsigned what, xkb_layout_index_t *ndx_rtrn)
611 {
612     const char *name = (what == SYMBOLS ? "symbols" : "actions");
613
614     if (arrayNdx == NULL) {
615         xkb_layout_index_t i;
616         GroupInfo *groupi;
617         enum group_field field = (what == SYMBOLS ?
618                                   GROUP_FIELD_SYMS : GROUP_FIELD_ACTS);
619
620         darray_enumerate(i, groupi, keyi->groups) {
621             if (!(groupi->defined & field)) {
622                 *ndx_rtrn = i;
623                 return true;
624             }
625         }
626
627         if (i >= XKB_NUM_GROUPS) {
628             log_err(info->keymap->ctx,
629                     "Too many groups of %s for key %s (max %u); "
630                     "Ignoring %s defined for extra groups\n",
631                     name, KeyInfoText(info, keyi), XKB_NUM_GROUPS + 1, name);
632             return false;
633         }
634
635         darray_resize0(keyi->groups, darray_size(keyi->groups) + 1);
636         *ndx_rtrn = darray_size(keyi->groups) - 1;
637         return true;
638     }
639
640     if (!ExprResolveGroup(info->keymap->ctx, arrayNdx, ndx_rtrn)) {
641         log_err(info->keymap->ctx,
642                 "Illegal group index for %s of key %s\n"
643                 "Definition with non-integer array index ignored\n",
644                 name, KeyInfoText(info, keyi));
645         return false;
646     }
647
648     (*ndx_rtrn)--;
649     if (*ndx_rtrn >= darray_size(keyi->groups))
650         darray_resize0(keyi->groups, *ndx_rtrn + 1);
651
652     return true;
653 }
654
655 bool
656 LookupKeysym(const char *str, xkb_keysym_t *sym_rtrn)
657 {
658     xkb_keysym_t sym;
659
660     if (!str || istreq(str, "any") || istreq(str, "nosymbol")) {
661         *sym_rtrn = XKB_KEY_NoSymbol;
662         return 1;
663     }
664
665     if (istreq(str, "none") || istreq(str, "voidsymbol")) {
666         *sym_rtrn = XKB_KEY_VoidSymbol;
667         return 1;
668     }
669
670     sym = xkb_keysym_from_name(str);
671     if (sym != XKB_KEY_NoSymbol) {
672         *sym_rtrn = sym;
673         return 1;
674     }
675
676     return 0;
677 }
678
679 static bool
680 AddSymbolsToKey(SymbolsInfo *info, KeyInfo *keyi, ExprDef *arrayNdx,
681                 ExprDef *value)
682 {
683     xkb_layout_index_t ndx;
684     GroupInfo *groupi;
685     xkb_level_index_t nLevels;
686     xkb_level_index_t i;
687     int j;
688
689     if (!GetGroupIndex(info, keyi, arrayNdx, SYMBOLS, &ndx))
690         return false;
691
692     groupi = &darray_item(keyi->groups, ndx);
693
694     if (value == NULL) {
695         groupi->defined |= GROUP_FIELD_SYMS;
696         return true;
697     }
698
699     if (value->op != EXPR_KEYSYM_LIST) {
700         log_err(info->keymap->ctx,
701                 "Expected a list of symbols, found %s; "
702                 "Ignoring symbols for group %u of %s\n",
703                 expr_op_type_to_string(value->op), ndx + 1,
704                 KeyInfoText(info, keyi));
705         return false;
706     }
707
708     if (groupi->defined & GROUP_FIELD_SYMS) {
709         log_err(info->keymap->ctx,
710                 "Symbols for key %s, group %u already defined; "
711                 "Ignoring duplicate definition\n",
712                 KeyInfoText(info, keyi), ndx + 1);
713         return false;
714     }
715
716     nLevels = darray_size(value->value.list.symsMapIndex);
717     if (darray_size(groupi->levels) < nLevels)
718         darray_resize0(groupi->levels, nLevels);
719
720     groupi->defined |= GROUP_FIELD_SYMS;
721
722     for (i = 0; i < nLevels; i++) {
723         unsigned int sym_index;
724         struct xkb_level *leveli = &darray_item(groupi->levels, i);
725
726         sym_index = darray_item(value->value.list.symsMapIndex, i);
727         leveli->num_syms = darray_item(value->value.list.symsNumEntries, i);
728         if (leveli->num_syms > 1)
729             leveli->u.syms = calloc(leveli->num_syms, sizeof(*leveli->u.syms));
730
731         for (j = 0; j < leveli->num_syms; j++) {
732             char *sym_name = darray_item(value->value.list.syms,
733                                          sym_index + j);
734             xkb_keysym_t keysym;
735
736             if (!LookupKeysym(sym_name, &keysym)) {
737                 const char *group_name = "unnamed";
738
739                 if (ndx < darray_size(info->group_names) &&
740                     darray_item(info->group_names, ndx))
741                     group_name = xkb_atom_text(info->keymap->ctx,
742                                                darray_item(info->group_names,
743                                                            ndx));
744
745                 log_warn(info->keymap->ctx,
746                          "Could not resolve keysym %s for key %s, group %u (%s), level %u\n",
747                          sym_name, KeyInfoText(info, keyi), ndx + 1,
748                          group_name, i);
749
750                 ClearLevelInfo(leveli);
751                 leveli->num_syms = 0;
752                 break;
753             }
754
755             if (leveli->num_syms == 1) {
756                 if (keysym == XKB_KEY_NoSymbol)
757                     leveli->num_syms = 0;
758                 else
759                     leveli->u.sym = keysym;
760             }
761             else if (leveli->num_syms > 1) {
762                 leveli->u.syms[j] = keysym;
763             }
764         }
765     }
766
767     return true;
768 }
769
770 static bool
771 AddActionsToKey(SymbolsInfo *info, KeyInfo *keyi, ExprDef *arrayNdx,
772                 ExprDef *value)
773 {
774     unsigned int i;
775     xkb_layout_index_t ndx;
776     GroupInfo *groupi;
777     unsigned int nActs;
778     ExprDef *act;
779     union xkb_action *toAct;
780
781     if (!GetGroupIndex(info, keyi, arrayNdx, ACTIONS, &ndx))
782         return false;
783
784     groupi = &darray_item(keyi->groups, ndx);
785
786     if (value == NULL) {
787         groupi->defined |= GROUP_FIELD_ACTS;
788         return true;
789     }
790
791     if (value->op != EXPR_ACTION_LIST) {
792         log_wsgo(info->keymap->ctx,
793                  "Bad expression type (%d) for action list value; "
794                  "Ignoring actions for group %u of %s\n",
795                  value->op, ndx, KeyInfoText(info, keyi));
796         return false;
797     }
798
799     if (groupi->defined & GROUP_FIELD_ACTS) {
800         log_wsgo(info->keymap->ctx,
801                  "Actions for key %s, group %u already defined\n",
802                  KeyInfoText(info, keyi), ndx);
803         return false;
804     }
805
806     nActs = 0;
807     for (act = value->value.child; act; act = (ExprDef *) act->common.next)
808         nActs++;
809
810     if (darray_size(groupi->levels) < nActs)
811         darray_resize0(groupi->levels, nActs);
812
813     groupi->defined |= GROUP_FIELD_ACTS;
814
815     act = value->value.child;
816     for (i = 0; i < nActs; i++) {
817         toAct = &darray_item(groupi->levels, i).action;
818
819         if (!HandleActionDef(act, info->keymap, toAct, info->actions))
820             log_err(info->keymap->ctx,
821                     "Illegal action definition for %s; "
822                     "Action for group %u/level %u ignored\n",
823                     KeyInfoText(info, keyi), ndx + 1, i + 1);
824
825         act = (ExprDef *) act->common.next;
826     }
827
828     return true;
829 }
830
831 static const LookupEntry repeatEntries[] = {
832     { "true", KEY_REPEAT_YES },
833     { "yes", KEY_REPEAT_YES },
834     { "on", KEY_REPEAT_YES },
835     { "false", KEY_REPEAT_NO },
836     { "no", KEY_REPEAT_NO },
837     { "off", KEY_REPEAT_NO },
838     { "default", KEY_REPEAT_UNDEFINED },
839     { NULL, 0 }
840 };
841
842 static bool
843 SetSymbolsField(SymbolsInfo *info, KeyInfo *keyi, const char *field,
844                 ExprDef *arrayNdx, ExprDef *value)
845 {
846     bool ok = true;
847     struct xkb_context *ctx = info->keymap->ctx;
848
849     if (istreq(field, "type")) {
850         xkb_layout_index_t ndx;
851         xkb_atom_t val;
852
853         if (!ExprResolveString(ctx, value, &val))
854             log_vrb(ctx, 1,
855                     "The type field of a key symbol map must be a string; "
856                     "Ignoring illegal type definition\n");
857
858         if (arrayNdx == NULL) {
859             keyi->dfltType = val;
860             keyi->defined |= KEY_FIELD_TYPE_DFLT;
861         }
862         else if (!ExprResolveGroup(ctx, arrayNdx, &ndx)) {
863             log_err(ctx,
864                     "Illegal group index for type of key %s; "
865                     "Definition with non-integer array index ignored\n",
866                     KeyInfoText(info, keyi));
867             return false;
868         }
869         else {
870             ndx--;
871             if (ndx >= darray_size(keyi->groups))
872                 darray_resize0(keyi->groups, ndx + 1);
873             darray_item(keyi->groups, ndx).type = val;
874             darray_item(keyi->groups, ndx).defined |= GROUP_FIELD_TYPE;
875         }
876     }
877     else if (istreq(field, "symbols"))
878         return AddSymbolsToKey(info, keyi, arrayNdx, value);
879     else if (istreq(field, "actions"))
880         return AddActionsToKey(info, keyi, arrayNdx, value);
881     else if (istreq(field, "vmods") ||
882              istreq(field, "virtualmods") ||
883              istreq(field, "virtualmodifiers")) {
884         xkb_mod_mask_t mask;
885
886         ok = ExprResolveVModMask(info->keymap, value, &mask);
887         if (ok) {
888             keyi->vmodmap = (mask >> XKB_NUM_CORE_MODS) & 0xffff;
889             keyi->defined |= KEY_FIELD_VMODMAP;
890         }
891         else {
892             log_err(info->keymap->ctx,
893                     "Expected a virtual modifier mask, found %s; "
894                     "Ignoring virtual modifiers definition for key %s\n",
895                     expr_op_type_to_string(value->op),
896                     KeyInfoText(info, keyi));
897         }
898     }
899     else if (istreq(field, "locking") ||
900              istreq(field, "lock") ||
901              istreq(field, "locks")) {
902         log_err(info->keymap->ctx,
903                 "Key behaviors not supported; "
904                 "Ignoring locking specification for key %s\n",
905                 KeyInfoText(info, keyi));
906     }
907     else if (istreq(field, "radiogroup") ||
908              istreq(field, "permanentradiogroup") ||
909              istreq(field, "allownone")) {
910         log_err(info->keymap->ctx,
911                 "Radio groups not supported; "
912                 "Ignoring radio group specification for key %s\n",
913                 KeyInfoText(info, keyi));
914     }
915     else if (istreq_prefix("overlay", field) ||
916              istreq_prefix("permanentoverlay", field)) {
917         log_err(info->keymap->ctx,
918                 "Overlays not supported; "
919                 "Ignoring overlay specification for key %s\n",
920                 KeyInfoText(info, keyi));
921     }
922     else if (istreq(field, "repeating") ||
923              istreq(field, "repeats") ||
924              istreq(field, "repeat")) {
925         unsigned int val;
926
927         ok = ExprResolveEnum(ctx, value, &val, repeatEntries);
928         if (!ok) {
929             log_err(info->keymap->ctx,
930                     "Illegal repeat setting for %s; "
931                     "Non-boolean repeat setting ignored\n",
932                     KeyInfoText(info, keyi));
933             return false;
934         }
935         keyi->repeat = val;
936         keyi->defined |= KEY_FIELD_REPEAT;
937     }
938     else if (istreq(field, "groupswrap") ||
939              istreq(field, "wrapgroups")) {
940         bool set;
941
942         if (!ExprResolveBoolean(ctx, value, &set)) {
943             log_err(info->keymap->ctx,
944                     "Illegal groupsWrap setting for %s; "
945                     "Non-boolean value ignored\n",
946                     KeyInfoText(info, keyi));
947             return false;
948         }
949
950         if (set)
951             keyi->out_of_range_group_action = RANGE_WRAP;
952         else
953             keyi->out_of_range_group_action = RANGE_SATURATE;
954
955         keyi->defined |= KEY_FIELD_GROUPINFO;
956     }
957     else if (istreq(field, "groupsclamp") ||
958              istreq(field, "clampgroups")) {
959         bool set;
960
961         if (!ExprResolveBoolean(ctx, value, &set)) {
962             log_err(info->keymap->ctx,
963                     "Illegal groupsClamp setting for %s; "
964                     "Non-boolean value ignored\n",
965                     KeyInfoText(info, keyi));
966             return false;
967         }
968
969         if (set)
970             keyi->out_of_range_group_action = RANGE_SATURATE;
971         else
972             keyi->out_of_range_group_action = RANGE_WRAP;
973
974         keyi->defined |= KEY_FIELD_GROUPINFO;
975     }
976     else if (istreq(field, "groupsredirect") ||
977              istreq(field, "redirectgroups")) {
978         xkb_layout_index_t grp;
979
980         if (!ExprResolveGroup(ctx, value, &grp)) {
981             log_err(info->keymap->ctx,
982                     "Illegal group index for redirect of key %s; "
983                     "Definition with non-integer group ignored\n",
984                     KeyInfoText(info, keyi));
985             return false;
986         }
987
988         keyi->out_of_range_group_action = RANGE_REDIRECT;
989         keyi->out_of_range_group_number = grp - 1;
990         keyi->defined |= KEY_FIELD_GROUPINFO;
991     }
992     else {
993         log_err(info->keymap->ctx,
994                 "Unknown field %s in a symbol interpretation; "
995                 "Definition ignored\n",
996                 field);
997         ok = false;
998     }
999
1000     return ok;
1001 }
1002
1003 static int
1004 SetGroupName(SymbolsInfo *info, ExprDef *arrayNdx, ExprDef *value)
1005 {
1006     xkb_layout_index_t grp, grp_to_use;
1007     xkb_atom_t name;
1008
1009     if (!arrayNdx) {
1010         log_vrb(info->keymap->ctx, 1,
1011                 "You must specify an index when specifying a group name; "
1012                 "Group name definition without array subscript ignored\n");
1013         return false;
1014     }
1015
1016     if (!ExprResolveGroup(info->keymap->ctx, arrayNdx, &grp)) {
1017         log_err(info->keymap->ctx,
1018                 "Illegal index in group name definition; "
1019                 "Definition with non-integer array index ignored\n");
1020         return false;
1021     }
1022
1023     if (!ExprResolveString(info->keymap->ctx, value, &name)) {
1024         log_err(info->keymap->ctx,
1025                 "Group name must be a string; "
1026                 "Illegal name for group %d ignored\n", grp);
1027         return false;
1028     }
1029
1030     grp_to_use = XKB_LAYOUT_INVALID;
1031     if (info->explicit_group == XKB_LAYOUT_INVALID) {
1032         grp_to_use = grp - 1;
1033     }
1034     else if (grp - 1 == 0) {
1035         grp_to_use = info->explicit_group;
1036     }
1037     else {
1038         log_warn(info->keymap->ctx,
1039                  "An explicit group was specified for the '%s' map, "
1040                  "but it provides a name for a group other than Group1 (%d); "
1041                  "Ignoring group name '%s'\n",
1042                  info->name, grp,
1043                  xkb_atom_text(info->keymap->ctx, name));
1044         return false;
1045     }
1046
1047     if (grp_to_use >= darray_size(info->group_names))
1048         darray_resize0(info->group_names, grp_to_use + 1);
1049     darray_item(info->group_names, grp_to_use) = name;
1050     return true;
1051 }
1052
1053 static int
1054 HandleGlobalVar(SymbolsInfo *info, VarDef *stmt)
1055 {
1056     const char *elem, *field;
1057     ExprDef *arrayNdx;
1058     bool ret;
1059
1060     if (ExprResolveLhs(info->keymap->ctx, stmt->name, &elem, &field,
1061                        &arrayNdx) == 0)
1062         return 0;               /* internal error, already reported */
1063     if (elem && istreq(elem, "key")) {
1064         ret = SetSymbolsField(info, &info->dflt, field, arrayNdx,
1065                               stmt->value);
1066     }
1067     else if (!elem && (istreq(field, "name") ||
1068                        istreq(field, "groupname"))) {
1069         ret = SetGroupName(info, arrayNdx, stmt->value);
1070     }
1071     else if (!elem && (istreq(field, "groupswrap") ||
1072                        istreq(field, "wrapgroups"))) {
1073         log_err(info->keymap->ctx,
1074                 "Global \"groupswrap\" not supported; Ignored\n");
1075         ret = true;
1076     }
1077     else if (!elem && (istreq(field, "groupsclamp") ||
1078                        istreq(field, "clampgroups"))) {
1079         log_err(info->keymap->ctx,
1080                 "Global \"groupsclamp\" not supported; Ignored\n");
1081         ret = true;
1082     }
1083     else if (!elem && (istreq(field, "groupsredirect") ||
1084                        istreq(field, "redirectgroups"))) {
1085         log_err(info->keymap->ctx,
1086                 "Global \"groupsredirect\" not supported; Ignored\n");
1087         ret = true;
1088     }
1089     else if (!elem && istreq(field, "allownone")) {
1090         log_err(info->keymap->ctx,
1091                 "Radio groups not supported; "
1092                 "Ignoring \"allownone\" specification\n");
1093         ret = true;
1094     }
1095     else {
1096         ret = SetActionField(info->keymap, elem, field, arrayNdx, stmt->value,
1097                              info->actions);
1098     }
1099
1100     return ret;
1101 }
1102
1103 static bool
1104 HandleSymbolsBody(SymbolsInfo *info, VarDef *def, KeyInfo *keyi)
1105 {
1106     bool ok = true;
1107     const char *elem, *field;
1108     ExprDef *arrayNdx;
1109
1110     for (; def; def = (VarDef *) def->common.next) {
1111         if (def->name && def->name->op == EXPR_FIELD_REF) {
1112             log_err(info->keymap->ctx,
1113                     "Cannot set a global default value from within a key statement; "
1114                     "Move statements to the global file scope\n");
1115             continue;
1116         }
1117
1118         if (!def->name) {
1119             if (!def->value || def->value->op == EXPR_KEYSYM_LIST)
1120                 field = "symbols";
1121             else
1122                 field = "actions";
1123             arrayNdx = NULL;
1124         }
1125         else {
1126             ok = ExprResolveLhs(info->keymap->ctx, def->name, &elem, &field,
1127                                 &arrayNdx);
1128         }
1129
1130         if (ok)
1131             ok = SetSymbolsField(info, keyi, field, arrayNdx, def->value);
1132     }
1133
1134     return ok;
1135 }
1136
1137 static bool
1138 SetExplicitGroup(SymbolsInfo *info, KeyInfo *keyi)
1139 {
1140     xkb_layout_index_t i;
1141     GroupInfo *groupi;
1142     bool warn = false;
1143
1144     if (info->explicit_group == XKB_LAYOUT_INVALID)
1145         return true;
1146
1147     darray_enumerate_from(i, groupi, keyi->groups, 1) {
1148         if (groupi->defined) {
1149             warn = true;
1150             ClearGroupInfo(groupi);
1151             InitGroupInfo(groupi);
1152         }
1153     }
1154
1155     if (warn)
1156         log_warn(info->keymap->ctx,
1157                  "For the map %s an explicit group specified, "
1158                  "but key %s has more than one group defined; "
1159                  "All groups except first one will be ignored\n",
1160                  info->name, KeyInfoText(info, keyi));
1161
1162     darray_resize0(keyi->groups, info->explicit_group + 1);
1163     if (info->explicit_group > 0) {
1164         darray_item(keyi->groups, info->explicit_group) =
1165             darray_item(keyi->groups, 0);
1166         InitGroupInfo(&darray_item(keyi->groups, 0));
1167     }
1168
1169     return true;
1170 }
1171
1172 static int
1173 HandleSymbolsDef(SymbolsInfo *info, SymbolsDef *stmt)
1174 {
1175     KeyInfo keyi;
1176     xkb_layout_index_t i;
1177
1178     keyi = info->dflt;
1179     darray_init(keyi.groups);
1180     darray_copy(keyi.groups, info->dflt.groups);
1181     for (i = 0; i < darray_size(keyi.groups); i++)
1182         CopyGroupInfo(&darray_item(keyi.groups, i),
1183                       &darray_item(info->dflt.groups, i));
1184     keyi.merge = stmt->merge;
1185     keyi.name = stmt->keyName;
1186
1187     if (!HandleSymbolsBody(info, (VarDef *) stmt->symbols, &keyi)) {
1188         info->errorCount++;
1189         return false;
1190     }
1191
1192     if (!SetExplicitGroup(info, &keyi)) {
1193         info->errorCount++;
1194         return false;
1195     }
1196
1197     if (!AddKeySymbols(info, &keyi)) {
1198         info->errorCount++;
1199         return false;
1200     }
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 = 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 = HandleGlobalVar(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_layout_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(key, group); level++) {
1316                 if (key->groups[group].levels[level].num_syms != 1 ||
1317                     key->groups[group].levels[level].u.sym != sym)
1318                     continue;
1319
1320                 /*
1321                  * If the keysym was found in a group or level > 0, we must
1322                  * keep looking since we might find a key in which the keysym
1323                  * is in a lower group or level.
1324                  */
1325                 if (group < min_group ||
1326                     (group == min_group && level < min_level)) {
1327                     ret = key;
1328                     if (group == 0 && level == 0) {
1329                         return ret;
1330                     }
1331                     else {
1332                         min_group = group;
1333                         min_level = level;
1334                     }
1335                 }
1336             }
1337         }
1338     }
1339
1340     return ret;
1341 }
1342
1343 /*
1344  * Find an appropriate type for a group and return its name.
1345  *
1346  * Simple recipe:
1347  * - ONE_LEVEL for width 0/1
1348  * - ALPHABETIC for 2 shift levels, with lower/upercase keysyms
1349  * - KEYPAD for keypad keys.
1350  * - TWO_LEVEL for other 2 shift level keys.
1351  * and the same for four level keys.
1352  *
1353  * FIXME: Decide how to handle multiple-syms-per-level, and do it.
1354  */
1355 static xkb_atom_t
1356 FindAutomaticType(struct xkb_context *ctx, GroupInfo *groupi)
1357 {
1358     xkb_keysym_t sym0, sym1, sym2, sym3;
1359     xkb_level_index_t width = darray_size(groupi->levels);
1360
1361 #define GET_SYM(level) \
1362     (darray_item(groupi->levels, level).num_syms == 0 ? \
1363         XKB_KEY_NoSymbol : \
1364      darray_item(groupi->levels, level).num_syms == 1 ? \
1365         darray_item(groupi->levels, level).u.sym : \
1366      /* num_syms > 1 */ \
1367         darray_item(groupi->levels, level).u.syms[0])
1368
1369     if (width == 1 || width <= 0)
1370         return xkb_atom_intern(ctx, "ONE_LEVEL");
1371
1372     sym0 = GET_SYM(0);
1373     sym1 = GET_SYM(1);
1374
1375     if (width == 2) {
1376         if (xkb_keysym_is_lower(sym0) && xkb_keysym_is_upper(sym1))
1377             return xkb_atom_intern(ctx, "ALPHABETIC");
1378
1379         if (xkb_keysym_is_keypad(sym0) || xkb_keysym_is_keypad(sym1))
1380             return xkb_atom_intern(ctx, "KEYPAD");
1381
1382         return xkb_atom_intern(ctx, "TWO_LEVEL");
1383     }
1384
1385     if (width <= 4) {
1386         if (xkb_keysym_is_lower(sym0) && xkb_keysym_is_upper(sym1)) {
1387             sym2 = GET_SYM(2);
1388             sym3 = (width == 4 ? GET_SYM(3) : XKB_KEY_NoSymbol);
1389
1390             if (xkb_keysym_is_lower(sym2) && xkb_keysym_is_upper(sym3))
1391                 return xkb_atom_intern(ctx, "FOUR_LEVEL_ALPHABETIC");
1392
1393             return xkb_atom_intern(ctx, "FOUR_LEVEL_SEMIALPHABETIC");
1394         }
1395
1396         if (xkb_keysym_is_keypad(sym0) || xkb_keysym_is_keypad(sym1))
1397             return xkb_atom_intern(ctx, "FOUR_LEVEL_KEYPAD");
1398
1399         return xkb_atom_intern(ctx, "FOUR_LEVEL");
1400     }
1401
1402     return XKB_ATOM_NONE;
1403
1404 #undef GET_SYM
1405 }
1406
1407 static const struct xkb_key_type *
1408 FindTypeForGroup(struct xkb_keymap *keymap, KeyInfo *keyi,
1409                  xkb_layout_index_t group, bool *explicit_type)
1410 {
1411     unsigned int i;
1412     GroupInfo *groupi = &darray_item(keyi->groups, group);
1413     xkb_atom_t type_name = groupi->type;
1414
1415     *explicit_type = true;
1416
1417     if (type_name == XKB_ATOM_NONE) {
1418         if (keyi->dfltType != XKB_ATOM_NONE) {
1419             type_name  = keyi->dfltType;
1420         }
1421         else {
1422             type_name = FindAutomaticType(keymap->ctx, groupi);
1423             if (type_name != XKB_ATOM_NONE)
1424                 *explicit_type = false;
1425         }
1426     }
1427
1428     if (type_name == XKB_ATOM_NONE) {
1429         log_warn(keymap->ctx,
1430                  "Couldn't find an automatic type for key '%s' group %d with %lu levels; "
1431                  "Using the default type\n",
1432                  KeyNameText(keymap->ctx, keyi->name), group + 1,
1433                  (unsigned long) darray_size(groupi->levels));
1434         goto use_default;
1435     }
1436
1437     for (i = 0; i < keymap->num_types; i++)
1438         if (keymap->types[i].name == type_name)
1439             break;
1440
1441     if (i >= keymap->num_types) {
1442         log_warn(keymap->ctx,
1443                  "The type \"%s\" for key '%s' group %d was not previously defined; "
1444                  "Using the default type\n",
1445                  xkb_atom_text(keymap->ctx, type_name),
1446                  KeyNameText(keymap->ctx, keyi->name), group + 1);
1447         goto use_default;
1448     }
1449
1450     return &keymap->types[i];
1451
1452 use_default:
1453     /*
1454      * Index 0 is guaranteed to contain something, usually
1455      * ONE_LEVEL or at least some default one-level type.
1456      */
1457     return &keymap->types[0];
1458 }
1459
1460 static bool
1461 CopySymbolsDef(SymbolsInfo *info, KeyInfo *keyi)
1462 {
1463     struct xkb_keymap *keymap = info->keymap;
1464     struct xkb_key *key;
1465     GroupInfo *groupi;
1466     const GroupInfo *group0;
1467     xkb_layout_index_t i;
1468
1469     /*
1470      * The name is guaranteed to be real and not an alias (see
1471      * AddKeySymbols), so 'false' is safe here.
1472      */
1473     key = FindNamedKey(keymap, keyi->name, false);
1474     if (!key) {
1475         log_vrb(info->keymap->ctx, 5,
1476                 "Key %s not found in keycodes; Symbols ignored\n",
1477                 KeyInfoText(info, keyi));
1478         return false;
1479     }
1480
1481     /* Find the range of groups we need. */
1482     key->num_groups = 0;
1483     darray_enumerate(i, groupi, keyi->groups)
1484         if (groupi->defined)
1485             key->num_groups = i + 1;
1486
1487     if (key->num_groups <= 0)
1488         return false; /* WSGO */
1489
1490     darray_resize(keyi->groups, key->num_groups);
1491
1492     /*
1493      * If there are empty groups between non-empty ones, fill them with data
1494      * from the first group.
1495      * We can make a wrong assumption here. But leaving gaps is worse.
1496      */
1497     group0 = &darray_item(keyi->groups, 0);
1498     darray_foreach_from(groupi, keyi->groups, 1) {
1499         if (groupi->defined)
1500             continue;
1501
1502         CopyGroupInfo(groupi, group0);
1503     }
1504
1505     key->groups = calloc(key->num_groups, sizeof(*key->groups));
1506
1507     /* Find and assign the groups' types in the keymap. */
1508     darray_enumerate(i, groupi, keyi->groups) {
1509         const struct xkb_key_type *type;
1510         bool explicit_type;
1511
1512         type = FindTypeForGroup(keymap, keyi, i, &explicit_type);
1513
1514         /* Always have as many levels as the type specifies. */
1515         if (type->num_levels < darray_size(groupi->levels)) {
1516             struct xkb_level *leveli;
1517
1518             log_vrb(info->keymap->ctx, 1,
1519                     "Type \"%s\" has %d levels, but %s has %d levels; "
1520                     "Ignoring extra symbols\n",
1521                     xkb_atom_text(keymap->ctx, type->name), type->num_levels,
1522                     KeyInfoText(info, keyi),
1523                     (int) darray_size(groupi->levels));
1524
1525             darray_foreach_from(leveli, groupi->levels, type->num_levels)
1526                 ClearLevelInfo(leveli);
1527         }
1528         darray_resize0(groupi->levels, type->num_levels);
1529
1530         key->groups[i].explicit_type = explicit_type;
1531         key->groups[i].type = type;
1532     }
1533
1534     /* Copy levels. */
1535     darray_enumerate(i, groupi, keyi->groups) {
1536         key->groups[i].levels = darray_mem(groupi->levels, 0);
1537         darray_init(groupi->levels);
1538     }
1539
1540     key->out_of_range_group_number = keyi->out_of_range_group_number;
1541     key->out_of_range_group_action = keyi->out_of_range_group_action;
1542
1543     if (keyi->defined & KEY_FIELD_VMODMAP) {
1544         key->vmodmap = keyi->vmodmap;
1545         key->explicit |= EXPLICIT_VMODMAP;
1546     }
1547
1548     if (keyi->repeat != KEY_REPEAT_UNDEFINED) {
1549         key->repeats = (keyi->repeat == KEY_REPEAT_YES);
1550         key->explicit |= EXPLICIT_REPEAT;
1551     }
1552
1553     darray_foreach(groupi, keyi->groups) {
1554         if (groupi->defined & GROUP_FIELD_ACTS) {
1555             key->explicit |= EXPLICIT_INTERP;
1556             break;
1557         }
1558     }
1559
1560     return true;
1561 }
1562
1563 static bool
1564 CopyModMapDef(SymbolsInfo *info, ModMapEntry *entry)
1565 {
1566     struct xkb_key *key;
1567     struct xkb_keymap *keymap = info->keymap;
1568
1569     if (!entry->haveSymbol) {
1570         key = FindNamedKey(keymap, entry->u.keyName, true);
1571         if (!key) {
1572             log_vrb(info->keymap->ctx, 5,
1573                     "Key %s not found in keycodes; "
1574                     "Modifier map entry for %s not updated\n",
1575                     KeyNameText(keymap->ctx, entry->u.keyName),
1576                     ModIndexText(entry->modifier));
1577             return false;
1578         }
1579     }
1580     else {
1581         key = FindKeyForSymbol(keymap, entry->u.keySym);
1582         if (!key) {
1583             log_vrb(info->keymap->ctx, 5,
1584                     "Key \"%s\" not found in symbol map; "
1585                     "Modifier map entry for %s not updated\n",
1586                     KeysymText(entry->u.keySym),
1587                     ModIndexText(entry->modifier));
1588             return false;
1589         }
1590     }
1591
1592     key->modmap |= (1 << entry->modifier);
1593     return true;
1594 }
1595
1596 static bool
1597 CopySymbolsToKeymap(struct xkb_keymap *keymap, SymbolsInfo *info)
1598 {
1599     KeyInfo *keyi;
1600     ModMapEntry *mm;
1601     struct xkb_key *key;
1602
1603     keymap->symbols_section_name = strdup_safe(info->name);
1604
1605     keymap->group_names = info->group_names;
1606     darray_init(info->group_names);
1607
1608     darray_foreach(keyi, info->keys)
1609         if (!CopySymbolsDef(info, keyi))
1610             info->errorCount++;
1611
1612     if (xkb_context_get_log_verbosity(keymap->ctx) > 3) {
1613         xkb_foreach_key(key, keymap) {
1614             if (key->name == XKB_ATOM_NONE)
1615                 continue;
1616
1617             if (key->num_groups < 1)
1618                 log_info(keymap->ctx,
1619                          "No symbols defined for %s\n",
1620                          KeyNameText(keymap->ctx, key->name));
1621         }
1622     }
1623
1624     darray_foreach(mm, info->modMaps)
1625         if (!CopyModMapDef(info, mm))
1626             info->errorCount++;
1627
1628     /* XXX: If we don't ignore errorCount, things break. */
1629     return true;
1630 }
1631
1632 bool
1633 CompileSymbols(XkbFile *file, struct xkb_keymap *keymap,
1634                enum merge_mode merge)
1635 {
1636     SymbolsInfo info;
1637     ActionsInfo *actions;
1638
1639     actions = NewActionsInfo();
1640     if (!actions)
1641         return false;
1642
1643     InitSymbolsInfo(&info, keymap, file->id, actions);
1644     info.dflt.merge = merge;
1645
1646     HandleSymbolsFile(&info, file, merge);
1647
1648     if (darray_empty(info.keys))
1649         goto err_info;
1650
1651     if (info.errorCount != 0)
1652         goto err_info;
1653
1654     if (!CopySymbolsToKeymap(keymap, &info))
1655         goto err_info;
1656
1657     ClearSymbolsInfo(&info);
1658     FreeActionsInfo(actions);
1659     return true;
1660
1661 err_info:
1662     FreeActionsInfo(actions);
1663     ClearSymbolsInfo(&info);
1664     return false;
1665 }