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