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