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