58f73e673b5149763e1fbc78c2c9e27a4b0e5d2a
[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(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(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(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(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(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(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     if (!include)
573         return false;
574
575     InitSymbolsInfo(&included, info->keymap, info->actions, &info->mods);
576     included.name = include->stmt;
577     include->stmt = NULL;
578
579     for (IncludeStmt *stmt = include; stmt; stmt = stmt->next_incl) {
580         SymbolsInfo next_incl;
581         XkbFile *file;
582
583         file = ProcessIncludeFile(info->ctx, stmt, FILE_TYPE_SYMBOLS);
584         if (!file) {
585             info->errorCount += 10;
586             ClearSymbolsInfo(&included);
587             return false;
588         }
589
590         InitSymbolsInfo(&next_incl, info->keymap, info->actions,
591                         &included.mods);
592         if (stmt->modifier) {
593             next_incl.explicit_group = atoi(stmt->modifier) - 1;
594             if (next_incl.explicit_group >= XKB_MAX_GROUPS) {
595                 log_err(info->ctx,
596                         XKB_ERROR_UNSUPPORTED_GROUP_INDEX,
597                         "Cannot set explicit group to %d - must be between 1..%d; "
598                         "Ignoring group number\n",
599                         next_incl.explicit_group + 1, XKB_MAX_GROUPS);
600                 next_incl.explicit_group = info->explicit_group;
601             }
602         }
603         else {
604             next_incl.explicit_group = info->explicit_group;
605         }
606
607         HandleSymbolsFile(&next_incl, file, MERGE_OVERRIDE);
608
609         MergeIncludedSymbols(&included, &next_incl, stmt->merge);
610
611         ClearSymbolsInfo(&next_incl);
612         FreeXkbFile(file);
613     }
614
615     MergeIncludedSymbols(info, &included, include->merge);
616     ClearSymbolsInfo(&included);
617
618     return (info->errorCount == 0);
619 }
620
621 #define SYMBOLS 1
622 #define ACTIONS 2
623
624 static bool
625 GetGroupIndex(SymbolsInfo *info, KeyInfo *keyi, ExprDef *arrayNdx,
626               unsigned what, xkb_layout_index_t *ndx_rtrn)
627 {
628     const char *name = (what == SYMBOLS ? "symbols" : "actions");
629
630     if (arrayNdx == NULL) {
631         xkb_layout_index_t i;
632         GroupInfo *groupi;
633         enum group_field field = (what == SYMBOLS ?
634                                   GROUP_FIELD_SYMS : GROUP_FIELD_ACTS);
635
636         darray_enumerate(i, groupi, keyi->groups) {
637             if (!(groupi->defined & field)) {
638                 *ndx_rtrn = i;
639                 return true;
640             }
641         }
642
643         if (i >= XKB_MAX_GROUPS) {
644             log_err(info->ctx,
645                     XKB_ERROR_UNSUPPORTED_GROUP_INDEX,
646                     "Too many groups of %s for key %s (max %u); "
647                     "Ignoring %s defined for extra groups\n",
648                     name, KeyInfoText(info, keyi), XKB_MAX_GROUPS, name);
649             return false;
650         }
651
652         darray_resize0(keyi->groups, darray_size(keyi->groups) + 1);
653         *ndx_rtrn = darray_size(keyi->groups) - 1;
654         return true;
655     }
656
657     if (!ExprResolveGroup(info->ctx, arrayNdx, ndx_rtrn)) {
658         log_err(info->ctx, XKB_ERROR_UNSUPPORTED_GROUP_INDEX,
659                 "Illegal group index for %s of key %s\n"
660                 "Definition with non-integer array index ignored\n",
661                 name, KeyInfoText(info, keyi));
662         return false;
663     }
664
665     (*ndx_rtrn)--;
666     if (*ndx_rtrn >= darray_size(keyi->groups))
667         darray_resize0(keyi->groups, *ndx_rtrn + 1);
668
669     return true;
670 }
671
672 static bool
673 AddSymbolsToKey(SymbolsInfo *info, KeyInfo *keyi, ExprDef *arrayNdx,
674                 ExprDef *value)
675 {
676     xkb_layout_index_t ndx;
677     GroupInfo *groupi;
678     xkb_level_index_t nLevels;
679
680     if (!GetGroupIndex(info, keyi, arrayNdx, SYMBOLS, &ndx))
681         return false;
682
683     groupi = &darray_item(keyi->groups, ndx);
684
685     if (value == NULL) {
686         groupi->defined |= GROUP_FIELD_SYMS;
687         return true;
688     }
689
690     if (value->expr.op != EXPR_KEYSYM_LIST) {
691         log_err(info->ctx,
692                 XKB_ERROR_WRONG_FIELD_TYPE,
693                 "Expected a list of symbols, found %s; "
694                 "Ignoring symbols for group %u of %s\n",
695                 expr_op_type_to_string(value->expr.op), ndx + 1,
696                 KeyInfoText(info, keyi));
697         return false;
698     }
699
700     if (groupi->defined & GROUP_FIELD_SYMS) {
701         log_err(info->ctx,
702                 XKB_ERROR_CONFLICTING_KEY_SYMBOLS_ENTRY,
703                 "Symbols for key %s, group %u already defined; "
704                 "Ignoring duplicate definition\n",
705                 KeyInfoText(info, keyi), ndx + 1);
706         return false;
707     }
708
709     nLevels = darray_size(value->keysym_list.symsMapIndex);
710     if (darray_size(groupi->levels) < nLevels)
711         darray_resize0(groupi->levels, nLevels);
712
713     groupi->defined |= GROUP_FIELD_SYMS;
714
715     for (xkb_level_index_t i = 0; i < nLevels; i++) {
716         unsigned int sym_index;
717         struct xkb_level *leveli = &darray_item(groupi->levels, i);
718
719         sym_index = darray_item(value->keysym_list.symsMapIndex, i);
720         leveli->num_syms = darray_item(value->keysym_list.symsNumEntries, i);
721         if (leveli->num_syms > 1) {
722             leveli->u.syms = calloc(leveli->num_syms, sizeof(*leveli->u.syms));
723             if (!leveli->u.syms) {
724                 log_err(info->ctx, "Failed to allocate memory for leveli->u.syms\n");
725                 continue;
726             }
727         }
728
729         for (unsigned j = 0; j < leveli->num_syms; j++) {
730             xkb_keysym_t keysym = darray_item(value->keysym_list.syms,
731                                               sym_index + j);
732
733             if (leveli->num_syms == 1) {
734                 if (keysym == XKB_KEY_NoSymbol)
735                     leveli->num_syms = 0;
736                 else
737                     leveli->u.sym = keysym;
738             }
739             else if (leveli->num_syms > 1) {
740                 leveli->u.syms[j] = keysym;
741             }
742         }
743     }
744
745     return true;
746 }
747
748 static bool
749 AddActionsToKey(SymbolsInfo *info, KeyInfo *keyi, ExprDef *arrayNdx,
750                 ExprDef *value)
751 {
752     xkb_layout_index_t ndx;
753     GroupInfo *groupi;
754     unsigned int nActs;
755     ExprDef *act;
756
757     if (!GetGroupIndex(info, keyi, arrayNdx, ACTIONS, &ndx))
758         return false;
759
760     groupi = &darray_item(keyi->groups, ndx);
761
762     if (value == NULL) {
763         groupi->defined |= GROUP_FIELD_ACTS;
764         return true;
765     }
766
767     if (value->expr.op != EXPR_ACTION_LIST) {
768         log_wsgo(info->ctx, XKB_LOG_MESSAGE_NO_ID,
769                  "Bad expression type (%d) for action list value; "
770                  "Ignoring actions for group %u of %s\n",
771                  value->expr.op, ndx, KeyInfoText(info, keyi));
772         return false;
773     }
774
775     if (groupi->defined & GROUP_FIELD_ACTS) {
776         log_wsgo(info->ctx, XKB_LOG_MESSAGE_NO_ID,
777                  "Actions for key %s, group %u already defined\n",
778                  KeyInfoText(info, keyi), ndx);
779         return false;
780     }
781
782     nActs = 0;
783     for (act = value->actions.actions; act; act = (ExprDef *) act->common.next)
784         nActs++;
785
786     if (darray_size(groupi->levels) < nActs)
787         darray_resize0(groupi->levels, nActs);
788
789     groupi->defined |= GROUP_FIELD_ACTS;
790
791     act = value->actions.actions;
792     for (unsigned i = 0; i < nActs; i++) {
793         union xkb_action *toAct = &darray_item(groupi->levels, i).action;
794
795         if (!HandleActionDef(info->ctx, info->actions, &info->mods, act, toAct))
796             log_err(info->ctx,
797                     XKB_ERROR_INVALID_VALUE,
798                     "Illegal action definition for %s; "
799                     "Action for group %u/level %u ignored\n",
800                     KeyInfoText(info, keyi), ndx + 1, i + 1);
801
802         act = (ExprDef *) act->common.next;
803     }
804
805     return true;
806 }
807
808 static const LookupEntry repeatEntries[] = {
809     { "true", KEY_REPEAT_YES },
810     { "yes", KEY_REPEAT_YES },
811     { "on", KEY_REPEAT_YES },
812     { "false", KEY_REPEAT_NO },
813     { "no", KEY_REPEAT_NO },
814     { "off", KEY_REPEAT_NO },
815     { "default", KEY_REPEAT_UNDEFINED },
816     { NULL, 0 }
817 };
818
819 static bool
820 SetSymbolsField(SymbolsInfo *info, KeyInfo *keyi, const char *field,
821                 ExprDef *arrayNdx, ExprDef *value)
822 {
823     if (istreq(field, "type")) {
824         xkb_layout_index_t ndx;
825         xkb_atom_t val;
826
827         if (!ExprResolveString(info->ctx, value, &val)) {
828             log_err(info->ctx,
829                     XKB_ERROR_WRONG_FIELD_TYPE,
830                     "The type field of a key symbol map must be a string; "
831                     "Ignoring illegal type definition\n");
832             return false;
833         }
834
835         if (!arrayNdx) {
836             keyi->default_type = val;
837             keyi->defined |= KEY_FIELD_DEFAULT_TYPE;
838         }
839         else if (!ExprResolveGroup(info->ctx, arrayNdx, &ndx)) {
840             log_err(info->ctx, XKB_ERROR_UNSUPPORTED_GROUP_INDEX,
841                     "Illegal group index for type of key %s; "
842                     "Definition with non-integer array index ignored\n",
843                     KeyInfoText(info, keyi));
844             return false;
845         }
846         else {
847             ndx--;
848             if (ndx >= darray_size(keyi->groups))
849                 darray_resize0(keyi->groups, ndx + 1);
850             darray_item(keyi->groups, ndx).type = val;
851             darray_item(keyi->groups, ndx).defined |= GROUP_FIELD_TYPE;
852         }
853     }
854     else if (istreq(field, "symbols")) {
855         return AddSymbolsToKey(info, keyi, arrayNdx, value);
856     }
857     else if (istreq(field, "actions")) {
858         return AddActionsToKey(info, keyi, arrayNdx, value);
859     }
860     else if (istreq(field, "vmods") ||
861              istreq(field, "virtualmods") ||
862              istreq(field, "virtualmodifiers")) {
863         xkb_mod_mask_t mask;
864
865         if (!ExprResolveModMask(info->ctx, value, MOD_VIRT, &info->mods,
866                                 &mask)) {
867             log_err(info->ctx,
868                     XKB_ERROR_UNSUPPORTED_MODIFIER_MASK,
869                     "Expected a virtual modifier mask, found %s; "
870                     "Ignoring virtual modifiers definition for key %s\n",
871                     expr_op_type_to_string(value->expr.op),
872                     KeyInfoText(info, keyi));
873             return false;
874         }
875
876         keyi->vmodmap = mask;
877         keyi->defined |= KEY_FIELD_VMODMAP;
878     }
879     else if (istreq(field, "locking") ||
880              istreq(field, "lock") ||
881              istreq(field, "locks")) {
882         log_vrb(info->ctx, 1,
883                 XKB_WARNING_UNSUPPORTED_SYMBOLS_FIELD,
884                 "Key behaviors not supported; "
885                 "Ignoring locking specification for key %s\n",
886                 KeyInfoText(info, keyi));
887     }
888     else if (istreq(field, "radiogroup") ||
889              istreq(field, "permanentradiogroup") ||
890              istreq(field, "allownone")) {
891         log_vrb(info->ctx, 1,
892                 XKB_WARNING_UNSUPPORTED_SYMBOLS_FIELD,
893                 "Radio groups not supported; "
894                 "Ignoring radio group specification for key %s\n",
895                 KeyInfoText(info, keyi));
896     }
897     else if (istreq_prefix("overlay", field) ||
898              istreq_prefix("permanentoverlay", field)) {
899         log_vrb(info->ctx, 1,
900                 XKB_WARNING_UNSUPPORTED_SYMBOLS_FIELD,
901                 "Overlays not supported; "
902                 "Ignoring overlay specification for key %s\n",
903                 KeyInfoText(info, keyi));
904     }
905     else if (istreq(field, "repeating") ||
906              istreq(field, "repeats") ||
907              istreq(field, "repeat")) {
908         unsigned int val;
909
910         if (!ExprResolveEnum(info->ctx, value, &val, repeatEntries)) {
911             log_err(info->ctx,
912                     XKB_ERROR_INVALID_VALUE,
913                     "Illegal repeat setting for %s; "
914                     "Non-boolean repeat setting ignored\n",
915                     KeyInfoText(info, keyi));
916             return false;
917         }
918
919         keyi->repeat = val;
920         keyi->defined |= KEY_FIELD_REPEAT;
921     }
922     else if (istreq(field, "groupswrap") ||
923              istreq(field, "wrapgroups")) {
924         bool set;
925
926         if (!ExprResolveBoolean(info->ctx, value, &set)) {
927             log_err(info->ctx,
928                     XKB_ERROR_INVALID_VALUE,
929                     "Illegal groupsWrap setting for %s; "
930                     "Non-boolean value ignored\n",
931                     KeyInfoText(info, keyi));
932             return false;
933         }
934
935         keyi->out_of_range_group_action = (set ? RANGE_WRAP : RANGE_SATURATE);
936         keyi->defined |= KEY_FIELD_GROUPINFO;
937     }
938     else if (istreq(field, "groupsclamp") ||
939              istreq(field, "clampgroups")) {
940         bool set;
941
942         if (!ExprResolveBoolean(info->ctx, value, &set)) {
943             log_err(info->ctx,
944                     XKB_ERROR_INVALID_VALUE,
945                     "Illegal groupsClamp setting for %s; "
946                     "Non-boolean value ignored\n",
947                     KeyInfoText(info, keyi));
948             return false;
949         }
950
951         keyi->out_of_range_group_action = (set ? RANGE_SATURATE : RANGE_WRAP);
952         keyi->defined |= KEY_FIELD_GROUPINFO;
953     }
954     else if (istreq(field, "groupsredirect") ||
955              istreq(field, "redirectgroups")) {
956         xkb_layout_index_t grp;
957
958         if (!ExprResolveGroup(info->ctx, value, &grp)) {
959             log_err(info->ctx, XKB_ERROR_UNSUPPORTED_GROUP_INDEX,
960                     "Illegal group index for redirect of key %s; "
961                     "Definition with non-integer group ignored\n",
962                     KeyInfoText(info, keyi));
963             return false;
964         }
965
966         keyi->out_of_range_group_action = RANGE_REDIRECT;
967         keyi->out_of_range_group_number = grp - 1;
968         keyi->defined |= KEY_FIELD_GROUPINFO;
969     }
970     else {
971         log_err(info->ctx,
972                 XKB_ERROR_UNKNOWN_FIELD,
973                 "Unknown field %s in a symbol interpretation; "
974                 "Definition ignored\n",
975                 field);
976         return false;
977     }
978
979     return true;
980 }
981
982 static bool
983 SetGroupName(SymbolsInfo *info, ExprDef *arrayNdx, ExprDef *value)
984 {
985     xkb_layout_index_t group, group_to_use;
986     xkb_atom_t name;
987
988     if (!arrayNdx) {
989         log_vrb(info->ctx, 1,
990                 XKB_WARNING_MISSING_SYMBOLS_GROUP_NAME_INDEX,
991                 "You must specify an index when specifying a group name; "
992                 "Group name definition without array subscript ignored\n");
993         return false;
994     }
995
996     if (!ExprResolveGroup(info->ctx, arrayNdx, &group)) {
997         log_err(info->ctx, XKB_ERROR_UNSUPPORTED_GROUP_INDEX,
998                 "Illegal index in group name definition; "
999                 "Definition with non-integer array index ignored\n");
1000         return false;
1001     }
1002
1003     if (!ExprResolveString(info->ctx, value, &name)) {
1004         log_err(info->ctx,
1005                 XKB_ERROR_WRONG_FIELD_TYPE,
1006                 "Group name must be a string; "
1007                 "Illegal name for group %d ignored\n", group);
1008         return false;
1009     }
1010
1011     if (info->explicit_group == XKB_LAYOUT_INVALID) {
1012         group_to_use = group - 1;
1013     }
1014     else if (group - 1 == 0) {
1015         group_to_use = info->explicit_group;
1016     }
1017     else {
1018         log_warn(info->ctx,
1019                  XKB_WARNING_NON_BASE_GROUP_NAME,
1020                  "An explicit group was specified for the '%s' map, "
1021                  "but it provides a name for a group other than Group1 (%d); "
1022                  "Ignoring group name '%s'\n",
1023                  info->name, group,
1024                  xkb_atom_text(info->ctx, name));
1025         return false;
1026     }
1027
1028     if (group_to_use >= darray_size(info->group_names))
1029         darray_resize0(info->group_names, group_to_use + 1);
1030     darray_item(info->group_names, group_to_use) = name;
1031
1032     return true;
1033 }
1034
1035 static bool
1036 HandleGlobalVar(SymbolsInfo *info, VarDef *stmt)
1037 {
1038     const char *elem, *field;
1039     ExprDef *arrayNdx;
1040     bool ret;
1041
1042     if (!ExprResolveLhs(info->ctx, stmt->name, &elem, &field, &arrayNdx))
1043         return false;
1044
1045     if (elem && istreq(elem, "key")) {
1046         ret = SetSymbolsField(info, &info->default_key, field, arrayNdx,
1047                               stmt->value);
1048     }
1049     else if (!elem && (istreq(field, "name") ||
1050                        istreq(field, "groupname"))) {
1051         ret = SetGroupName(info, arrayNdx, stmt->value);
1052     }
1053     else if (!elem && (istreq(field, "groupswrap") ||
1054                        istreq(field, "wrapgroups"))) {
1055         log_err(info->ctx,
1056                 XKB_WARNING_UNSUPPORTED_SYMBOLS_FIELD,
1057                 "Global \"groupswrap\" not supported; Ignored\n");
1058         ret = true;
1059     }
1060     else if (!elem && (istreq(field, "groupsclamp") ||
1061                        istreq(field, "clampgroups"))) {
1062         log_err(info->ctx,
1063                 XKB_WARNING_UNSUPPORTED_SYMBOLS_FIELD,
1064                 "Global \"groupsclamp\" not supported; Ignored\n");
1065         ret = true;
1066     }
1067     else if (!elem && (istreq(field, "groupsredirect") ||
1068                        istreq(field, "redirectgroups"))) {
1069         log_err(info->ctx,
1070                 XKB_WARNING_UNSUPPORTED_SYMBOLS_FIELD,
1071                 "Global \"groupsredirect\" not supported; Ignored\n");
1072         ret = true;
1073     }
1074     else if (!elem && istreq(field, "allownone")) {
1075         log_err(info->ctx,
1076                 XKB_WARNING_UNSUPPORTED_SYMBOLS_FIELD,
1077                 "Radio groups not supported; "
1078                 "Ignoring \"allownone\" specification\n");
1079         ret = true;
1080     }
1081     else {
1082         ret = SetActionField(info->ctx, info->actions, &info->mods,
1083                              elem, field, arrayNdx, stmt->value);
1084     }
1085
1086     return ret;
1087 }
1088
1089 static bool
1090 HandleSymbolsBody(SymbolsInfo *info, VarDef *def, KeyInfo *keyi)
1091 {
1092     bool ok = true;
1093     const char *elem, *field;
1094     ExprDef *arrayNdx;
1095
1096     for (; def; def = (VarDef *) def->common.next) {
1097         if (def->name && def->name->expr.op == EXPR_FIELD_REF) {
1098             log_err(info->ctx,
1099                     XKB_ERROR_WRONG_SCOPE,
1100                     "Cannot set a global default value from within a key statement; "
1101                     "Move statements to the global file scope\n");
1102             continue;
1103         }
1104
1105         if (!def->name) {
1106             if (!def->value || def->value->expr.op == EXPR_KEYSYM_LIST)
1107                 field = "symbols";
1108             else
1109                 field = "actions";
1110             arrayNdx = NULL;
1111         }
1112         else {
1113             ok = ExprResolveLhs(info->ctx, def->name, &elem, &field,
1114                                 &arrayNdx);
1115         }
1116
1117         if (ok)
1118             ok = SetSymbolsField(info, keyi, field, arrayNdx, def->value);
1119     }
1120
1121     return ok;
1122 }
1123
1124 static bool
1125 SetExplicitGroup(SymbolsInfo *info, KeyInfo *keyi)
1126 {
1127     xkb_layout_index_t i;
1128     GroupInfo *groupi;
1129     bool warn = false;
1130
1131     if (info->explicit_group == XKB_LAYOUT_INVALID)
1132         return true;
1133
1134     darray_enumerate_from(i, groupi, keyi->groups, 1) {
1135         if (groupi->defined) {
1136             warn = true;
1137             ClearGroupInfo(groupi);
1138             InitGroupInfo(groupi);
1139         }
1140     }
1141
1142     if (warn) {
1143         log_warn(info->ctx,
1144                  XKB_WARNING_MULTIPLE_GROUPS_AT_ONCE,
1145                  "For the map %s an explicit group specified, "
1146                  "but key %s has more than one group defined; "
1147                  "All groups except first one will be ignored\n",
1148                  info->name, KeyInfoText(info, keyi));
1149     }
1150
1151     darray_resize0(keyi->groups, info->explicit_group + 1);
1152     if (info->explicit_group > 0) {
1153         darray_item(keyi->groups, info->explicit_group) =
1154             darray_item(keyi->groups, 0);
1155         InitGroupInfo(&darray_item(keyi->groups, 0));
1156     }
1157
1158     return true;
1159 }
1160
1161 static bool
1162 HandleSymbolsDef(SymbolsInfo *info, SymbolsDef *stmt)
1163 {
1164     KeyInfo keyi;
1165
1166     keyi = info->default_key;
1167     darray_init(keyi.groups);
1168     darray_copy(keyi.groups, info->default_key.groups);
1169     for (xkb_layout_index_t i = 0; i < darray_size(keyi.groups); i++)
1170         CopyGroupInfo(&darray_item(keyi.groups, i),
1171                       &darray_item(info->default_key.groups, i));
1172     keyi.merge = stmt->merge;
1173     keyi.name = stmt->keyName;
1174
1175     if (!HandleSymbolsBody(info, stmt->symbols, &keyi)) {
1176         info->errorCount++;
1177         return false;
1178     }
1179
1180     if (!SetExplicitGroup(info, &keyi)) {
1181         info->errorCount++;
1182         return false;
1183     }
1184
1185     if (!AddKeySymbols(info, &keyi, true)) {
1186         info->errorCount++;
1187         return false;
1188     }
1189
1190     return true;
1191 }
1192
1193 static bool
1194 HandleModMapDef(SymbolsInfo *info, ModMapDef *def)
1195 {
1196     ModMapEntry tmp;
1197     xkb_mod_index_t ndx;
1198     bool ok;
1199     struct xkb_context *ctx = info->ctx;
1200     const char *modifier_name = xkb_atom_text(ctx, def->modifier);
1201
1202     if (istreq(modifier_name, "none")) {
1203         // Handle special "None" entry
1204         ndx = XKB_MOD_NONE;
1205     } else {
1206         // Handle normal entry
1207         ndx = XkbModNameToIndex(&info->mods, def->modifier, MOD_REAL);
1208         if (ndx == XKB_MOD_INVALID) {
1209             log_err(info->ctx,
1210                     XKB_ERROR_INVALID_REAL_MODIFIER,
1211                     "Illegal modifier map definition; "
1212                     "Ignoring map for non-modifier \"%s\"\n",
1213                     xkb_atom_text(ctx, def->modifier));
1214             return false;
1215         }
1216     }
1217
1218     ok = true;
1219     tmp.modifier = ndx;
1220     tmp.merge = def->merge;
1221
1222     for (ExprDef *key = def->keys; key; key = (ExprDef *) key->common.next) {
1223         xkb_keysym_t sym;
1224
1225         if (key->expr.op == EXPR_VALUE &&
1226             key->expr.value_type == EXPR_TYPE_KEYNAME) {
1227             tmp.haveSymbol = false;
1228             tmp.u.keyName = key->key_name.key_name;
1229         }
1230         else if (ExprResolveKeySym(ctx, key, &sym)) {
1231             tmp.haveSymbol = true;
1232             tmp.u.keySym = sym;
1233         }
1234         else {
1235             log_err(info->ctx,
1236                     XKB_ERROR_INVALID_MODMAP_ENTRY,
1237                     "Modmap entries may contain only key names or keysyms; "
1238                     "Illegal definition for %s modifier ignored\n",
1239                     ModIndexText(info->ctx, &info->mods, tmp.modifier));
1240             continue;
1241         }
1242
1243         ok = AddModMapEntry(info, &tmp) && ok;
1244     }
1245     return ok;
1246 }
1247
1248 static void
1249 HandleSymbolsFile(SymbolsInfo *info, XkbFile *file, enum merge_mode merge)
1250 {
1251     bool ok;
1252
1253     free(info->name);
1254     info->name = strdup_safe(file->name);
1255
1256     for (ParseCommon *stmt = file->defs; stmt; stmt = stmt->next) {
1257         switch (stmt->type) {
1258         case STMT_INCLUDE:
1259             ok = HandleIncludeSymbols(info, (IncludeStmt *) stmt);
1260             break;
1261         case STMT_SYMBOLS:
1262             ok = HandleSymbolsDef(info, (SymbolsDef *) stmt);
1263             break;
1264         case STMT_VAR:
1265             ok = HandleGlobalVar(info, (VarDef *) stmt);
1266             break;
1267         case STMT_VMOD:
1268             ok = HandleVModDef(info->ctx, &info->mods, (VModDef *) stmt, merge);
1269             break;
1270         case STMT_MODMAP:
1271             ok = HandleModMapDef(info, (ModMapDef *) stmt);
1272             break;
1273         default:
1274             log_err(info->ctx,
1275                     XKB_ERROR_WRONG_STATEMENT_TYPE,
1276                     "Symbols files may not include other types; "
1277                     "Ignoring %s\n", stmt_type_to_string(stmt->type));
1278             ok = false;
1279             break;
1280         }
1281
1282         if (!ok)
1283             info->errorCount++;
1284
1285         if (info->errorCount > 10) {
1286             log_err(info->ctx,
1287                     XKB_ERROR_INVALID_SYNTAX,
1288                     "Abandoning symbols file \"%s\"\n",
1289                     file->name);
1290             break;
1291         }
1292     }
1293 }
1294
1295 /**
1296  * Given a keysym @sym, return a key which generates it, or NULL.
1297  * This is used for example in a modifier map definition, such as:
1298  *      modifier_map Lock           { Caps_Lock };
1299  * where we want to add the Lock modifier to the modmap of the key
1300  * which matches the keysym Caps_Lock.
1301  * Since there can be many keys which generates the keysym, the key
1302  * is chosen first by lowest group in which the keysym appears, than
1303  * by lowest level and than by lowest key code.
1304  */
1305 static struct xkb_key *
1306 FindKeyForSymbol(struct xkb_keymap *keymap, xkb_keysym_t sym)
1307 {
1308     struct xkb_key *key;
1309     xkb_layout_index_t group;
1310     bool got_one_group, got_one_level;
1311
1312     group = 0;
1313     do {
1314         xkb_level_index_t level = 0;
1315         got_one_group = false;
1316         do {
1317             got_one_level = false;
1318             xkb_keys_foreach(key, keymap) {
1319                 if (group < key->num_groups &&
1320                     level < XkbKeyNumLevels(key, group)) {
1321                     got_one_group = got_one_level = true;
1322                     if (key->groups[group].levels[level].num_syms == 1 &&
1323                         key->groups[group].levels[level].u.sym == sym)
1324                         return key;
1325                 }
1326             }
1327             level++;
1328         } while (got_one_level);
1329         group++;
1330     } while (got_one_group);
1331
1332     return NULL;
1333 }
1334
1335 /*
1336  * Find an appropriate type for a group and return its name.
1337  *
1338  * Simple recipe:
1339  * - ONE_LEVEL for width 0/1
1340  * - ALPHABETIC for 2 shift levels, with lower/upercase keysyms
1341  * - KEYPAD for keypad keys.
1342  * - TWO_LEVEL for other 2 shift level keys.
1343  * and the same for four level keys.
1344  *
1345  * FIXME: Decide how to handle multiple-syms-per-level, and do it.
1346  */
1347 static xkb_atom_t
1348 FindAutomaticType(struct xkb_context *ctx, GroupInfo *groupi)
1349 {
1350     xkb_keysym_t sym0, sym1;
1351     const xkb_level_index_t width = darray_size(groupi->levels);
1352
1353 #define GET_SYM(level) \
1354     (darray_item(groupi->levels, level).num_syms == 0 ? \
1355         XKB_KEY_NoSymbol : \
1356      darray_item(groupi->levels, level).num_syms == 1 ? \
1357         darray_item(groupi->levels, level).u.sym : \
1358      /* num_syms > 1 */ \
1359         darray_item(groupi->levels, level).u.syms[0])
1360
1361     if (width == 1 || width <= 0)
1362         return xkb_atom_intern_literal(ctx, "ONE_LEVEL");
1363
1364     sym0 = GET_SYM(0);
1365     sym1 = GET_SYM(1);
1366
1367     if (width == 2) {
1368         if (xkb_keysym_is_lower(sym0) && xkb_keysym_is_upper(sym1))
1369             return xkb_atom_intern_literal(ctx, "ALPHABETIC");
1370
1371         if (xkb_keysym_is_keypad(sym0) || xkb_keysym_is_keypad(sym1))
1372             return xkb_atom_intern_literal(ctx, "KEYPAD");
1373
1374         return xkb_atom_intern_literal(ctx, "TWO_LEVEL");
1375     }
1376
1377     if (width <= 4) {
1378         if (xkb_keysym_is_lower(sym0) && xkb_keysym_is_upper(sym1)) {
1379             xkb_keysym_t sym2, sym3;
1380             sym2 = GET_SYM(2);
1381             sym3 = (width == 4 ? GET_SYM(3) : XKB_KEY_NoSymbol);
1382
1383             if (xkb_keysym_is_lower(sym2) && xkb_keysym_is_upper(sym3))
1384                 return xkb_atom_intern_literal(ctx, "FOUR_LEVEL_ALPHABETIC");
1385
1386             return xkb_atom_intern_literal(ctx, "FOUR_LEVEL_SEMIALPHABETIC");
1387         }
1388
1389         if (xkb_keysym_is_keypad(sym0) || xkb_keysym_is_keypad(sym1))
1390             return xkb_atom_intern_literal(ctx, "FOUR_LEVEL_KEYPAD");
1391
1392         return xkb_atom_intern_literal(ctx, "FOUR_LEVEL");
1393     }
1394
1395     return XKB_ATOM_NONE;
1396
1397 #undef GET_SYM
1398 }
1399
1400 static const struct xkb_key_type *
1401 FindTypeForGroup(struct xkb_keymap *keymap, KeyInfo *keyi,
1402                  xkb_layout_index_t group, bool *explicit_type)
1403 {
1404     unsigned int i;
1405     GroupInfo *groupi = &darray_item(keyi->groups, group);
1406     xkb_atom_t type_name = groupi->type;
1407
1408     *explicit_type = true;
1409
1410     if (type_name == XKB_ATOM_NONE) {
1411         if (keyi->default_type != XKB_ATOM_NONE) {
1412             type_name  = keyi->default_type;
1413         }
1414         else {
1415             type_name = FindAutomaticType(keymap->ctx, groupi);
1416             if (type_name != XKB_ATOM_NONE)
1417                 *explicit_type = false;
1418         }
1419     }
1420
1421     if (type_name == XKB_ATOM_NONE) {
1422         log_warn(keymap->ctx,
1423                  XKB_WARNING_CANNOT_INFER_KEY_TYPE,
1424                  "Couldn't find an automatic type for key '%s' group %d with %lu levels; "
1425                  "Using the default type\n",
1426                  KeyNameText(keymap->ctx, keyi->name), group + 1,
1427                  (unsigned long) darray_size(groupi->levels));
1428         goto use_default;
1429     }
1430
1431     for (i = 0; i < keymap->num_types; i++)
1432         if (keymap->types[i].name == type_name)
1433             break;
1434
1435     if (i >= keymap->num_types) {
1436         log_warn(keymap->ctx,
1437                  XKB_WARNING_UNDEFINED_KEY_TYPE,
1438                  "The type \"%s\" for key '%s' group %d was not previously defined; "
1439                  "Using the default type\n",
1440                  xkb_atom_text(keymap->ctx, type_name),
1441                  KeyNameText(keymap->ctx, keyi->name), group + 1);
1442         goto use_default;
1443     }
1444
1445     return &keymap->types[i];
1446
1447 use_default:
1448     /*
1449      * Index 0 is guaranteed to contain something, usually
1450      * ONE_LEVEL or at least some default one-level type.
1451      */
1452     return &keymap->types[0];
1453 }
1454
1455 static bool
1456 CopySymbolsDefToKeymap(struct xkb_keymap *keymap, SymbolsInfo *info,
1457                        KeyInfo *keyi)
1458 {
1459     struct xkb_key *key;
1460     GroupInfo *groupi;
1461     const GroupInfo *group0;
1462     xkb_layout_index_t i;
1463
1464     /*
1465      * The name is guaranteed to be real and not an alias (see
1466      * AddKeySymbols), so 'false' is safe here.
1467      */
1468     key = XkbKeyByName(keymap, keyi->name, false);
1469     if (!key) {
1470         log_vrb(info->ctx, 5,
1471                 XKB_WARNING_UNDEFINED_KEYCODE,
1472                 "Key %s not found in keycodes; Symbols ignored\n",
1473                 KeyInfoText(info, keyi));
1474         return false;
1475     }
1476
1477     /* Find the range of groups we need. */
1478     key->num_groups = 0;
1479     darray_enumerate(i, groupi, keyi->groups)
1480         if (groupi->defined)
1481             key->num_groups = i + 1;
1482
1483     if (key->num_groups <= 0)
1484         return false; /* WSGO */
1485
1486     darray_resize(keyi->groups, key->num_groups);
1487
1488     /*
1489      * If there are empty groups between non-empty ones, fill them with data
1490      * from the first group.
1491      * We can make a wrong assumption here. But leaving gaps is worse.
1492      */
1493     group0 = &darray_item(keyi->groups, 0);
1494     darray_foreach_from(groupi, keyi->groups, 1) {
1495         if (groupi->defined)
1496             continue;
1497
1498         CopyGroupInfo(groupi, group0);
1499     }
1500
1501     key->groups = calloc(key->num_groups, sizeof(*key->groups));
1502     if (!key->groups) {
1503         log_err(info->ctx, "Failed to allocate memory for key->groups\n");
1504         return false;
1505     }
1506
1507     /* Find and assign the groups' types in the keymap. */
1508     darray_enumerate(i, groupi, keyi->groups) {
1509         const struct xkb_key_type *type;
1510         bool explicit_type;
1511
1512         type = FindTypeForGroup(keymap, keyi, i, &explicit_type);
1513
1514         /* Always have as many levels as the type specifies. */
1515         if (type->num_levels < darray_size(groupi->levels)) {
1516             struct xkb_level *leveli;
1517
1518             log_vrb(info->ctx, 1,
1519                     XKB_WARNING_EXTRA_SYMBOLS_IGNORED,
1520                     "Type \"%s\" has %d levels, but %s has %d levels; "
1521                     "Ignoring extra symbols\n",
1522                     xkb_atom_text(keymap->ctx, type->name), type->num_levels,
1523                     KeyInfoText(info, keyi),
1524                     (int) darray_size(groupi->levels));
1525
1526             darray_foreach_from(leveli, groupi->levels, type->num_levels)
1527                 ClearLevelInfo(leveli);
1528         }
1529         darray_resize0(groupi->levels, type->num_levels);
1530
1531         key->groups[i].explicit_type = explicit_type;
1532         key->groups[i].type = type;
1533     }
1534
1535     /* Copy levels. */
1536     darray_enumerate(i, groupi, keyi->groups)
1537         darray_steal(groupi->levels, &key->groups[i].levels, NULL);
1538
1539     key->out_of_range_group_number = keyi->out_of_range_group_number;
1540     key->out_of_range_group_action = keyi->out_of_range_group_action;
1541
1542     if (keyi->defined & KEY_FIELD_VMODMAP) {
1543         key->vmodmap = keyi->vmodmap;
1544         key->explicit |= EXPLICIT_VMODMAP;
1545     }
1546
1547     if (keyi->repeat != KEY_REPEAT_UNDEFINED) {
1548         key->repeats = (keyi->repeat == KEY_REPEAT_YES);
1549         key->explicit |= EXPLICIT_REPEAT;
1550     }
1551
1552     darray_foreach(groupi, keyi->groups) {
1553         if (groupi->defined & GROUP_FIELD_ACTS) {
1554             key->explicit |= EXPLICIT_INTERP;
1555             break;
1556         }
1557     }
1558
1559     return true;
1560 }
1561
1562 static bool
1563 CopyModMapDefToKeymap(struct xkb_keymap *keymap, SymbolsInfo *info,
1564                       ModMapEntry *entry)
1565 {
1566     struct xkb_key *key;
1567
1568     if (!entry->haveSymbol) {
1569         key = XkbKeyByName(keymap, entry->u.keyName, true);
1570         if (!key) {
1571             log_vrb(info->ctx, 5,
1572                     XKB_WARNING_UNDEFINED_KEYCODE,
1573                     "Key %s not found in keycodes; "
1574                     "Modifier map entry for %s not updated\n",
1575                     KeyNameText(info->ctx, entry->u.keyName),
1576                     ModIndexText(info->ctx, &info->mods, entry->modifier));
1577             return false;
1578         }
1579     }
1580     else {
1581         key = FindKeyForSymbol(keymap, entry->u.keySym);
1582         if (!key) {
1583             log_vrb(info->ctx, 5,
1584                     XKB_WARNING_UNRESOLVED_KEYMAP_SYMBOL,
1585                     "Key \"%s\" not found in symbol map; "
1586                     "Modifier map entry for %s not updated\n",
1587                     KeysymText(info->ctx, entry->u.keySym),
1588                     ModIndexText(info->ctx, &info->mods, entry->modifier));
1589             return false;
1590         }
1591     }
1592
1593     // Handle modMap None
1594     if (entry->modifier != XKB_MOD_NONE) {
1595         // Convert modifier index to modifier mask
1596         key->modmap |= (1u << entry->modifier);
1597     }
1598
1599     return true;
1600 }
1601
1602 static bool
1603 CopySymbolsToKeymap(struct xkb_keymap *keymap, SymbolsInfo *info)
1604 {
1605     KeyInfo *keyi;
1606     ModMapEntry *mm;
1607
1608     keymap->symbols_section_name = strdup_safe(info->name);
1609     XkbEscapeMapName(keymap->symbols_section_name);
1610
1611     keymap->mods = info->mods;
1612
1613     darray_steal(info->group_names,
1614                  &keymap->group_names, &keymap->num_group_names);
1615
1616     darray_foreach(keyi, info->keys)
1617         if (!CopySymbolsDefToKeymap(keymap, info, keyi))
1618             info->errorCount++;
1619
1620     if (xkb_context_get_log_verbosity(keymap->ctx) > 3) {
1621         struct xkb_key *key;
1622
1623         xkb_keys_foreach(key, keymap) {
1624             if (key->name == XKB_ATOM_NONE)
1625                 continue;
1626
1627             if (key->num_groups < 1)
1628                 log_info(info->ctx, XKB_LOG_MESSAGE_NO_ID,
1629                          "No symbols defined for %s\n",
1630                          KeyNameText(info->ctx, key->name));
1631         }
1632     }
1633
1634     darray_foreach(mm, info->modmaps)
1635         if (!CopyModMapDefToKeymap(keymap, info, mm))
1636             info->errorCount++;
1637
1638     /* XXX: If we don't ignore errorCount, things break. */
1639     return true;
1640 }
1641
1642 bool
1643 CompileSymbols(XkbFile *file, struct xkb_keymap *keymap,
1644                enum merge_mode merge)
1645 {
1646     SymbolsInfo info;
1647     ActionsInfo *actions;
1648
1649     actions = NewActionsInfo();
1650     if (!actions)
1651         return false;
1652
1653     InitSymbolsInfo(&info, keymap, actions, &keymap->mods);
1654     info.default_key.merge = merge;
1655
1656     HandleSymbolsFile(&info, file, merge);
1657
1658     if (info.errorCount != 0)
1659         goto err_info;
1660
1661     if (!CopySymbolsToKeymap(keymap, &info))
1662         goto err_info;
1663
1664     ClearSymbolsInfo(&info);
1665     FreeActionsInfo(actions);
1666     return true;
1667
1668 err_info:
1669     FreeActionsInfo(actions);
1670     ClearSymbolsInfo(&info);
1671     return false;
1672 }