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