symbols: remove unneeded optimization
[platform/upstream/libxkbcommon.git] / src / xkbcomp / symbols.c
1 /************************************************************
2  * Copyright (c) 1994 by Silicon Graphics Computer Systems, Inc.
3  *
4  * Permission to use, copy, modify, and distribute this
5  * software and its documentation for any purpose and without
6  * fee is hereby granted, provided that the above copyright
7  * notice appear in all copies and that both that copyright
8  * notice and this permission notice appear in supporting
9  * documentation, and that the name of Silicon Graphics not be
10  * used in advertising or publicity pertaining to distribution
11  * of the software without specific prior written permission.
12  * Silicon Graphics makes no representation about the suitability
13  * of this software for any purpose. It is provided "as is"
14  * without any express or implied warranty.
15  *
16  * SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
17  * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
18  * AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
19  * GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
20  * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
21  * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
22  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION  WITH
23  * THE USE OR PERFORMANCE OF THIS SOFTWARE.
24  *
25  ********************************************************/
26
27 /*
28  * Copyright © 2012 Intel Corporation
29  * Copyright © 2012 Ran Benita <ran234@gmail.com>
30  *
31  * Permission is hereby granted, free of charge, to any person obtaining a
32  * copy of this software and associated documentation files (the "Software"),
33  * to deal in the Software without restriction, including without limitation
34  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
35  * and/or sell copies of the Software, and to permit persons to whom the
36  * Software is furnished to do so, subject to the following conditions:
37  *
38  * The above copyright notice and this permission notice (including the next
39  * paragraph) shall be included in all copies or substantial portions of the
40  * Software.
41  *
42  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
43  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
44  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
45  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
46  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
47  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
48  * DEALINGS IN THE SOFTWARE.
49  *
50  * Author: Daniel Stone <daniel@fooishbar.org>
51  *         Ran Benita <ran234@gmail.com>
52  */
53
54 #include "xkbcomp-priv.h"
55 #include "text.h"
56 #include "expr.h"
57 #include "action.h"
58 #include "vmod.h"
59 #include "keycodes.h"
60 #include "include.h"
61 #include "keysym.h"
62
63 enum key_repeat {
64     KEY_REPEAT_UNDEFINED = 0,
65     KEY_REPEAT_YES = 1,
66     KEY_REPEAT_NO = 2,
67 };
68
69 enum group_field {
70     GROUP_FIELD_SYMS = (1 << 0),
71     GROUP_FIELD_ACTS = (1 << 1),
72     GROUP_FIELD_TYPE = (1 << 2),
73 };
74
75 enum key_field {
76     KEY_FIELD_REPEAT    = (1 << 0),
77     KEY_FIELD_TYPE_DFLT = (1 << 1),
78     KEY_FIELD_GROUPINFO = (1 << 2),
79     KEY_FIELD_VMODMAP   = (1 << 3),
80 };
81
82 typedef struct {
83     unsigned int num_syms;
84     unsigned int sym_index;
85     union xkb_action act;
86 } LevelInfo;
87
88 typedef darray(xkb_keysym_t) darray_xkb_keysym_t;
89
90 typedef struct {
91     enum group_field defined;
92     darray_xkb_keysym_t syms;
93     darray(LevelInfo) levels;
94     xkb_atom_t type;
95 } GroupInfo;
96
97 typedef struct _KeyInfo {
98     enum key_field defined;
99     unsigned file_id;
100     enum merge_mode merge;
101
102     unsigned long name; /* the 4 chars of the key name, as long */
103
104     darray(GroupInfo) groups;
105
106     enum key_repeat repeat;
107     xkb_mod_mask_t vmodmap;
108     xkb_atom_t dfltType;
109
110     enum xkb_range_exceed_type out_of_range_group_action;
111     xkb_layout_index_t out_of_range_group_number;
112 } KeyInfo;
113
114 static void
115 InitGroupInfo(GroupInfo *groupi)
116 {
117     memset(groupi, 0, sizeof(*groupi));
118 }
119
120 static void
121 ClearGroupInfo(GroupInfo *groupi)
122 {
123     darray_free(groupi->syms);
124     darray_free(groupi->levels);
125 }
126
127 static void
128 InitKeyInfo(KeyInfo *keyi, unsigned file_id)
129 {
130     static const char dflt_key_name[XKB_KEY_NAME_LENGTH] = "*";
131
132     memset(keyi, 0, sizeof(*keyi));
133     keyi->file_id = file_id;
134     keyi->merge = MERGE_OVERRIDE;
135     keyi->name = KeyNameToLong(dflt_key_name);
136     keyi->out_of_range_group_action = RANGE_WRAP;
137 }
138
139 static void
140 ClearKeyInfo(KeyInfo *keyi)
141 {
142     GroupInfo *groupi;
143     darray_foreach(groupi, keyi->groups)
144         ClearGroupInfo(groupi);
145     darray_free(keyi->groups);
146 }
147
148 /***====================================================================***/
149
150 typedef struct _ModMapEntry {
151     enum merge_mode merge;
152     bool haveSymbol;
153     int modifier;
154     union {
155         unsigned long keyName;
156         xkb_keysym_t keySym;
157     } u;
158 } ModMapEntry;
159
160 typedef struct _SymbolsInfo {
161     char *name;         /* e.g. pc+us+inet(evdev) */
162     int errorCount;
163     unsigned file_id;
164     enum merge_mode merge;
165     xkb_layout_index_t explicit_group;
166     darray(KeyInfo) keys;
167     KeyInfo dflt;
168     VModInfo vmods;
169     ActionsInfo *actions;
170     darray_xkb_atom_t group_names;
171     darray(ModMapEntry) modMaps;
172
173     struct xkb_keymap *keymap;
174 } SymbolsInfo;
175
176 static void
177 InitSymbolsInfo(SymbolsInfo *info, struct xkb_keymap *keymap,
178                 unsigned file_id, ActionsInfo *actions)
179 {
180     memset(info, 0, sizeof(*info));
181     info->keymap = keymap;
182     info->file_id = file_id;
183     info->merge = MERGE_OVERRIDE;
184     InitKeyInfo(&info->dflt, file_id);
185     InitVModInfo(&info->vmods, keymap);
186     info->actions = actions;
187     info->explicit_group = XKB_LAYOUT_INVALID;
188 }
189
190 static void
191 ClearSymbolsInfo(SymbolsInfo * info)
192 {
193     KeyInfo *keyi;
194     free(info->name);
195     darray_foreach(keyi, info->keys)
196         ClearKeyInfo(keyi);
197     darray_free(info->keys);
198     darray_free(info->group_names);
199     darray_free(info->modMaps);
200     ClearKeyInfo(&info->dflt);
201 }
202
203 static bool
204 MergeGroups(SymbolsInfo *info, GroupInfo *into, GroupInfo *from, bool clobber,
205             bool report, xkb_layout_index_t group, unsigned long key_name)
206 {
207     xkb_level_index_t i, numLevels;
208     enum { INTO = (1 << 0), FROM = (1 << 1) } using;
209
210     /* First find the type of the merged group. */
211     if (into->type != from->type) {
212         if (from->type == XKB_ATOM_NONE) {
213         }
214         else if (into->type == XKB_ATOM_NONE) {
215             into->type = from->type;
216         }
217         else {
218             xkb_atom_t use = (clobber ? from->type : into->type);
219             xkb_atom_t ignore = (clobber ? into->type : from->type);
220
221             if (report)
222                 log_warn(info->keymap->ctx,
223                          "Multiple definitions for group %d type of key %s; "
224                          "Using %s, ignoring %s\n",
225                          group + 1, LongKeyNameText(key_name),
226                          xkb_atom_text(info->keymap->ctx, use),
227                          xkb_atom_text(info->keymap->ctx, ignore));
228
229             into->type = use;
230         }
231     }
232     into->defined |= (from->defined & GROUP_FIELD_TYPE);
233
234     /* Now look at the levels. */
235
236     if (darray_empty(from->levels)) {
237         InitGroupInfo(from);
238         return true;
239     }
240
241     if (darray_empty(into->levels)) {
242         from->type = into->type;
243         *into = *from;
244         InitGroupInfo(from);
245         return true;
246     }
247
248     /* First we merge the actions and ensure @into has all the levels. */
249     numLevels = MAX(darray_size(into->levels), darray_size(from->levels));
250     for (i = 0; i < numLevels; i++) {
251         union xkb_action *intoAct, *fromAct;
252
253         if (i >= darray_size(from->levels))
254             continue;
255
256         if (i >= darray_size(into->levels)) {
257             darray_append(into->levels, darray_item(from->levels, i));
258             darray_item(into->levels, i).num_syms = 0;
259             darray_item(into->levels, i).sym_index = 0;
260             continue;
261         }
262
263         intoAct = &darray_item(into->levels, i).act;
264         fromAct = &darray_item(from->levels, i).act;
265
266         if (fromAct->type == ACTION_TYPE_NONE) {
267         }
268         else if (intoAct->type == ACTION_TYPE_NONE) {
269             *intoAct = *fromAct;
270         }
271         else {
272             union xkb_action *use = (clobber ? fromAct : intoAct);
273             union xkb_action *ignore = (clobber ? intoAct : fromAct);
274
275             if (report)
276                 log_warn(info->keymap->ctx,
277                          "Multiple actions for level %d/group %u on key %s; "
278                          "Using %s, ignoring %s\n",
279                          i + 1, group + 1, LongKeyNameText(key_name),
280                          ActionTypeText(use->type),
281                          ActionTypeText(ignore->type));
282
283             *intoAct = *use;
284         }
285     }
286     into->defined |= (from->defined & GROUP_FIELD_ACTS);
287
288     /* Then merge the keysyms. */
289
290     /*
291      * We want to avoid copying and allocating if not necessary. So
292      * here we do a pre-scan of the levels to check if we'll only use
293      * @into's or @from's keysyms, and if so we'll just assign them.
294      * However if one level uses @into's and another uses @from's, we
295      * will need to construct a new syms array.
296      */
297     using = 0;
298     for (i = 0; i < numLevels; i++) {
299         unsigned int intoSize, fromSize;
300
301         intoSize = darray_item(into->levels, i).num_syms;
302         if (i < darray_size(from->levels))
303             fromSize = darray_item(from->levels, i).num_syms;
304         else
305             fromSize = 0;
306
307         if (intoSize == 0 && fromSize == 0)
308             using |= 0;
309         else if (intoSize == 0)
310             using |= FROM;
311         else if (fromSize == 0)
312             using |= INTO;
313         else
314             using |= (clobber ? FROM : INTO);
315     }
316
317     if (using == 0 || using == INTO) {
318     }
319     else if (using == FROM) {
320         darray_free(into->syms);
321         into->syms = from->syms;
322         darray_init(from->syms);
323         for (i = 0; i < darray_size(from->levels); i++) {
324             darray_item(into->levels, i).num_syms =
325                 darray_item(from->levels, i).num_syms;
326             darray_item(into->levels, i).sym_index =
327                 darray_item(from->levels, i).sym_index;
328         }
329     }
330     else {
331         darray_xkb_keysym_t syms = darray_new();
332
333         for (i = 0; i < numLevels; i++) {
334             unsigned int intoSize, fromSize;
335
336             intoSize = darray_item(into->levels, i).num_syms;
337             if (i < darray_size(from->levels))
338                 fromSize = darray_item(from->levels, i).num_syms;
339             else
340                 fromSize = 0;
341
342             /* Empty level. */
343             if (intoSize == 0 && fromSize == 0)
344                 continue;
345
346             if (intoSize != 0 && fromSize != 0 && report)
347                 log_info(info->keymap->ctx,
348                          "Multiple symbols for group %u, level %d on key %s; "
349                          "Using %s, ignoring %s\n",
350                          group + 1, i + 1, LongKeyNameText(key_name),
351                          (clobber ? "from" : "to"),
352                          (clobber ? "to" : "from"));
353
354             if (intoSize == 0 || (fromSize != 0 && clobber)) {
355                 unsigned sym_index = darray_item(from->levels, i).sym_index;
356                 darray_item(into->levels, i).sym_index = darray_size(syms);
357                 darray_item(into->levels, i).num_syms = fromSize;
358                 darray_append_items(syms, &darray_item(from->syms, sym_index),
359                                     fromSize);
360             }
361             else
362             {
363                 unsigned sym_index = darray_item(into->levels, i).sym_index;
364                 darray_item(into->levels, i).sym_index = darray_size(syms);
365                 darray_item(into->levels, i).num_syms = intoSize;
366                 darray_append_items(syms, &darray_item(into->syms, sym_index),
367                                     intoSize);
368             }
369         }
370         darray_free(into->syms);
371         into->syms = syms;
372     }
373     into->defined |= (from->defined & GROUP_FIELD_SYMS);
374
375     return true;
376 }
377
378 static bool
379 UseNewKeyField(enum key_field field, enum key_field old, enum key_field new,
380                bool clobber, bool report, enum key_field *collide)
381 {
382     if (!(old & field))
383         return (new & field);
384
385     if (new & field) {
386         if (report)
387             *collide |= field;
388
389         if (clobber)
390             return true;
391     }
392
393     return false;
394 }
395
396
397 static bool
398 MergeKeys(SymbolsInfo *info, KeyInfo *into, KeyInfo *from)
399 {
400     xkb_layout_index_t i;
401     xkb_layout_index_t groups_in_both;
402     enum key_field collide = 0;
403     bool clobber, report;
404     int verbosity = xkb_context_get_log_verbosity(info->keymap->ctx);
405
406     if (from->merge == MERGE_REPLACE) {
407         ClearKeyInfo(into);
408         *into = *from;
409         InitKeyInfo(from, info->file_id);
410         return true;
411     }
412
413     clobber = (from->merge != MERGE_AUGMENT);
414     report = (verbosity > 9 ||
415               (into->file_id == from->file_id && verbosity > 0));
416
417     groups_in_both = MIN(darray_size(into->groups),
418                          darray_size(from->groups));
419     for (i = 0; i < groups_in_both; i++)
420         MergeGroups(info,
421                     &darray_item(into->groups, i),
422                     &darray_item(from->groups, i),
423                     clobber, report, i, into->name);
424     /* If @from has extra groups, just move them to @into. */
425     for (i = groups_in_both; i < darray_size(from->groups); i++) {
426         darray_append(into->groups, darray_item(from->groups, i));
427         InitGroupInfo(&darray_item(from->groups, i));
428     }
429
430     if (UseNewKeyField(KEY_FIELD_VMODMAP, into->defined, from->defined,
431                        clobber, report, &collide)) {
432         into->vmodmap = from->vmodmap;
433         into->defined |= KEY_FIELD_VMODMAP;
434     }
435     if (UseNewKeyField(KEY_FIELD_REPEAT, into->defined, from->defined,
436                        clobber, report, &collide)) {
437         into->repeat = from->repeat;
438         into->defined |= KEY_FIELD_REPEAT;
439     }
440     if (UseNewKeyField(KEY_FIELD_TYPE_DFLT, into->defined, from->defined,
441                        clobber, report, &collide)) {
442         into->dfltType = from->dfltType;
443         into->defined |= KEY_FIELD_TYPE_DFLT;
444     }
445     if (UseNewKeyField(KEY_FIELD_GROUPINFO, into->defined, from->defined,
446                        clobber, report, &collide)) {
447         into->out_of_range_group_action = from->out_of_range_group_action;
448         into->out_of_range_group_number = from->out_of_range_group_number;
449         into->defined |= KEY_FIELD_GROUPINFO;
450     }
451
452     if (collide)
453         log_warn(info->keymap->ctx,
454                  "Symbol map for key %s redefined; "
455                  "Using %s definition for conflicting fields\n",
456                  LongKeyNameText(into->name),
457                  (clobber ? "first" : "last"));
458
459     ClearKeyInfo(from);
460     InitKeyInfo(from, info->file_id);
461     return true;
462 }
463
464 static bool
465 AddKeySymbols(SymbolsInfo *info, KeyInfo *keyi)
466 {
467     unsigned long real_name;
468     KeyInfo *iter;
469
470     /*
471      * Don't keep aliases in the keys array; this guarantees that
472      * searching for keys to merge with by straight comparison (see the
473      * following loop) is enough, and we won't get multiple KeyInfo's
474      * for the same key because of aliases.
475      */
476     if (FindKeyNameForAlias(info->keymap, keyi->name, &real_name))
477         keyi->name = real_name;
478
479     darray_foreach(iter, info->keys)
480         if (iter->name == keyi->name)
481             return MergeKeys(info, iter, keyi);
482
483     darray_append(info->keys, *keyi);
484     InitKeyInfo(keyi, info->file_id);
485     return true;
486 }
487
488 static bool
489 AddModMapEntry(SymbolsInfo * info, ModMapEntry * new)
490 {
491     ModMapEntry *mm;
492     bool clobber;
493
494     clobber = (new->merge != MERGE_AUGMENT);
495     darray_foreach(mm, info->modMaps) {
496         if (new->haveSymbol && mm->haveSymbol
497             && (new->u.keySym == mm->u.keySym)) {
498             unsigned use, ignore;
499             if (mm->modifier != new->modifier) {
500                 if (clobber) {
501                     use = new->modifier;
502                     ignore = mm->modifier;
503                 }
504                 else {
505                     use = mm->modifier;
506                     ignore = new->modifier;
507                 }
508                 log_err(info->keymap->ctx,
509                         "%s added to symbol map for multiple modifiers; "
510                         "Using %s, ignoring %s.\n",
511                         KeysymText(new->u.keySym), ModIndexText(use),
512                         ModIndexText(ignore));
513                 mm->modifier = use;
514             }
515             return true;
516         }
517         if ((!new->haveSymbol) && (!mm->haveSymbol) &&
518             (new->u.keyName == mm->u.keyName)) {
519             unsigned use, ignore;
520             if (mm->modifier != new->modifier) {
521                 if (clobber) {
522                     use = new->modifier;
523                     ignore = mm->modifier;
524                 }
525                 else {
526                     use = mm->modifier;
527                     ignore = new->modifier;
528                 }
529                 log_err(info->keymap->ctx,
530                         "Key %s added to map for multiple modifiers; "
531                         "Using %s, ignoring %s.\n",
532                         LongKeyNameText(new->u.keyName), ModIndexText(use),
533                         ModIndexText(ignore));
534                 mm->modifier = use;
535             }
536             return true;
537         }
538     }
539
540     darray_append(info->modMaps, *new);
541     return true;
542 }
543
544 /***====================================================================***/
545
546 static void
547 MergeIncludedSymbols(SymbolsInfo *into, SymbolsInfo *from,
548                      enum merge_mode merge)
549 {
550     unsigned int i;
551     KeyInfo *keyi;
552     ModMapEntry *mm;
553     xkb_atom_t *group_name;
554     xkb_layout_index_t group_names_in_both;
555
556     if (from->errorCount > 0) {
557         into->errorCount += from->errorCount;
558         return;
559     }
560
561     if (into->name == NULL) {
562         into->name = from->name;
563         from->name = NULL;
564     }
565
566     group_names_in_both = MIN(darray_size(into->group_names),
567                               darray_size(from->group_names));
568     for (i = 0; i < group_names_in_both; i++) {
569         if (!darray_item(from->group_names, i))
570             continue;
571
572         if (merge == MERGE_AUGMENT && darray_item(into->group_names, i))
573             continue;
574
575         darray_item(into->group_names, i) = darray_item(from->group_names, i);
576     }
577     /* If @from has more, get them as well. */
578     darray_foreach_from(group_name, from->group_names, group_names_in_both)
579         darray_append(into->group_names, *group_name);
580
581     darray_foreach(keyi, from->keys) {
582         merge = (merge == MERGE_DEFAULT ? keyi->merge : merge);
583         if (!AddKeySymbols(into, keyi))
584             into->errorCount++;
585     }
586
587     darray_foreach(mm, from->modMaps) {
588         mm->merge = (merge == MERGE_DEFAULT ? mm->merge : merge);
589         if (!AddModMapEntry(into, mm))
590             into->errorCount++;
591     }
592 }
593
594 static void
595 HandleSymbolsFile(SymbolsInfo *info, XkbFile *file, enum merge_mode merge);
596
597 static bool
598 HandleIncludeSymbols(SymbolsInfo *info, IncludeStmt *stmt)
599 {
600     enum merge_mode merge = MERGE_DEFAULT;
601     XkbFile *rtrn;
602     SymbolsInfo included, next_incl;
603
604     InitSymbolsInfo(&included, info->keymap, info->file_id, info->actions);
605     if (stmt->stmt) {
606         free(included.name);
607         included.name = stmt->stmt;
608         stmt->stmt = NULL;
609     }
610
611     for (; stmt; stmt = stmt->next_incl) {
612         if (!ProcessIncludeFile(info->keymap->ctx, stmt, FILE_TYPE_SYMBOLS,
613                                 &rtrn, &merge)) {
614             info->errorCount += 10;
615             ClearSymbolsInfo(&included);
616             return false;
617         }
618
619         InitSymbolsInfo(&next_incl, info->keymap, rtrn->id, info->actions);
620         next_incl.merge = next_incl.dflt.merge = MERGE_OVERRIDE;
621         if (stmt->modifier) {
622             next_incl.explicit_group = atoi(stmt->modifier) - 1;
623             if (next_incl.explicit_group >= XKB_NUM_GROUPS) {
624                 log_err(info->keymap->ctx,
625                         "Cannot set explicit group to %d - must be between 1..%d; "
626                         "Ignoring group number\n",
627                         next_incl.explicit_group + 1, XKB_NUM_GROUPS);
628                 next_incl.explicit_group = info->explicit_group;
629             }
630         }
631         else {
632             next_incl.explicit_group = info->explicit_group;
633         }
634
635         HandleSymbolsFile(&next_incl, rtrn, MERGE_OVERRIDE);
636
637         MergeIncludedSymbols(&included, &next_incl, merge);
638
639         ClearSymbolsInfo(&next_incl);
640         FreeXkbFile(rtrn);
641     }
642
643     MergeIncludedSymbols(info, &included, merge);
644     ClearSymbolsInfo(&included);
645
646     return (info->errorCount == 0);
647 }
648
649 #define SYMBOLS 1
650 #define ACTIONS 2
651
652 static bool
653 GetGroupIndex(SymbolsInfo *info, KeyInfo *keyi, ExprDef *arrayNdx,
654               unsigned what, xkb_layout_index_t *ndx_rtrn)
655 {
656     const char *name = (what == SYMBOLS ? "symbols" : "actions");
657
658     if (arrayNdx == NULL) {
659         xkb_layout_index_t i;
660         GroupInfo *groupi;
661         enum group_field field = (what == SYMBOLS ?
662                                   GROUP_FIELD_SYMS : GROUP_FIELD_ACTS);
663
664         darray_enumerate(i, groupi, keyi->groups) {
665             if (!(groupi->defined & field)) {
666                 *ndx_rtrn = i;
667                 return true;
668             }
669         }
670
671         if (i >= XKB_NUM_GROUPS) {
672             log_err(info->keymap->ctx,
673                     "Too many groups of %s for key %s (max %u); "
674                     "Ignoring %s defined for extra groups\n",
675                     name, LongKeyNameText(keyi->name), XKB_NUM_GROUPS + 1, name);
676             return false;
677         }
678
679         darray_resize0(keyi->groups, darray_size(keyi->groups) + 1);
680         *ndx_rtrn = darray_size(keyi->groups) - 1;
681         return true;
682     }
683
684     if (!ExprResolveGroup(info->keymap->ctx, arrayNdx, ndx_rtrn)) {
685         log_err(info->keymap->ctx,
686                 "Illegal group index for %s of key %s\n"
687                 "Definition with non-integer array index ignored\n",
688                 name, LongKeyNameText(keyi->name));
689         return false;
690     }
691
692     (*ndx_rtrn)--;
693     if (*ndx_rtrn >= darray_size(keyi->groups))
694         darray_resize0(keyi->groups, *ndx_rtrn + 1);
695
696     return true;
697 }
698
699 bool
700 LookupKeysym(const char *str, xkb_keysym_t *sym_rtrn)
701 {
702     xkb_keysym_t sym;
703
704     if (!str || istreq(str, "any") || istreq(str, "nosymbol")) {
705         *sym_rtrn = XKB_KEY_NoSymbol;
706         return 1;
707     }
708
709     if (istreq(str, "none") || istreq(str, "voidsymbol")) {
710         *sym_rtrn = XKB_KEY_VoidSymbol;
711         return 1;
712     }
713
714     sym = xkb_keysym_from_name(str);
715     if (sym != XKB_KEY_NoSymbol) {
716         *sym_rtrn = sym;
717         return 1;
718     }
719
720     return 0;
721 }
722
723 static bool
724 AddSymbolsToKey(SymbolsInfo *info, KeyInfo *keyi, ExprDef *arrayNdx,
725                 ExprDef *value)
726 {
727     xkb_layout_index_t ndx;
728     GroupInfo *groupi;
729     unsigned int nSyms;
730     xkb_level_index_t nLevels;
731     xkb_level_index_t i;
732     int j;
733
734     if (!GetGroupIndex(info, keyi, arrayNdx, SYMBOLS, &ndx))
735         return false;
736
737     groupi = &darray_item(keyi->groups, ndx);
738
739     if (value == NULL) {
740         groupi->defined |= GROUP_FIELD_SYMS;
741         return true;
742     }
743
744     if (value->op != EXPR_KEYSYM_LIST) {
745         log_err(info->keymap->ctx,
746                 "Expected a list of symbols, found %s; "
747                 "Ignoring symbols for group %u of %s\n",
748                 expr_op_type_to_string(value->op), ndx + 1,
749                 LongKeyNameText(keyi->name));
750         return false;
751     }
752
753     if (groupi->defined & GROUP_FIELD_SYMS) {
754         log_err(info->keymap->ctx,
755                 "Symbols for key %s, group %u already defined; "
756                 "Ignoring duplicate definition\n",
757                 LongKeyNameText(keyi->name), ndx + 1);
758         return false;
759     }
760
761     nSyms = darray_size(value->value.list.syms);
762     nLevels = darray_size(value->value.list.symsMapIndex);
763
764     if (darray_size(groupi->syms) < nSyms)
765         darray_resize0(groupi->syms, nSyms);
766
767     if (darray_size(groupi->levels) < nLevels)
768         darray_resize0(groupi->levels, nLevels);
769
770     groupi->defined |= GROUP_FIELD_SYMS;
771
772     for (i = 0; i < nLevels; i++) {
773         LevelInfo *leveli = &darray_item(groupi->levels, i);
774
775         leveli->sym_index = darray_item(value->value.list.symsMapIndex, i);
776         leveli->num_syms = darray_item(value->value.list.symsNumEntries, i);
777
778         for (j = 0; j < leveli->num_syms; j++) {
779             if (!LookupKeysym(darray_item(value->value.list.syms,
780                                           leveli->sym_index + j),
781                               &darray_item(groupi->syms,
782                                            leveli->sym_index + j))) {
783                 const char *group_name = "unnamed";
784
785                 if (ndx < darray_size(info->group_names) &&
786                     darray_item(info->group_names, ndx))
787                     group_name = xkb_atom_text(info->keymap->ctx,
788                                                darray_item(info->group_names,
789                                                            ndx));
790
791                 log_warn(info->keymap->ctx,
792                          "Could not resolve keysym %s for key %s, group %u (%s), level %u\n",
793                          darray_item(value->value.list.syms, i),
794                          LongKeyNameText(keyi->name),
795                          ndx + 1, group_name, nSyms);
796
797                 leveli->sym_index = 0;
798                 leveli->num_syms = 0;
799                 break;
800             }
801
802             if (leveli->num_syms == 1 &&
803                 darray_item(groupi->syms,
804                             leveli->sym_index + j) == XKB_KEY_NoSymbol) {
805                 leveli->sym_index = 0;
806                 leveli->num_syms = 0;
807             }
808         }
809     }
810
811     return true;
812 }
813
814 static bool
815 AddActionsToKey(SymbolsInfo *info, KeyInfo *keyi, ExprDef *arrayNdx,
816                 ExprDef *value)
817 {
818     unsigned int i;
819     xkb_layout_index_t ndx;
820     GroupInfo *groupi;
821     unsigned int nActs;
822     ExprDef *act;
823     union xkb_action *toAct;
824
825     if (!GetGroupIndex(info, keyi, arrayNdx, ACTIONS, &ndx))
826         return false;
827
828     groupi = &darray_item(keyi->groups, ndx);
829
830     if (value == NULL) {
831         groupi->defined |= GROUP_FIELD_ACTS;
832         return true;
833     }
834
835     if (value->op != EXPR_ACTION_LIST) {
836         log_wsgo(info->keymap->ctx,
837                  "Bad expression type (%d) for action list value; "
838                  "Ignoring actions for group %u of %s\n",
839                  value->op, ndx, LongKeyNameText(keyi->name));
840         return false;
841     }
842
843     if (groupi->defined & GROUP_FIELD_ACTS) {
844         log_wsgo(info->keymap->ctx,
845                  "Actions for key %s, group %u already defined\n",
846                  LongKeyNameText(keyi->name), ndx);
847         return false;
848     }
849
850     nActs = 0;
851     for (act = value->value.child; act; act = (ExprDef *) act->common.next)
852         nActs++;
853
854     if (darray_size(groupi->levels) < nActs)
855         darray_resize0(groupi->levels, nActs);
856
857     groupi->defined |= GROUP_FIELD_ACTS;
858
859     act = value->value.child;
860     for (i = 0; i < nActs; i++) {
861         toAct = &darray_item(groupi->levels, i).act;
862
863         if (!HandleActionDef(act, info->keymap, toAct, info->actions))
864             log_err(info->keymap->ctx,
865                     "Illegal action definition for %s; "
866                     "Action for group %u/level %u ignored\n",
867                     LongKeyNameText(keyi->name), ndx + 1, i + 1);
868
869         act = (ExprDef *) act->common.next;
870     }
871
872     return true;
873 }
874
875 static const LookupEntry repeatEntries[] = {
876     { "true", KEY_REPEAT_YES },
877     { "yes", KEY_REPEAT_YES },
878     { "on", KEY_REPEAT_YES },
879     { "false", KEY_REPEAT_NO },
880     { "no", KEY_REPEAT_NO },
881     { "off", KEY_REPEAT_NO },
882     { "default", KEY_REPEAT_UNDEFINED },
883     { NULL, 0 }
884 };
885
886 static bool
887 SetSymbolsField(SymbolsInfo *info, KeyInfo *keyi, const char *field,
888                 ExprDef *arrayNdx, ExprDef *value)
889 {
890     bool ok = true;
891     struct xkb_context *ctx = info->keymap->ctx;
892
893     if (istreq(field, "type")) {
894         xkb_layout_index_t ndx;
895         xkb_atom_t val;
896
897         if (!ExprResolveString(ctx, value, &val))
898             log_vrb(ctx, 1,
899                     "The type field of a key symbol map must be a string; "
900                     "Ignoring illegal type definition\n");
901
902         if (arrayNdx == NULL) {
903             keyi->dfltType = val;
904             keyi->defined |= KEY_FIELD_TYPE_DFLT;
905         }
906         else if (!ExprResolveGroup(ctx, arrayNdx, &ndx)) {
907             log_err(ctx,
908                     "Illegal group index for type of key %s; "
909                     "Definition with non-integer array index ignored\n",
910                     LongKeyNameText(keyi->name));
911             return false;
912         }
913         else {
914             ndx--;
915             if (ndx >= darray_size(keyi->groups))
916                 darray_resize0(keyi->groups, ndx + 1);
917             darray_item(keyi->groups, ndx).type = val;
918             darray_item(keyi->groups, ndx).defined |= GROUP_FIELD_TYPE;
919         }
920     }
921     else if (istreq(field, "symbols"))
922         return AddSymbolsToKey(info, keyi, arrayNdx, value);
923     else if (istreq(field, "actions"))
924         return AddActionsToKey(info, keyi, arrayNdx, value);
925     else if (istreq(field, "vmods") ||
926              istreq(field, "virtualmods") ||
927              istreq(field, "virtualmodifiers")) {
928         xkb_mod_mask_t mask;
929
930         ok = ExprResolveVModMask(info->keymap, value, &mask);
931         if (ok) {
932             keyi->vmodmap = (mask >> XKB_NUM_CORE_MODS) & 0xffff;
933             keyi->defined |= KEY_FIELD_VMODMAP;
934         }
935         else {
936             log_err(info->keymap->ctx,
937                     "Expected a virtual modifier mask, found %s; "
938                     "Ignoring virtual modifiers definition for key %s\n",
939                     expr_op_type_to_string(value->op),
940                     LongKeyNameText(keyi->name));
941         }
942     }
943     else if (istreq(field, "locking") ||
944              istreq(field, "lock") ||
945              istreq(field, "locks")) {
946         log_err(info->keymap->ctx,
947                 "Key behaviors not supported; "
948                 "Ignoring locking specification for key %s\n",
949                 LongKeyNameText(keyi->name));
950     }
951     else if (istreq(field, "radiogroup") ||
952              istreq(field, "permanentradiogroup") ||
953              istreq(field, "allownone")) {
954         log_err(info->keymap->ctx,
955                 "Radio groups not supported; "
956                 "Ignoring radio group specification for key %s\n",
957                 LongKeyNameText(keyi->name));
958     }
959     else if (istreq_prefix("overlay", field) ||
960              istreq_prefix("permanentoverlay", field)) {
961         log_err(info->keymap->ctx,
962                 "Overlays not supported; "
963                 "Ignoring overlay specification for key %s\n",
964                 LongKeyNameText(keyi->name));
965     }
966     else if (istreq(field, "repeating") ||
967              istreq(field, "repeats") ||
968              istreq(field, "repeat")) {
969         unsigned int val;
970
971         ok = ExprResolveEnum(ctx, value, &val, repeatEntries);
972         if (!ok) {
973             log_err(info->keymap->ctx,
974                     "Illegal repeat setting for %s; "
975                     "Non-boolean repeat setting ignored\n",
976                     LongKeyNameText(keyi->name));
977             return false;
978         }
979         keyi->repeat = val;
980         keyi->defined |= KEY_FIELD_REPEAT;
981     }
982     else if (istreq(field, "groupswrap") ||
983              istreq(field, "wrapgroups")) {
984         bool set;
985
986         if (!ExprResolveBoolean(ctx, value, &set)) {
987             log_err(info->keymap->ctx,
988                     "Illegal groupsWrap setting for %s; "
989                     "Non-boolean value ignored\n",
990                     LongKeyNameText(keyi->name));
991             return false;
992         }
993
994         if (set)
995             keyi->out_of_range_group_action = RANGE_WRAP;
996         else
997             keyi->out_of_range_group_action = RANGE_SATURATE;
998
999         keyi->defined |= KEY_FIELD_GROUPINFO;
1000     }
1001     else if (istreq(field, "groupsclamp") ||
1002              istreq(field, "clampgroups")) {
1003         bool set;
1004
1005         if (!ExprResolveBoolean(ctx, value, &set)) {
1006             log_err(info->keymap->ctx,
1007                     "Illegal groupsClamp setting for %s; "
1008                     "Non-boolean value ignored\n",
1009                     LongKeyNameText(keyi->name));
1010             return false;
1011         }
1012
1013         if (set)
1014             keyi->out_of_range_group_action = RANGE_SATURATE;
1015         else
1016             keyi->out_of_range_group_action = RANGE_WRAP;
1017
1018         keyi->defined |= KEY_FIELD_GROUPINFO;
1019     }
1020     else if (istreq(field, "groupsredirect") ||
1021              istreq(field, "redirectgroups")) {
1022         xkb_layout_index_t grp;
1023
1024         if (!ExprResolveGroup(ctx, value, &grp)) {
1025             log_err(info->keymap->ctx,
1026                     "Illegal group index for redirect of key %s; "
1027                     "Definition with non-integer group ignored\n",
1028                     LongKeyNameText(keyi->name));
1029             return false;
1030         }
1031
1032         keyi->out_of_range_group_action = RANGE_REDIRECT;
1033         keyi->out_of_range_group_number = grp - 1;
1034         keyi->defined |= KEY_FIELD_GROUPINFO;
1035     }
1036     else {
1037         log_err(info->keymap->ctx,
1038                 "Unknown field %s in a symbol interpretation; "
1039                 "Definition ignored\n",
1040                 field);
1041         ok = false;
1042     }
1043
1044     return ok;
1045 }
1046
1047 static int
1048 SetGroupName(SymbolsInfo *info, ExprDef *arrayNdx, ExprDef *value)
1049 {
1050     xkb_layout_index_t grp, grp_to_use;
1051     xkb_atom_t name;
1052
1053     if (!arrayNdx) {
1054         log_vrb(info->keymap->ctx, 1,
1055                 "You must specify an index when specifying a group name; "
1056                 "Group name definition without array subscript ignored\n");
1057         return false;
1058     }
1059
1060     if (!ExprResolveGroup(info->keymap->ctx, arrayNdx, &grp)) {
1061         log_err(info->keymap->ctx,
1062                 "Illegal index in group name definition; "
1063                 "Definition with non-integer array index ignored\n");
1064         return false;
1065     }
1066
1067     if (!ExprResolveString(info->keymap->ctx, value, &name)) {
1068         log_err(info->keymap->ctx,
1069                 "Group name must be a string; "
1070                 "Illegal name for group %d ignored\n", grp);
1071         return false;
1072     }
1073
1074     grp_to_use = XKB_LAYOUT_INVALID;
1075     if (info->explicit_group == XKB_LAYOUT_INVALID) {
1076         grp_to_use = grp - 1;
1077     }
1078     else if (grp - 1 == 0) {
1079         grp_to_use = info->explicit_group;
1080     }
1081     else {
1082         log_warn(info->keymap->ctx,
1083                  "An explicit group was specified for the '%s' map, "
1084                  "but it provides a name for a group other than Group1 (%d); "
1085                  "Ignoring group name '%s'\n",
1086                  info->name, grp,
1087                  xkb_atom_text(info->keymap->ctx, name));
1088         return false;
1089     }
1090
1091     if (grp_to_use >= darray_size(info->group_names))
1092         darray_resize0(info->group_names, grp_to_use + 1);
1093     darray_item(info->group_names, grp_to_use) = name;
1094     return true;
1095 }
1096
1097 static int
1098 HandleGlobalVar(SymbolsInfo *info, VarDef *stmt)
1099 {
1100     const char *elem, *field;
1101     ExprDef *arrayNdx;
1102     bool ret;
1103
1104     if (ExprResolveLhs(info->keymap->ctx, stmt->name, &elem, &field,
1105                        &arrayNdx) == 0)
1106         return 0;               /* internal error, already reported */
1107     if (elem && istreq(elem, "key")) {
1108         ret = SetSymbolsField(info, &info->dflt, field, arrayNdx,
1109                               stmt->value);
1110     }
1111     else if (!elem && (istreq(field, "name") ||
1112                        istreq(field, "groupname"))) {
1113         ret = SetGroupName(info, arrayNdx, stmt->value);
1114     }
1115     else if (!elem && (istreq(field, "groupswrap") ||
1116                        istreq(field, "wrapgroups"))) {
1117         log_err(info->keymap->ctx,
1118                 "Global \"groupswrap\" not supported; Ignored\n");
1119         ret = true;
1120     }
1121     else if (!elem && (istreq(field, "groupsclamp") ||
1122                        istreq(field, "clampgroups"))) {
1123         log_err(info->keymap->ctx,
1124                 "Global \"groupsclamp\" not supported; Ignored\n");
1125         ret = true;
1126     }
1127     else if (!elem && (istreq(field, "groupsredirect") ||
1128                        istreq(field, "redirectgroups"))) {
1129         log_err(info->keymap->ctx,
1130                 "Global \"groupsredirect\" not supported; Ignored\n");
1131         ret = true;
1132     }
1133     else if (!elem && istreq(field, "allownone")) {
1134         log_err(info->keymap->ctx,
1135                 "Radio groups not supported; "
1136                 "Ignoring \"allownone\" specification\n");
1137         ret = true;
1138     }
1139     else {
1140         ret = SetActionField(info->keymap, elem, field, arrayNdx, stmt->value,
1141                              info->actions);
1142     }
1143
1144     return ret;
1145 }
1146
1147 static bool
1148 HandleSymbolsBody(SymbolsInfo *info, VarDef *def, KeyInfo *keyi)
1149 {
1150     bool ok = true;
1151     const char *elem, *field;
1152     ExprDef *arrayNdx;
1153
1154     for (; def; def = (VarDef *) def->common.next) {
1155         if (def->name && def->name->op == EXPR_FIELD_REF) {
1156             log_err(info->keymap->ctx,
1157                     "Cannot set a global default value from within a key statement; "
1158                     "Move statements to the global file scope\n");
1159             continue;
1160         }
1161
1162         if (!def->name) {
1163             if (!def->value || def->value->op == EXPR_KEYSYM_LIST)
1164                 field = "symbols";
1165             else
1166                 field = "actions";
1167             arrayNdx = NULL;
1168         }
1169         else {
1170             ok = ExprResolveLhs(info->keymap->ctx, def->name, &elem, &field,
1171                                 &arrayNdx);
1172         }
1173
1174         if (ok)
1175             ok = SetSymbolsField(info, keyi, field, arrayNdx, def->value);
1176     }
1177
1178     return ok;
1179 }
1180
1181 static bool
1182 SetExplicitGroup(SymbolsInfo *info, KeyInfo *keyi)
1183 {
1184     xkb_layout_index_t i;
1185     GroupInfo *groupi;
1186     bool warn = false;
1187
1188     if (info->explicit_group == XKB_LAYOUT_INVALID)
1189         return true;
1190
1191     darray_enumerate_from(i, groupi, keyi->groups, 1) {
1192         if (groupi->defined) {
1193             warn = true;
1194             ClearGroupInfo(groupi);
1195         }
1196     }
1197
1198     if (warn)
1199         log_warn(info->keymap->ctx,
1200                  "For the map %s an explicit group specified, "
1201                  "but key %s has more than one group defined; "
1202                  "All groups except first one will be ignored\n",
1203                  info->name, LongKeyNameText(keyi->name));
1204
1205     darray_resize0(keyi->groups, info->explicit_group + 1);
1206     if (info->explicit_group > 0) {
1207         darray_item(keyi->groups, info->explicit_group) =
1208             darray_item(keyi->groups, 0);
1209         InitGroupInfo(&darray_item(keyi->groups, 0));
1210     }
1211
1212     return true;
1213 }
1214
1215 static int
1216 HandleSymbolsDef(SymbolsInfo *info, SymbolsDef *stmt)
1217 {
1218     KeyInfo keyi;
1219     xkb_layout_index_t i;
1220
1221     keyi = info->dflt;
1222     darray_init(keyi.groups);
1223     darray_copy(keyi.groups, info->dflt.groups);
1224     for (i = 0; i < darray_size(keyi.groups); i++) {
1225         darray_init(darray_item(keyi.groups, i).syms);
1226         darray_copy(darray_item(keyi.groups, i).syms,
1227                     darray_item(info->dflt.groups, i).syms);
1228         darray_init(darray_item(keyi.groups, i).levels);
1229         darray_copy(darray_item(keyi.groups, i).levels,
1230                     darray_item(info->dflt.groups, i).levels);
1231     }
1232     keyi.merge = stmt->merge;
1233     keyi.name = KeyNameToLong(stmt->keyName);
1234
1235     if (!HandleSymbolsBody(info, (VarDef *) stmt->symbols, &keyi)) {
1236         info->errorCount++;
1237         return false;
1238     }
1239
1240     if (!SetExplicitGroup(info, &keyi)) {
1241         info->errorCount++;
1242         return false;
1243     }
1244
1245     if (!AddKeySymbols(info, &keyi)) {
1246         info->errorCount++;
1247         return false;
1248     }
1249
1250     return true;
1251 }
1252
1253 static bool
1254 HandleModMapDef(SymbolsInfo *info, ModMapDef *def)
1255 {
1256     ExprDef *key;
1257     ModMapEntry tmp;
1258     xkb_mod_index_t ndx;
1259     bool ok;
1260     struct xkb_context *ctx = info->keymap->ctx;
1261
1262     if (!LookupModIndex(ctx, NULL, def->modifier, EXPR_TYPE_INT, &ndx)) {
1263         log_err(info->keymap->ctx,
1264                 "Illegal modifier map definition; "
1265                 "Ignoring map for non-modifier \"%s\"\n",
1266                 xkb_atom_text(ctx, def->modifier));
1267         return false;
1268     }
1269
1270     ok = true;
1271     tmp.modifier = ndx;
1272
1273     for (key = def->keys; key != NULL; key = (ExprDef *) key->common.next) {
1274         xkb_keysym_t sym;
1275
1276         if (key->op == EXPR_VALUE && key->value_type == EXPR_TYPE_KEYNAME) {
1277             tmp.haveSymbol = false;
1278             tmp.u.keyName = KeyNameToLong(key->value.keyName);
1279         }
1280         else if (ExprResolveKeySym(ctx, key, &sym)) {
1281             tmp.haveSymbol = true;
1282             tmp.u.keySym = sym;
1283         }
1284         else {
1285             log_err(info->keymap->ctx,
1286                     "Modmap entries may contain only key names or keysyms; "
1287                     "Illegal definition for %s modifier ignored\n",
1288                     ModIndexText(tmp.modifier));
1289             continue;
1290         }
1291
1292         ok = AddModMapEntry(info, &tmp) && ok;
1293     }
1294     return ok;
1295 }
1296
1297 static void
1298 HandleSymbolsFile(SymbolsInfo *info, XkbFile *file, enum merge_mode merge)
1299 {
1300     bool ok;
1301     ParseCommon *stmt;
1302
1303     free(info->name);
1304     info->name = strdup_safe(file->name);
1305
1306     stmt = file->defs;
1307     for (stmt = file->defs; stmt; stmt = stmt->next) {
1308         switch (stmt->type) {
1309         case STMT_INCLUDE:
1310             ok = HandleIncludeSymbols(info, (IncludeStmt *) stmt);
1311             break;
1312         case STMT_SYMBOLS:
1313             ok = HandleSymbolsDef(info, (SymbolsDef *) stmt);
1314             break;
1315         case STMT_VAR:
1316             ok = HandleGlobalVar(info, (VarDef *) stmt);
1317             break;
1318         case STMT_VMOD:
1319             ok = HandleVModDef((VModDef *) stmt, info->keymap, merge,
1320                                &info->vmods);
1321             break;
1322         case STMT_MODMAP:
1323             ok = HandleModMapDef(info, (ModMapDef *) stmt);
1324             break;
1325         default:
1326             log_err(info->keymap->ctx,
1327                     "Interpretation files may not include other types; "
1328                     "Ignoring %s\n", stmt_type_to_string(stmt->type));
1329             ok = false;
1330             break;
1331         }
1332
1333         if (!ok)
1334             info->errorCount++;
1335
1336         if (info->errorCount > 10) {
1337             log_err(info->keymap->ctx, "Abandoning symbols file \"%s\"\n",
1338                     file->topName);
1339             break;
1340         }
1341     }
1342 }
1343
1344 /**
1345  * Given a keysym @sym, return a key which generates it, or NULL.
1346  * This is used for example in a modifier map definition, such as:
1347  *      modifier_map Lock           { Caps_Lock };
1348  * where we want to add the Lock modifier to the modmap of the key
1349  * which matches the keysym Caps_Lock.
1350  * Since there can be many keys which generates the keysym, the key
1351  * is chosen first by lowest group in which the keysym appears, than
1352  * by lowest level and than by lowest key code.
1353  */
1354 static struct xkb_key *
1355 FindKeyForSymbol(struct xkb_keymap *keymap, xkb_keysym_t sym)
1356 {
1357     struct xkb_key *key, *ret = NULL;
1358     xkb_layout_index_t group, min_group = UINT32_MAX;
1359     xkb_level_index_t level, min_level = UINT16_MAX;
1360
1361     xkb_foreach_key(key, keymap) {
1362         for (group = 0; group < key->num_groups; group++) {
1363             for (level = 0; level < XkbKeyGroupWidth(keymap, key, group);
1364                  level++) {
1365                 if (XkbKeyNumSyms(key, group, level) != 1 ||
1366                     (XkbKeySymEntry(key, group, level))[0] != sym)
1367                     continue;
1368
1369                 /*
1370                  * If the keysym was found in a group or level > 0, we must
1371                  * keep looking since we might find a key in which the keysym
1372                  * is in a lower group or level.
1373                  */
1374                 if (group < min_group ||
1375                     (group == min_group && level < min_level)) {
1376                     ret = key;
1377                     if (group == 0 && level == 0) {
1378                         return ret;
1379                     }
1380                     else {
1381                         min_group = group;
1382                         min_level = level;
1383                     }
1384                 }
1385             }
1386         }
1387     }
1388
1389     return ret;
1390 }
1391
1392 static bool
1393 FindNamedType(struct xkb_keymap *keymap, xkb_atom_t name, unsigned *type_rtrn)
1394 {
1395     unsigned int i;
1396
1397     for (i = 0; i < keymap->num_types; i++) {
1398         if (keymap->types[i].name == name) {
1399             *type_rtrn = i;
1400             return true;
1401         }
1402     }
1403
1404     return false;
1405 }
1406
1407 /**
1408  * Assign a type to the given sym and return the Atom for the type assigned.
1409  *
1410  * Simple recipe:
1411  * - ONE_LEVEL for width 0/1
1412  * - ALPHABETIC for 2 shift levels, with lower/upercase
1413  * - KEYPAD for keypad keys.
1414  * - TWO_LEVEL for other 2 shift level keys.
1415  * and the same for four level keys.
1416  *
1417  * @param width Number of sysms in syms.
1418  * @param syms The keysyms for the given key (must be size width).
1419  * @param typeNameRtrn Set to the Atom of the type name.
1420  *
1421  * @returns true if a type could be found, false otherwise.
1422  *
1423  * FIXME: I need to take the KeyInfo so I can look at symsMapIndex and
1424  *        all that fun stuff rather than just assuming there's always one
1425  *        symbol per level.
1426  */
1427 static bool
1428 FindAutomaticType(struct xkb_context *ctx, xkb_level_index_t width,
1429                   const xkb_keysym_t *syms, xkb_atom_t *typeNameRtrn,
1430                   bool *autoType)
1431 {
1432     *autoType = false;
1433     if ((width == 1) || (width == 0)) {
1434         *typeNameRtrn = xkb_atom_intern(ctx, "ONE_LEVEL");
1435         *autoType = true;
1436     }
1437     else if (width == 2) {
1438         if (syms && xkb_keysym_is_lower(syms[0]) &&
1439             xkb_keysym_is_upper(syms[1])) {
1440             *typeNameRtrn = xkb_atom_intern(ctx, "ALPHABETIC");
1441         }
1442         else if (syms && (xkb_keysym_is_keypad(syms[0]) ||
1443                           xkb_keysym_is_keypad(syms[1]))) {
1444             *typeNameRtrn = xkb_atom_intern(ctx, "KEYPAD");
1445             *autoType = true;
1446         }
1447         else {
1448             *typeNameRtrn = xkb_atom_intern(ctx, "TWO_LEVEL");
1449             *autoType = true;
1450         }
1451     }
1452     else if (width <= 4) {
1453         if (syms && xkb_keysym_is_lower(syms[0]) &&
1454             xkb_keysym_is_upper(syms[1]))
1455             if (xkb_keysym_is_lower(syms[2]) && xkb_keysym_is_upper(syms[3]))
1456                 *typeNameRtrn =
1457                     xkb_atom_intern(ctx, "FOUR_LEVEL_ALPHABETIC");
1458             else
1459                 *typeNameRtrn = xkb_atom_intern(ctx,
1460                                                 "FOUR_LEVEL_SEMIALPHABETIC");
1461
1462         else if (syms && (xkb_keysym_is_keypad(syms[0]) ||
1463                           xkb_keysym_is_keypad(syms[1])))
1464             *typeNameRtrn = xkb_atom_intern(ctx, "FOUR_LEVEL_KEYPAD");
1465         else
1466             *typeNameRtrn = xkb_atom_intern(ctx, "FOUR_LEVEL");
1467         /* XXX: why not set autoType here? */
1468     }
1469     return width <= 4;
1470 }
1471
1472 static bool
1473 CopySymbolsDef(SymbolsInfo *info, KeyInfo *keyi)
1474 {
1475     struct xkb_keymap *keymap = info->keymap;
1476     struct xkb_key *key;
1477     GroupInfo *groupi;
1478     const GroupInfo *group0;
1479     xkb_layout_index_t i;
1480     bool haveActions;
1481     unsigned int sizeSyms;
1482     unsigned int symIndex;
1483
1484     /*
1485      * The name is guaranteed to be real and not an alias (see
1486      * AddKeySymbols), so 'false' is safe here.
1487      */
1488     key = FindNamedKey(keymap, keyi->name, false);
1489     if (!key) {
1490         log_vrb(info->keymap->ctx, 5,
1491                 "Key %s not found in keycodes; Symbols ignored\n",
1492                 LongKeyNameText(keyi->name));
1493         return false;
1494     }
1495
1496     /* Find the range of groups we need. */
1497     key->num_groups = 0;
1498     darray_enumerate(i, groupi, keyi->groups)
1499         if (groupi->defined)
1500             key->num_groups = i + 1;
1501
1502     if (key->num_groups <= 0)
1503         return false; /* WSGO */
1504
1505     darray_resize(keyi->groups, key->num_groups);
1506
1507     /*
1508      * If there are empty groups between non-empty ones, fill them with data
1509      * from the first group.
1510      * We can make a wrong assumption here. But leaving gaps is worse.
1511      */
1512     group0 = &darray_item(keyi->groups, 0);
1513     darray_foreach_from(groupi, keyi->groups, 1) {
1514         if (groupi->defined)
1515             continue;
1516
1517         groupi->type = group0->type;
1518         darray_copy(groupi->syms, group0->syms);
1519         darray_copy(groupi->levels, group0->levels);
1520         groupi->defined = group0->defined;
1521     }
1522
1523     /* See if we need to allocate an actions array. */
1524     haveActions = false;
1525     darray_foreach(groupi, keyi->groups) {
1526         LevelInfo *leveli;
1527         darray_foreach(leveli, groupi->levels) {
1528             if (leveli->act.type != ACTION_TYPE_NONE) {
1529                 haveActions = true;
1530                 goto out_of_loops;
1531             }
1532         }
1533     }
1534 out_of_loops:
1535
1536     /*
1537      * Find and assign the groups' types in the keymap. Also find the
1538      * key width according to the largest type.
1539      */
1540     key->kt_index = calloc(key->num_groups, sizeof(*key->kt_index));
1541     key->width = 0;
1542     darray_enumerate(i, groupi, keyi->groups) {
1543         struct xkb_key_type *type;
1544         bool autoType = false;
1545
1546         /* Find the type of the group, if it is missing. */
1547         if (groupi->type == XKB_ATOM_NONE) {
1548             if (keyi->dfltType != XKB_ATOM_NONE)
1549                 groupi->type = keyi->dfltType;
1550             else if (FindAutomaticType(keymap->ctx,
1551                                        darray_size(groupi->levels),
1552                                        darray_mem(groupi->syms, 0),
1553                                        &groupi->type, &autoType)) { }
1554             else
1555                 log_vrb(info->keymap->ctx, 5,
1556                         "No automatic type for %d levels; "
1557                         "Using %s for the %s key\n",
1558                         (int) darray_size(groupi->levels),
1559                         xkb_atom_text(keymap->ctx, groupi->type),
1560                         LongKeyNameText(keyi->name));
1561         }
1562
1563         /* Find the type in the keymap, if it was defined in xkb_types. */
1564         if (FindNamedType(keymap, groupi->type, &key->kt_index[i])) {
1565             if (!autoType || darray_size(groupi->levels) > 2)
1566                 key->explicit_groups |= (1 << i);
1567         }
1568         else {
1569             log_vrb(info->keymap->ctx, 3,
1570                     "Type \"%s\" is not defined; "
1571                     "Using default type for the %s key\n",
1572                     xkb_atom_text(keymap->ctx, groupi->type),
1573                     LongKeyNameText(keyi->name));
1574             /*
1575              * Index 0 is guaranteed to contain something, usually
1576              * ONE_LEVEL or at least some default one-level type.
1577              */
1578             key->kt_index[i] = 0;
1579         }
1580
1581         /* If the type specifies fewer levels than the key has, shrink the key. */
1582         type = &keymap->types[key->kt_index[i]];
1583         if (type->num_levels < darray_size(groupi->levels)) {
1584             log_vrb(info->keymap->ctx, 1,
1585                     "Type \"%s\" has %d levels, but %s has %d levels; "
1586                     "Ignoring extra symbols\n",
1587                     xkb_atom_text(keymap->ctx, type->name),
1588                     type->num_levels,
1589                     LongKeyNameText(keyi->name),
1590                     (int) darray_size(groupi->levels));
1591             darray_resize(groupi->levels, type->num_levels);
1592         }
1593
1594         /*
1595          * Why type->num_levels and not darray_size(groupi->levels)?
1596          * Because the type may have more levels, and each group must
1597          * have at least as many levels as its type. Because the
1598          * key->syms array is indexed by (group * width + level), we
1599          * must take the largest one.
1600          * Maybe we can change it to save some space.
1601          */
1602         key->width = MAX(key->width, type->num_levels);
1603     }
1604
1605     /* Find the size of the syms array. */
1606     sizeSyms = 0;
1607     darray_foreach(groupi, keyi->groups)
1608         sizeSyms += darray_size(groupi->syms);
1609
1610     /* Initialize the xkb_key, now that we know the sizes. */
1611     key->syms = calloc(sizeSyms, sizeof(*key->syms));
1612     key->sym_index = calloc(key->num_groups * key->width,
1613                             sizeof(*key->sym_index));
1614     key->num_syms = calloc(key->num_groups * key->width,
1615                            sizeof(*key->num_syms));
1616     key->out_of_range_group_number = keyi->out_of_range_group_number;
1617     key->out_of_range_group_action = keyi->out_of_range_group_action;
1618     if (haveActions) {
1619         key->actions = calloc(key->num_groups * key->width,
1620                               sizeof(*key->actions));
1621         key->explicit |= EXPLICIT_INTERP;
1622     }
1623     if (keyi->defined & KEY_FIELD_VMODMAP) {
1624         key->vmodmap = keyi->vmodmap;
1625         key->explicit |= EXPLICIT_VMODMAP;
1626     }
1627
1628     if (keyi->repeat != KEY_REPEAT_UNDEFINED) {
1629         key->repeats = (keyi->repeat == KEY_REPEAT_YES);
1630         key->explicit |= EXPLICIT_REPEAT;
1631     }
1632
1633     /* Copy keysyms and actions. */
1634     symIndex = 0;
1635     darray_enumerate(i, groupi, keyi->groups) {
1636         xkb_level_index_t j;
1637         LevelInfo *leveli;
1638
1639         /* We rely on calloc having zeroized the arrays up to key->width. */
1640         darray_enumerate(j, leveli, groupi->levels) {
1641             if (leveli->act.type != ACTION_TYPE_NONE)
1642                 key->actions[i * key->width + j] = leveli->act;
1643
1644             if (leveli->num_syms <= 0)
1645                 continue;
1646
1647             memcpy(&key->syms[symIndex],
1648                    &darray_item(groupi->syms, leveli->sym_index),
1649                    leveli->num_syms * sizeof(*key->syms));
1650             key->sym_index[i * key->width + j] = symIndex;
1651             key->num_syms[i * key->width + j] = leveli->num_syms;
1652             symIndex += key->num_syms[i * key->width + j];
1653         }
1654     }
1655
1656     return true;
1657 }
1658
1659 static bool
1660 CopyModMapDef(SymbolsInfo *info, ModMapEntry *entry)
1661 {
1662     struct xkb_key *key;
1663     struct xkb_keymap *keymap = info->keymap;
1664
1665     if (!entry->haveSymbol) {
1666         key = FindNamedKey(keymap, entry->u.keyName, true);
1667         if (!key) {
1668             log_vrb(info->keymap->ctx, 5,
1669                     "Key %s not found in keycodes; "
1670                     "Modifier map entry for %s not updated\n",
1671                     LongKeyNameText(entry->u.keyName),
1672                     ModIndexText(entry->modifier));
1673             return false;
1674         }
1675     }
1676     else {
1677         key = FindKeyForSymbol(keymap, entry->u.keySym);
1678         if (!key) {
1679             log_vrb(info->keymap->ctx, 5,
1680                     "Key \"%s\" not found in symbol map; "
1681                     "Modifier map entry for %s not updated\n",
1682                     KeysymText(entry->u.keySym),
1683                     ModIndexText(entry->modifier));
1684             return false;
1685         }
1686     }
1687
1688     key->modmap |= (1 << entry->modifier);
1689     return true;
1690 }
1691
1692 static bool
1693 CopySymbolsToKeymap(struct xkb_keymap *keymap, SymbolsInfo *info)
1694 {
1695     KeyInfo *keyi;
1696     ModMapEntry *mm;
1697     struct xkb_key *key;
1698
1699     keymap->symbols_section_name = strdup_safe(info->name);
1700
1701     keymap->group_names = info->group_names;
1702     darray_init(info->group_names);
1703
1704     darray_foreach(keyi, info->keys)
1705         if (!CopySymbolsDef(info, keyi))
1706             info->errorCount++;
1707
1708     if (xkb_context_get_log_verbosity(keymap->ctx) > 3) {
1709         xkb_foreach_key(key, keymap) {
1710             if (key->name[0] == '\0')
1711                 continue;
1712
1713             if (key->num_groups < 1)
1714                 log_info(keymap->ctx,
1715                          "No symbols defined for %s\n",
1716                          KeyNameText(key->name));
1717         }
1718     }
1719
1720     darray_foreach(mm, info->modMaps)
1721         if (!CopyModMapDef(info, mm))
1722             info->errorCount++;
1723
1724     /* XXX: If we don't ignore errorCount, things break. */
1725     return true;
1726 }
1727
1728 bool
1729 CompileSymbols(XkbFile *file, struct xkb_keymap *keymap,
1730                enum merge_mode merge)
1731 {
1732     SymbolsInfo info;
1733     ActionsInfo *actions;
1734
1735     actions = NewActionsInfo();
1736     if (!actions)
1737         return false;
1738
1739     InitSymbolsInfo(&info, keymap, file->id, actions);
1740     info.dflt.merge = merge;
1741
1742     HandleSymbolsFile(&info, file, merge);
1743
1744     if (darray_empty(info.keys))
1745         goto err_info;
1746
1747     if (info.errorCount != 0)
1748         goto err_info;
1749
1750     if (!CopySymbolsToKeymap(keymap, &info))
1751         goto err_info;
1752
1753     ClearSymbolsInfo(&info);
1754     FreeActionsInfo(actions);
1755     return true;
1756
1757 err_info:
1758     FreeActionsInfo(actions);
1759     ClearSymbolsInfo(&info);
1760     return false;
1761 }