symbols: consolidate group merging in MergeGroups
[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
62 enum key_repeat {
63     KEY_REPEAT_YES = 1,
64     KEY_REPEAT_NO = 0,
65     KEY_REPEAT_UNDEFINED = -1
66 };
67
68 enum group_field {
69     GROUP_FIELD_SYMS = (1 << 0),
70     GROUP_FIELD_ACTS = (1 << 1),
71     GROUP_FIELD_TYPE = (1 << 2),
72 };
73
74 enum key_field {
75     KEY_FIELD_REPEAT    = (1 << 0),
76     KEY_FIELD_TYPE_DFLT = (1 << 1),
77     KEY_FIELD_GROUPINFO = (1 << 2),
78     KEY_FIELD_VMODMAP   = (1 << 3),
79 };
80
81 typedef struct {
82     enum group_field defined;
83
84     xkb_level_index_t numLevels;
85     darray(xkb_keysym_t) syms;
86     /*
87      * symsMapIndex[level] -> The index from which the syms for the
88      * level begin in the syms array. Remember each keycode can have
89      * multiple keysyms in each level (that is, each key press can
90      * result in multiple keysyms).
91      */
92     darray(int) symsMapIndex;
93     /*
94      * symsMapNumEntries[level] -> How many syms are in
95      * syms[symsMapIndex[level]].
96      */
97     darray(size_t) symsMapNumEntries;
98     darray(union xkb_action) acts;
99     xkb_atom_t type;
100 } GroupInfo;
101
102 typedef struct _KeyInfo {
103     enum key_field defined;
104     unsigned file_id;
105     enum merge_mode merge;
106
107     unsigned long name; /* the 4 chars of the key name, as long */
108
109     GroupInfo groups[XKB_NUM_GROUPS];
110
111     enum key_repeat repeat;
112     xkb_mod_mask_t vmodmap;
113     xkb_atom_t dfltType;
114
115     enum xkb_range_exceed_type out_of_range_group_action;
116     xkb_group_index_t out_of_range_group_number;
117 } KeyInfo;
118
119 static void
120 InitGroupInfo(GroupInfo *groupi)
121 {
122     memset(groupi, 0, sizeof(*groupi));
123 }
124
125 static void
126 ClearGroupInfo(GroupInfo *groupi)
127 {
128     darray_free(groupi->syms);
129     darray_free(groupi->symsMapIndex);
130     darray_free(groupi->symsMapNumEntries);
131     darray_free(groupi->acts);
132     InitGroupInfo(groupi);
133 }
134
135 static void
136 InitKeyInfo(KeyInfo *keyi, unsigned file_id)
137 {
138     xkb_group_index_t i;
139     static const char dflt[4] = "*";
140
141     keyi->defined = 0;
142     keyi->file_id = file_id;
143     keyi->merge = MERGE_OVERRIDE;
144     keyi->name = KeyNameToLong(dflt);
145     for (i = 0; i < XKB_NUM_GROUPS; i++)
146         InitGroupInfo(&keyi->groups[i]);
147     keyi->dfltType = XKB_ATOM_NONE;
148     keyi->vmodmap = 0;
149     keyi->repeat = KEY_REPEAT_UNDEFINED;
150     keyi->out_of_range_group_action = RANGE_WRAP;
151     keyi->out_of_range_group_number = 0;
152 }
153
154 static void
155 ClearKeyInfo(KeyInfo *keyi)
156 {
157     xkb_group_index_t i;
158
159     for (i = 0; i < XKB_NUM_GROUPS; i++)
160         ClearGroupInfo(&keyi->groups[i]);
161 }
162
163 static bool
164 CopyKeyInfo(KeyInfo * old, KeyInfo * new, bool clearOld)
165 {
166     xkb_group_index_t i;
167
168     *new = *old;
169
170     if (clearOld) {
171         for (i = 0; i < XKB_NUM_GROUPS; i++) {
172             InitGroupInfo(&old->groups[i]);
173         }
174     }
175     else {
176         for (i = 0; i < XKB_NUM_GROUPS; i++) {
177             GroupInfo *n = &new->groups[i], *o = &old->groups[i];
178             darray_copy(n->syms, o->syms);
179             darray_copy(n->symsMapIndex, o->symsMapIndex);
180             darray_copy(n->symsMapNumEntries, o->symsMapNumEntries);
181             darray_copy(n->acts, o->acts);
182         }
183     }
184
185     return true;
186 }
187
188 /***====================================================================***/
189
190 typedef struct _ModMapEntry {
191     enum merge_mode merge;
192     bool haveSymbol;
193     int modifier;
194     union {
195         unsigned long keyName;
196         xkb_keysym_t keySym;
197     } u;
198 } ModMapEntry;
199
200 typedef struct _SymbolsInfo {
201     char *name;         /* e.g. pc+us+inet(evdev) */
202     int errorCount;
203     unsigned file_id;
204     enum merge_mode merge;
205     xkb_group_index_t explicit_group;
206     darray(KeyInfo) keys;
207     KeyInfo dflt;
208     VModInfo vmods;
209     ActionsInfo *actions;
210     xkb_atom_t groupNames[XKB_NUM_GROUPS];
211     darray(ModMapEntry) modMaps;
212
213     struct xkb_keymap *keymap;
214 } SymbolsInfo;
215
216 static void
217 InitSymbolsInfo(SymbolsInfo *info, struct xkb_keymap *keymap,
218                 unsigned file_id, ActionsInfo *actions)
219 {
220     xkb_group_index_t i;
221
222     info->name = NULL;
223     info->explicit_group = 0;
224     info->errorCount = 0;
225     info->file_id = file_id;
226     info->merge = MERGE_OVERRIDE;
227     darray_init(info->keys);
228     darray_growalloc(info->keys, 110);
229     darray_init(info->modMaps);
230     for (i = 0; i < XKB_NUM_GROUPS; i++)
231         info->groupNames[i] = XKB_ATOM_NONE;
232     InitKeyInfo(&info->dflt, file_id);
233     InitVModInfo(&info->vmods, keymap);
234     info->actions = actions;
235     info->keymap = keymap;
236 }
237
238 static void
239 ClearSymbolsInfo(SymbolsInfo * info)
240 {
241     KeyInfo *keyi;
242
243     free(info->name);
244     darray_foreach(keyi, info->keys)
245         ClearKeyInfo(keyi);
246     darray_free(info->keys);
247     darray_free(info->modMaps);
248     memset(info, 0, sizeof(SymbolsInfo));
249 }
250
251 static bool
252 ResizeGroupInfo(GroupInfo *groupi, xkb_level_index_t numLevels,
253                 unsigned sizeSyms, bool forceActions)
254 {
255     xkb_level_index_t i;
256
257     if (darray_size(groupi->syms) < sizeSyms)
258         darray_resize0(groupi->syms, sizeSyms);
259
260     if (darray_empty(groupi->symsMapIndex) ||
261         groupi->numLevels < numLevels) {
262         darray_resize(groupi->symsMapIndex, numLevels);
263         for (i = groupi->numLevels; i < numLevels; i++)
264             darray_item(groupi->symsMapIndex, i) = -1;
265     }
266
267     if (darray_empty(groupi->symsMapNumEntries) ||
268         groupi->numLevels < numLevels)
269         darray_resize0(groupi->symsMapNumEntries, numLevels);
270
271     if ((forceActions && (groupi->numLevels < numLevels ||
272                           darray_empty(groupi->acts))) ||
273         (groupi->numLevels < numLevels && !darray_empty(groupi->acts)))
274         darray_resize0(groupi->acts, numLevels);
275
276     groupi->numLevels = MAX(groupi->numLevels, numLevels);
277
278     return true;
279 }
280
281 enum key_group_selector {
282     NONE = 0,
283     FROM = (1 << 0),
284     TO = (1 << 1),
285 };
286
287 /*
288  * Merge @from into @into, where both are groups with the same index
289  * for the same key, and have at least on level to merge.
290  * @group and @key_name are just for reporting.
291  */
292 static bool
293 MergeGroups(SymbolsInfo *info, GroupInfo *into, GroupInfo *from, bool clobber,
294             bool report, xkb_group_index_t group, unsigned long key_name)
295 {
296     GroupInfo result;
297     unsigned int resultSize = 0;
298     enum key_group_selector using = NONE;
299     size_t cur_idx = 0;
300     xkb_level_index_t i;
301
302     /* First find the type of the merged group. */
303     if (into->type != from->type && from->type != XKB_ATOM_NONE) {
304         if (into->type == XKB_ATOM_NONE) {
305             into->type = from->type;
306         }
307         else {
308             xkb_atom_t use, ignore;
309
310             use = (clobber ? from->type : into->type);
311             ignore = (clobber ? into->type : from->type);
312
313             if (report)
314                 log_warn(info->keymap->ctx,
315                          "Multiple definitions for group %d type of key %s; "
316                          "Using %s, ignoring %s\n",
317                          group + 1, LongKeyNameText(key_name),
318                          xkb_atom_text(info->keymap->ctx, use),
319                          xkb_atom_text(info->keymap->ctx, ignore));
320
321             into->type = use;
322         }
323
324         into->defined |= GROUP_FIELD_TYPE;
325     }
326
327     /* Now look at the levels. */
328
329     /* Easy case: @from is empty. Just stick with @into. */
330     if (from->numLevels == 0) {
331         InitGroupInfo(from);
332         return true;
333     }
334
335     /* Easy case: @into is empty. Just copy @from as-is. */
336     if (into->numLevels == 0) {
337         from->type = into->type;
338         *into = *from;
339         InitGroupInfo(from);
340         return true;
341     }
342
343     /*
344      * Hard case: need to start merging levels. The aim is to avoid
345      * copying/allocating where possible.
346      */
347
348     InitGroupInfo(&result);
349
350     if (into->numLevels >= from->numLevels) {
351         result.acts = into->acts;
352         result.numLevels = into->numLevels;
353     }
354     else {
355         result.acts = from->acts;
356         result.numLevels = from->numLevels;
357         darray_resize(into->symsMapIndex, from->numLevels);
358         darray_resize0(into->symsMapNumEntries, from->numLevels);
359         for (i = into->numLevels; i < from->numLevels; i++)
360             darray_item(into->symsMapIndex, i) = -1;
361     }
362
363     if (darray_empty(result.acts) && (!darray_empty(into->acts) ||
364                                       !darray_empty(from->acts))) {
365         darray_resize0(result.acts, result.numLevels);
366         for (i = 0; i < result.numLevels; i++) {
367             union xkb_action *fromAct = NULL, *toAct = NULL;
368
369             if (!darray_empty(from->acts))
370                 fromAct = &darray_item(from->acts, i);
371
372             if (!darray_empty(into->acts))
373                 toAct = &darray_item(into->acts, i);
374
375             if (((fromAct == NULL) || (fromAct->type == ACTION_TYPE_NONE))
376                 && (toAct != NULL)) {
377                 darray_item(result.acts, i) = *toAct;
378             }
379             else if (((toAct == NULL) || (toAct->type == ACTION_TYPE_NONE))
380                      && (fromAct != NULL)) {
381                 darray_item(result.acts, i) = *fromAct;
382             }
383             else {
384                 union xkb_action *use, *ignore;
385                 if (clobber) {
386                     use = fromAct;
387                     ignore = toAct;
388                 }
389                 else {
390                     use = toAct;
391                     ignore = fromAct;
392                 }
393                 if (report)
394                     log_warn(info->keymap->ctx,
395                              "Multiple actions for level %d/group %u on key %s; "
396                              "Using %s, ignoring %s\n",
397                              i + 1, group + 1, LongKeyNameText(key_name),
398                              ActionTypeText(use->type),
399                              ActionTypeText(ignore->type));
400                 if (use)
401                     darray_item(result.acts, i) = *use;
402             }
403         }
404     }
405
406     for (i = 0; i < result.numLevels; i++) {
407         unsigned int fromSize = 0;
408         unsigned int toSize = 0;
409
410         if (!darray_empty(from->symsMapNumEntries) && i < from->numLevels)
411             fromSize = darray_item(from->symsMapNumEntries, i);
412
413         if (!darray_empty(into->symsMapNumEntries) && i < into->numLevels)
414             toSize = darray_item(into->symsMapNumEntries, i);
415
416         if (fromSize == 0) {
417             resultSize += toSize;
418             using |= TO;
419         }
420         else if (toSize == 0 || clobber) {
421             resultSize += fromSize;
422             using |= FROM;
423         }
424         else {
425             resultSize += toSize;
426             using |= TO;
427         }
428     }
429
430     if (resultSize == 0)
431         goto out;
432
433     if (using == FROM) {
434         result.syms = from->syms;
435         darray_free(into->symsMapNumEntries);
436         darray_free(into->symsMapIndex);
437         into->symsMapNumEntries = from->symsMapNumEntries;
438         into->symsMapIndex = from->symsMapIndex;
439         darray_init(from->symsMapNumEntries);
440         darray_init(from->symsMapIndex);
441         goto out;
442     }
443     else if (using == TO) {
444         result.syms = into->syms;
445         goto out;
446     }
447
448     darray_resize0(result.syms, resultSize);
449
450     for (i = 0; i < result.numLevels; i++) {
451         enum key_group_selector use = NONE;
452         unsigned int fromSize = 0;
453         unsigned int toSize = 0;
454
455         if (i < from->numLevels)
456             fromSize = darray_item(from->symsMapNumEntries, i);
457
458         if (i < into->numLevels)
459             toSize = darray_item(into->symsMapNumEntries, i);
460
461         if (fromSize == 0 && toSize == 0) {
462             darray_item(into->symsMapIndex, i) = -1;
463             darray_item(into->symsMapNumEntries, i) = 0;
464             continue;
465         }
466
467         if (fromSize == 0)
468             use = TO;
469         else if (toSize == 0 || clobber)
470             use = FROM;
471         else
472             use = TO;
473
474         if (toSize && fromSize && report) {
475             log_info(info->keymap->ctx,
476                      "Multiple symbols for group %u, level %d on key %s; "
477                      "Using %s, ignoring %s\n",
478                      group + 1, i + 1, LongKeyNameText(key_name),
479                      (use == FROM ? "from" : "to"),
480                      (use == FROM ? "to" : "from"));
481         }
482
483         if (use == FROM) {
484             memcpy(darray_mem(result.syms, cur_idx),
485                    darray_mem(from->syms, darray_item(from->symsMapIndex, i)),
486                    darray_item(from->symsMapNumEntries, i) * sizeof(xkb_keysym_t));
487             darray_item(into->symsMapIndex, i) = cur_idx;
488             darray_item(into->symsMapNumEntries, i) =
489                 darray_item(from->symsMapNumEntries, i);
490         }
491         else {
492             memcpy(darray_mem(result.syms, cur_idx),
493                    darray_mem(into->syms, darray_item(into->symsMapIndex, i)),
494                    darray_item(into->symsMapNumEntries, i) * sizeof(xkb_keysym_t));
495             darray_item(into->symsMapIndex, i) = cur_idx;
496         }
497
498         cur_idx += darray_item(into->symsMapNumEntries, i);
499     }
500
501 out:
502     into->numLevels = result.numLevels;
503
504     if (!darray_same(result.acts, into->acts))
505         darray_free(into->acts);
506     if (!darray_same(result.acts, from->acts))
507         darray_free(from->acts);
508     into->acts = result.acts;
509     into->defined |= GROUP_FIELD_ACTS;
510     darray_init(from->acts);
511     from->defined &= ~GROUP_FIELD_ACTS;
512
513     if (!darray_same(result.syms, into->syms))
514         darray_free(into->syms);
515     if (!darray_same(result.syms, from->syms))
516         darray_free(from->syms);
517     into->syms = result.syms;
518     if (darray_empty(into->syms))
519         into->defined &= ~GROUP_FIELD_SYMS;
520     else
521         into->defined |= GROUP_FIELD_SYMS;
522     darray_init(from->syms);
523     from->defined &= ~GROUP_FIELD_SYMS;
524
525     darray_free(from->symsMapIndex);
526     darray_free(from->symsMapNumEntries);
527
528     return true;
529 }
530
531 static bool
532 UseNewKeyField(enum key_field field, enum key_field old, enum key_field new,
533                bool clobber, bool report, enum key_field *collide)
534 {
535     if (!(old & field))
536         return (new & field);
537
538     if (new & field) {
539         if (report)
540             *collide |= field;
541
542         if (clobber)
543             return true;
544     }
545
546     return false;
547 }
548
549
550 /* Merge @from into @into, where both contain info for the same key. */
551 static bool
552 MergeKeys(SymbolsInfo *info, KeyInfo *into, KeyInfo *from)
553 {
554     xkb_group_index_t i;
555     enum key_field collide = 0;
556     bool clobber, report;
557     int verbosity = xkb_get_log_verbosity(info->keymap->ctx);
558
559     /* Forget about @into; just copy @from as-is. */
560     if (from->merge == MERGE_REPLACE) {
561         for (i = 0; i < XKB_NUM_GROUPS; i++)
562             if (into->groups[i].numLevels != 0)
563                 ClearGroupInfo(&into->groups[i]);
564         *into = *from;
565         InitKeyInfo(from, info->file_id);
566         return true;
567     }
568
569     clobber = (from->merge != MERGE_AUGMENT);
570     report = (verbosity > 9 ||
571               (into->file_id == from->file_id && verbosity > 0));
572
573     /* Start looking into the key groups. */
574     for (i = 0; i < XKB_NUM_GROUPS; i++)
575         MergeGroups(info, &into->groups[i], &from->groups[i], clobber,
576                     report, i, into->name);
577
578     if (UseNewKeyField(KEY_FIELD_VMODMAP, into->defined, from->defined,
579                        clobber, report, &collide)) {
580         into->vmodmap = from->vmodmap;
581         into->defined |= KEY_FIELD_VMODMAP;
582     }
583     if (UseNewKeyField(KEY_FIELD_REPEAT, into->defined, from->defined,
584                        clobber, report, &collide)) {
585         into->repeat = from->repeat;
586         into->defined |= KEY_FIELD_REPEAT;
587     }
588     if (UseNewKeyField(KEY_FIELD_TYPE_DFLT, into->defined, from->defined,
589                        clobber, report, &collide)) {
590         into->dfltType = from->dfltType;
591         into->defined |= KEY_FIELD_TYPE_DFLT;
592     }
593     if (UseNewKeyField(KEY_FIELD_GROUPINFO, into->defined, from->defined,
594                        clobber, report, &collide)) {
595         into->out_of_range_group_action = from->out_of_range_group_action;
596         into->out_of_range_group_number = from->out_of_range_group_number;
597         into->defined |= KEY_FIELD_GROUPINFO;
598     }
599
600     if (collide)
601         log_warn(info->keymap->ctx,
602                  "Symbol map for key %s redefined; "
603                  "Using %s definition for conflicting fields\n",
604                  LongKeyNameText(into->name),
605                  (clobber ? "first" : "last"));
606
607     return true;
608 }
609
610 static bool
611 AddKeySymbols(SymbolsInfo *info, KeyInfo *keyi)
612 {
613     unsigned long real_name;
614     KeyInfo *iter, *new;
615
616     darray_foreach(iter, info->keys)
617         if (iter->name == keyi->name)
618             return MergeKeys(info, iter, keyi);
619
620     if (FindKeyNameForAlias(info->keymap, keyi->name, &real_name))
621         darray_foreach(iter, info->keys)
622             if (iter->name == real_name)
623                 return MergeKeys(info, iter, keyi);
624
625     darray_resize0(info->keys, darray_size(info->keys) + 1);
626     new = &darray_item(info->keys, darray_size(info->keys) - 1);
627     return CopyKeyInfo(keyi, new, true);
628 }
629
630 static bool
631 AddModMapEntry(SymbolsInfo * info, ModMapEntry * new)
632 {
633     ModMapEntry *mm;
634     bool clobber;
635
636     clobber = (new->merge != MERGE_AUGMENT);
637     darray_foreach(mm, info->modMaps) {
638         if (new->haveSymbol && mm->haveSymbol
639             && (new->u.keySym == mm->u.keySym)) {
640             unsigned use, ignore;
641             if (mm->modifier != new->modifier) {
642                 if (clobber) {
643                     use = new->modifier;
644                     ignore = mm->modifier;
645                 }
646                 else {
647                     use = mm->modifier;
648                     ignore = new->modifier;
649                 }
650                 log_err(info->keymap->ctx,
651                         "%s added to symbol map for multiple modifiers; "
652                         "Using %s, ignoring %s.\n",
653                         KeysymText(new->u.keySym), ModIndexText(use),
654                         ModIndexText(ignore));
655                 mm->modifier = use;
656             }
657             return true;
658         }
659         if ((!new->haveSymbol) && (!mm->haveSymbol) &&
660             (new->u.keyName == mm->u.keyName)) {
661             unsigned use, ignore;
662             if (mm->modifier != new->modifier) {
663                 if (clobber) {
664                     use = new->modifier;
665                     ignore = mm->modifier;
666                 }
667                 else {
668                     use = mm->modifier;
669                     ignore = new->modifier;
670                 }
671                 log_err(info->keymap->ctx,
672                         "Key %s added to map for multiple modifiers; "
673                         "Using %s, ignoring %s.\n",
674                         LongKeyNameText(new->u.keyName), ModIndexText(use),
675                         ModIndexText(ignore));
676                 mm->modifier = use;
677             }
678             return true;
679         }
680     }
681
682     darray_append(info->modMaps, *new);
683     return true;
684 }
685
686 /***====================================================================***/
687
688 static void
689 MergeIncludedSymbols(SymbolsInfo *into, SymbolsInfo *from,
690                      enum merge_mode merge)
691 {
692     unsigned int i;
693     KeyInfo *keyi;
694     ModMapEntry *mm;
695
696     if (from->errorCount > 0) {
697         into->errorCount += from->errorCount;
698         return;
699     }
700     if (into->name == NULL) {
701         into->name = from->name;
702         from->name = NULL;
703     }
704     for (i = 0; i < XKB_NUM_GROUPS; i++) {
705         if (from->groupNames[i] != XKB_ATOM_NONE) {
706             if ((merge != MERGE_AUGMENT) ||
707                 (into->groupNames[i] == XKB_ATOM_NONE))
708                 into->groupNames[i] = from->groupNames[i];
709         }
710     }
711
712     darray_foreach(keyi, from->keys) {
713         merge = (merge == MERGE_DEFAULT ? keyi->merge : merge);
714         if (!AddKeySymbols(into, keyi))
715             into->errorCount++;
716     }
717
718     darray_foreach(mm, from->modMaps) {
719         mm->merge = (merge == MERGE_DEFAULT ? mm->merge : merge);
720         if (!AddModMapEntry(into, mm))
721             into->errorCount++;
722     }
723 }
724
725 static void
726 HandleSymbolsFile(SymbolsInfo *info, XkbFile *file, enum merge_mode merge);
727
728 static bool
729 HandleIncludeSymbols(SymbolsInfo *info, IncludeStmt *stmt)
730 {
731     enum merge_mode merge = MERGE_DEFAULT;
732     XkbFile *rtrn;
733     SymbolsInfo included, next_incl;
734
735     InitSymbolsInfo(&included, info->keymap, info->file_id, info->actions);
736     if (stmt->stmt) {
737         free(included.name);
738         included.name = stmt->stmt;
739         stmt->stmt = NULL;
740     }
741
742     for (; stmt; stmt = stmt->next_incl) {
743         if (!ProcessIncludeFile(info->keymap->ctx, stmt, FILE_TYPE_SYMBOLS,
744                                 &rtrn, &merge)) {
745             info->errorCount += 10;
746             ClearSymbolsInfo(&included);
747             return false;
748         }
749
750         InitSymbolsInfo(&next_incl, info->keymap, rtrn->id, info->actions);
751         next_incl.merge = next_incl.dflt.merge = MERGE_OVERRIDE;
752         if (stmt->modifier)
753             next_incl.explicit_group = atoi(stmt->modifier) - 1;
754         else
755             next_incl.explicit_group = info->explicit_group;
756
757         HandleSymbolsFile(&next_incl, rtrn, MERGE_OVERRIDE);
758
759         MergeIncludedSymbols(&included, &next_incl, merge);
760
761         ClearSymbolsInfo(&next_incl);
762         FreeXkbFile(rtrn);
763     }
764
765     MergeIncludedSymbols(info, &included, merge);
766     ClearSymbolsInfo(&included);
767
768     return (info->errorCount == 0);
769 }
770
771 #define SYMBOLS 1
772 #define ACTIONS 2
773
774 static bool
775 GetGroupIndex(SymbolsInfo *info, KeyInfo *keyi, ExprDef *arrayNdx,
776               unsigned what, xkb_group_index_t *ndx_rtrn)
777 {
778     const char *name = (what == SYMBOLS ? "symbols" : "actions");
779
780     if (arrayNdx == NULL) {
781         xkb_group_index_t i;
782         enum group_field field = (what == SYMBOLS ?
783                                   GROUP_FIELD_SYMS : GROUP_FIELD_ACTS);
784
785         for (i = 0; i < XKB_NUM_GROUPS; i++) {
786             if (!(keyi->groups[i].defined & field)) {
787                 *ndx_rtrn = i;
788                 return true;
789             }
790         }
791
792         log_err(info->keymap->ctx,
793                 "Too many groups of %s for key %s (max %u); "
794                 "Ignoring %s defined for extra groups\n",
795                 name, LongKeyNameText(keyi->name), XKB_NUM_GROUPS + 1, name);
796         return false;
797     }
798
799     if (!ExprResolveGroup(info->keymap->ctx, arrayNdx, ndx_rtrn)) {
800         log_err(info->keymap->ctx,
801                 "Illegal group index for %s of key %s\n"
802                 "Definition with non-integer array index ignored\n",
803                 name, LongKeyNameText(keyi->name));
804         return false;
805     }
806
807     (*ndx_rtrn)--;
808     return true;
809 }
810
811 bool
812 LookupKeysym(const char *str, xkb_keysym_t *sym_rtrn)
813 {
814     xkb_keysym_t sym;
815
816     if (!str || istreq(str, "any") || istreq(str, "nosymbol")) {
817         *sym_rtrn = XKB_KEY_NoSymbol;
818         return 1;
819     }
820
821     if (istreq(str, "none") || istreq(str, "voidsymbol")) {
822         *sym_rtrn = XKB_KEY_VoidSymbol;
823         return 1;
824     }
825
826     sym = xkb_keysym_from_name(str);
827     if (sym != XKB_KEY_NoSymbol) {
828         *sym_rtrn = sym;
829         return 1;
830     }
831
832     return 0;
833 }
834
835 static bool
836 AddSymbolsToKey(SymbolsInfo *info, KeyInfo *keyi, ExprDef *arrayNdx,
837                 ExprDef *value)
838 {
839     xkb_group_index_t ndx;
840     GroupInfo *groupi;
841     size_t nSyms;
842     xkb_level_index_t nLevels;
843     xkb_level_index_t i;
844     int j;
845
846     if (!GetGroupIndex(info, keyi, arrayNdx, SYMBOLS, &ndx))
847         return false;
848
849     groupi = &keyi->groups[ndx];
850
851     if (value == NULL) {
852         groupi->defined |= GROUP_FIELD_SYMS;
853         return true;
854     }
855
856     if (value->op != EXPR_KEYSYM_LIST) {
857         log_err(info->keymap->ctx,
858                 "Expected a list of symbols, found %s; "
859                 "Ignoring symbols for group %u of %s\n",
860                 expr_op_type_to_string(value->op), ndx + 1,
861                 LongKeyNameText(keyi->name));
862         return false;
863     }
864
865     if (!darray_empty(groupi->syms)) {
866         log_err(info->keymap->ctx,
867                 "Symbols for key %s, group %u already defined; "
868                 "Ignoring duplicate definition\n",
869                 LongKeyNameText(keyi->name), ndx + 1);
870         return false;
871     }
872
873     nSyms = darray_size(value->value.list.syms);
874     nLevels = darray_size(value->value.list.symsMapIndex);
875
876     if ((groupi->numLevels < nSyms || darray_empty(groupi->syms))) {
877         if (!ResizeGroupInfo(groupi, nLevels, nSyms, false)) {
878             log_wsgo(info->keymap->ctx,
879                      "Could not resize group %u of key %s to contain %zu levels; "
880                      "Symbols lost\n",
881                      ndx + 1, LongKeyNameText(keyi->name), nSyms);
882             return false;
883         }
884     }
885
886     groupi->defined |= GROUP_FIELD_SYMS;
887
888     for (i = 0; i < nLevels; i++) {
889         darray_item(groupi->symsMapIndex, i) =
890             darray_item(value->value.list.symsMapIndex, i);
891         darray_item(groupi->symsMapNumEntries, i) =
892             darray_item(value->value.list.symsNumEntries, i);
893
894         for (j = 0; j < darray_item(groupi->symsMapNumEntries, i); j++) {
895             /* FIXME: What's abort() doing here? */
896             if (darray_item(groupi->symsMapIndex, i) + j >= nSyms)
897                 abort();
898
899             if (!LookupKeysym(darray_item(value->value.list.syms,
900                                           darray_item(value->value.list.symsMapIndex, i) + j),
901                               &darray_item(groupi->syms,
902                                            darray_item(groupi->symsMapIndex, i) + j))) {
903                 log_warn(info->keymap->ctx,
904                          "Could not resolve keysym %s for key %s, group %u (%s), level %zu\n",
905                          darray_item(value->value.list.syms, i),
906                          LongKeyNameText(keyi->name),
907                          ndx + 1,
908                          xkb_atom_text(info->keymap->ctx,
909                                        info->groupNames[ndx]),
910                          nSyms);
911
912                 while (--j >= 0)
913                     darray_item(groupi->syms,
914                                 darray_item(groupi->symsMapIndex, i) + j) = XKB_KEY_NoSymbol;
915
916                 darray_item(groupi->symsMapIndex, i) = -1;
917                 darray_item(groupi->symsMapNumEntries, i) = 0;
918                 break;
919             }
920
921             if (darray_item(groupi->symsMapNumEntries, i) == 1 &&
922                 darray_item(groupi->syms,
923                             darray_item(groupi->symsMapIndex, i) + j) == XKB_KEY_NoSymbol) {
924                 darray_item(groupi->symsMapIndex, i) = -1;
925                 darray_item(groupi->symsMapNumEntries, i) = 0;
926             }
927         }
928     }
929
930     for (j = groupi->numLevels - 1;
931          j >= 0 && darray_item(groupi->symsMapNumEntries, j) == 0; j--)
932         groupi->numLevels--;
933
934     return true;
935 }
936
937 static bool
938 AddActionsToKey(SymbolsInfo *info, KeyInfo *keyi, ExprDef *arrayNdx,
939                 ExprDef *value)
940 {
941     size_t i;
942     xkb_group_index_t ndx;
943     GroupInfo *groupi;
944     size_t nActs;
945     ExprDef *act;
946     union xkb_action *toAct;
947
948     if (!GetGroupIndex(info, keyi, arrayNdx, ACTIONS, &ndx))
949         return false;
950
951     groupi = &keyi->groups[ndx];
952
953     if (value == NULL) {
954         groupi->defined |= GROUP_FIELD_ACTS;
955         return true;
956     }
957
958     if (value->op != EXPR_ACTION_LIST) {
959         log_wsgo(info->keymap->ctx,
960                  "Bad expression type (%d) for action list value; "
961                  "Ignoring actions for group %u of %s\n",
962                  value->op, ndx, LongKeyNameText(keyi->name));
963         return false;
964     }
965
966     if (!darray_empty(groupi->acts)) {
967         log_wsgo(info->keymap->ctx,
968                  "Actions for key %s, group %u already defined\n",
969                  LongKeyNameText(keyi->name), ndx);
970         return false;
971     }
972
973     for (nActs = 0, act = value->value.child; act != NULL; nActs++) {
974         act = (ExprDef *) act->common.next;
975     }
976
977     if (nActs < 1) {
978         log_wsgo(info->keymap->ctx,
979                  "Action list but not actions in AddActionsToKey\n");
980         return false;
981     }
982
983     if ((groupi->numLevels < nActs || darray_empty(groupi->acts))) {
984         if (!ResizeGroupInfo(&keyi->groups[ndx], nActs, nActs, true)) {
985             log_wsgo(info->keymap->ctx,
986                      "Could not resize group %u of key %s; "
987                      "Actions lost\n",
988                      ndx, LongKeyNameText(keyi->name));
989             return false;
990         }
991     }
992
993     groupi->defined |= GROUP_FIELD_ACTS;
994
995     toAct = darray_mem(groupi->acts, 0);
996     act = value->value.child;
997     for (i = 0; i < nActs; i++, toAct++) {
998         if (!HandleActionDef(act, info->keymap, toAct, info->actions)) {
999             log_err(info->keymap->ctx,
1000                     "Illegal action definition for %s; "
1001                     "Action for group %u/level %zu ignored\n",
1002                     LongKeyNameText(keyi->name), ndx + 1, i + 1);
1003         }
1004         act = (ExprDef *) act->common.next;
1005     }
1006
1007     return true;
1008 }
1009
1010 static const LookupEntry repeatEntries[] = {
1011     { "true", KEY_REPEAT_YES },
1012     { "yes", KEY_REPEAT_YES },
1013     { "on", KEY_REPEAT_YES },
1014     { "false", KEY_REPEAT_NO },
1015     { "no", KEY_REPEAT_NO },
1016     { "off", KEY_REPEAT_NO },
1017     { "default", KEY_REPEAT_UNDEFINED },
1018     { NULL, 0 }
1019 };
1020
1021 static bool
1022 SetSymbolsField(SymbolsInfo *info, KeyInfo *keyi, const char *field,
1023                 ExprDef *arrayNdx, ExprDef *value)
1024 {
1025     bool ok = true;
1026     struct xkb_context *ctx = info->keymap->ctx;
1027
1028     if (istreq(field, "type")) {
1029         xkb_group_index_t ndx;
1030         xkb_atom_t val;
1031
1032         if (!ExprResolveString(ctx, value, &val))
1033             log_vrb(ctx, 1,
1034                     "The type field of a key symbol map must be a string; "
1035                     "Ignoring illegal type definition\n");
1036
1037         if (arrayNdx == NULL) {
1038             keyi->dfltType = val;
1039             keyi->defined |= KEY_FIELD_TYPE_DFLT;
1040         }
1041         else if (!ExprResolveGroup(ctx, arrayNdx, &ndx)) {
1042             log_err(ctx,
1043                     "Illegal group index for type of key %s; "
1044                     "Definition with non-integer array index ignored\n",
1045                     LongKeyNameText(keyi->name));
1046             return false;
1047         }
1048         else {
1049             ndx--;
1050             keyi->groups[ndx].type = val;
1051             keyi->groups[ndx].defined |= GROUP_FIELD_TYPE;
1052         }
1053     }
1054     else if (istreq(field, "symbols"))
1055         return AddSymbolsToKey(info, keyi, arrayNdx, value);
1056     else if (istreq(field, "actions"))
1057         return AddActionsToKey(info, keyi, arrayNdx, value);
1058     else if (istreq(field, "vmods") ||
1059              istreq(field, "virtualmods") ||
1060              istreq(field, "virtualmodifiers")) {
1061         xkb_mod_mask_t mask;
1062
1063         ok = ExprResolveVModMask(info->keymap, value, &mask);
1064         if (ok) {
1065             keyi->vmodmap = (mask >> XKB_NUM_CORE_MODS) & 0xffff;
1066             keyi->defined |= KEY_FIELD_VMODMAP;
1067         }
1068         else {
1069             log_err(info->keymap->ctx,
1070                     "Expected a virtual modifier mask, found %s; "
1071                     "Ignoring virtual modifiers definition for key %s\n",
1072                     expr_op_type_to_string(value->op),
1073                     LongKeyNameText(keyi->name));
1074         }
1075     }
1076     else if (istreq(field, "locking") ||
1077              istreq(field, "lock") ||
1078              istreq(field, "locks")) {
1079         log_err(info->keymap->ctx,
1080                 "Key behaviors not supported; "
1081                 "Ignoring locking specification for key %s\n",
1082                 LongKeyNameText(keyi->name));
1083     }
1084     else if (istreq(field, "radiogroup") ||
1085              istreq(field, "permanentradiogroup") ||
1086              istreq(field, "allownone")) {
1087         log_err(info->keymap->ctx,
1088                 "Radio groups not supported; "
1089                 "Ignoring radio group specification for key %s\n",
1090                 LongKeyNameText(keyi->name));
1091     }
1092     else if (istreq_prefix("overlay", field) ||
1093              istreq_prefix("permanentoverlay", field)) {
1094         log_err(info->keymap->ctx,
1095                 "Overlays not supported; "
1096                 "Ignoring overlay specification for key %s\n",
1097                 LongKeyNameText(keyi->name));
1098     }
1099     else if (istreq(field, "repeating") ||
1100              istreq(field, "repeats") ||
1101              istreq(field, "repeat")) {
1102         unsigned int val;
1103
1104         ok = ExprResolveEnum(ctx, value, &val, repeatEntries);
1105         if (!ok) {
1106             log_err(info->keymap->ctx,
1107                     "Illegal repeat setting for %s; "
1108                     "Non-boolean repeat setting ignored\n",
1109                     LongKeyNameText(keyi->name));
1110             return false;
1111         }
1112         keyi->repeat = val;
1113         keyi->defined |= KEY_FIELD_REPEAT;
1114     }
1115     else if (istreq(field, "groupswrap") ||
1116              istreq(field, "wrapgroups")) {
1117         bool set;
1118
1119         if (!ExprResolveBoolean(ctx, value, &set)) {
1120             log_err(info->keymap->ctx,
1121                     "Illegal groupsWrap setting for %s; "
1122                     "Non-boolean value ignored\n",
1123                     LongKeyNameText(keyi->name));
1124             return false;
1125         }
1126
1127         if (set)
1128             keyi->out_of_range_group_action = RANGE_WRAP;
1129         else
1130             keyi->out_of_range_group_action = RANGE_SATURATE;
1131
1132         keyi->defined |= KEY_FIELD_GROUPINFO;
1133     }
1134     else if (istreq(field, "groupsclamp") ||
1135              istreq(field, "clampgroups")) {
1136         bool set;
1137
1138         if (!ExprResolveBoolean(ctx, value, &set)) {
1139             log_err(info->keymap->ctx,
1140                     "Illegal groupsClamp setting for %s; "
1141                     "Non-boolean value ignored\n",
1142                     LongKeyNameText(keyi->name));
1143             return false;
1144         }
1145
1146         if (set)
1147             keyi->out_of_range_group_action = RANGE_SATURATE;
1148         else
1149             keyi->out_of_range_group_action = RANGE_WRAP;
1150
1151         keyi->defined |= KEY_FIELD_GROUPINFO;
1152     }
1153     else if (istreq(field, "groupsredirect") ||
1154              istreq(field, "redirectgroups")) {
1155         xkb_group_index_t grp;
1156
1157         if (!ExprResolveGroup(ctx, value, &grp)) {
1158             log_err(info->keymap->ctx,
1159                     "Illegal group index for redirect of key %s; "
1160                     "Definition with non-integer group ignored\n",
1161                     LongKeyNameText(keyi->name));
1162             return false;
1163         }
1164
1165         keyi->out_of_range_group_action = RANGE_REDIRECT;
1166         keyi->out_of_range_group_number = grp - 1;
1167         keyi->defined |= KEY_FIELD_GROUPINFO;
1168     }
1169     else {
1170         log_err(info->keymap->ctx,
1171                 "Unknown field %s in a symbol interpretation; "
1172                 "Definition ignored\n",
1173                 field);
1174         ok = false;
1175     }
1176
1177     return ok;
1178 }
1179
1180 static int
1181 SetGroupName(SymbolsInfo *info, ExprDef *arrayNdx, ExprDef *value)
1182 {
1183     xkb_group_index_t grp;
1184     xkb_atom_t name;
1185
1186     if (!arrayNdx) {
1187         log_vrb(info->keymap->ctx, 1,
1188                 "You must specify an index when specifying a group name; "
1189                 "Group name definition without array subscript ignored\n");
1190         return false;
1191     }
1192
1193     if (!ExprResolveGroup(info->keymap->ctx, arrayNdx, &grp)) {
1194         log_err(info->keymap->ctx,
1195                 "Illegal index in group name definition; "
1196                 "Definition with non-integer array index ignored\n");
1197         return false;
1198     }
1199
1200     if (!ExprResolveString(info->keymap->ctx, value, &name)) {
1201         log_err(info->keymap->ctx,
1202                 "Group name must be a string; "
1203                 "Illegal name for group %d ignored\n", grp);
1204         return false;
1205     }
1206
1207     info->groupNames[grp - 1 + info->explicit_group] = name;
1208     return true;
1209 }
1210
1211 static int
1212 HandleSymbolsVar(SymbolsInfo *info, VarDef *stmt)
1213 {
1214     const char *elem, *field;
1215     ExprDef *arrayNdx;
1216     bool ret;
1217
1218     if (ExprResolveLhs(info->keymap->ctx, stmt->name, &elem, &field,
1219                        &arrayNdx) == 0)
1220         return 0;               /* internal error, already reported */
1221     if (elem && istreq(elem, "key")) {
1222         ret = SetSymbolsField(info, &info->dflt, field, arrayNdx,
1223                               stmt->value);
1224     }
1225     else if (!elem && (istreq(field, "name") ||
1226                        istreq(field, "groupname"))) {
1227         ret = SetGroupName(info, arrayNdx, stmt->value);
1228     }
1229     else if (!elem && (istreq(field, "groupswrap") ||
1230                        istreq(field, "wrapgroups"))) {
1231         log_err(info->keymap->ctx,
1232                 "Global \"groupswrap\" not supported; Ignored\n");
1233         ret = true;
1234     }
1235     else if (!elem && (istreq(field, "groupsclamp") ||
1236                        istreq(field, "clampgroups"))) {
1237         log_err(info->keymap->ctx,
1238                 "Global \"groupsclamp\" not supported; Ignored\n");
1239         ret = true;
1240     }
1241     else if (!elem && (istreq(field, "groupsredirect") ||
1242                        istreq(field, "redirectgroups"))) {
1243         log_err(info->keymap->ctx,
1244                 "Global \"groupsredirect\" not supported; Ignored\n");
1245         ret = true;
1246     }
1247     else if (!elem && istreq(field, "allownone")) {
1248         log_err(info->keymap->ctx,
1249                 "Radio groups not supported; "
1250                 "Ignoring \"allownone\" specification\n");
1251         ret = true;
1252     }
1253     else {
1254         ret = SetActionField(info->keymap, elem, field, arrayNdx, stmt->value,
1255                              info->actions);
1256     }
1257
1258     return ret;
1259 }
1260
1261 static bool
1262 HandleSymbolsBody(SymbolsInfo *info, VarDef *def, KeyInfo *keyi)
1263 {
1264     bool ok = true;
1265     const char *elem, *field;
1266     ExprDef *arrayNdx;
1267
1268     for (; def; def = (VarDef *) def->common.next) {
1269         if (def->name && def->name->op == EXPR_FIELD_REF) {
1270             ok = HandleSymbolsVar(info, def);
1271             continue;
1272         }
1273
1274         if (!def->name) {
1275             if (!def->value || def->value->op == EXPR_KEYSYM_LIST)
1276                 field = "symbols";
1277             else
1278                 field = "actions";
1279             arrayNdx = NULL;
1280         }
1281         else {
1282             ok = ExprResolveLhs(info->keymap->ctx, def->name, &elem, &field,
1283                                 &arrayNdx);
1284         }
1285
1286         if (ok)
1287             ok = SetSymbolsField(info, keyi, field, arrayNdx, def->value);
1288     }
1289
1290     return ok;
1291 }
1292
1293 static bool
1294 SetExplicitGroup(SymbolsInfo *info, KeyInfo *keyi)
1295 {
1296     xkb_group_index_t i;
1297
1298     if (info->explicit_group == 0)
1299         return true;
1300
1301     for (i = 1; i < XKB_NUM_GROUPS; i++) {
1302         if (keyi->groups[i].defined) {
1303             log_warn(info->keymap->ctx,
1304                      "For the map %s an explicit group specified, "
1305                      "but key %s has more than one group defined; "
1306                      "All groups except first one will be ignored\n",
1307                      info->name, LongKeyNameText(keyi->name));
1308             break;
1309         }
1310     }
1311     if (i < XKB_NUM_GROUPS)
1312         for (i = 1; i < XKB_NUM_GROUPS; i++)
1313             ClearGroupInfo(&keyi->groups[i]);
1314
1315     keyi->groups[info->explicit_group] = keyi->groups[0];
1316     InitGroupInfo(&keyi->groups[0]);
1317     return true;
1318 }
1319
1320 static int
1321 HandleSymbolsDef(SymbolsInfo *info, SymbolsDef *stmt)
1322 {
1323     KeyInfo keyi;
1324
1325     InitKeyInfo(&keyi, info->file_id);
1326     CopyKeyInfo(&info->dflt, &keyi, false);
1327     keyi.merge = stmt->merge;
1328     keyi.name = KeyNameToLong(stmt->keyName);
1329     if (!HandleSymbolsBody(info, (VarDef *) stmt->symbols, &keyi)) {
1330         info->errorCount++;
1331         return false;
1332     }
1333
1334     if (!SetExplicitGroup(info, &keyi)) {
1335         info->errorCount++;
1336         return false;
1337     }
1338
1339     if (!AddKeySymbols(info, &keyi)) {
1340         info->errorCount++;
1341         return false;
1342     }
1343     return true;
1344 }
1345
1346 static bool
1347 HandleModMapDef(SymbolsInfo *info, ModMapDef *def)
1348 {
1349     ExprDef *key;
1350     ModMapEntry tmp;
1351     xkb_mod_index_t ndx;
1352     bool ok;
1353     struct xkb_context *ctx = info->keymap->ctx;
1354
1355     if (!LookupModIndex(ctx, NULL, def->modifier, EXPR_TYPE_INT, &ndx)) {
1356         log_err(info->keymap->ctx,
1357                 "Illegal modifier map definition; "
1358                 "Ignoring map for non-modifier \"%s\"\n",
1359                 xkb_atom_text(ctx, def->modifier));
1360         return false;
1361     }
1362
1363     ok = true;
1364     tmp.modifier = ndx;
1365
1366     for (key = def->keys; key != NULL; key = (ExprDef *) key->common.next) {
1367         xkb_keysym_t sym;
1368
1369         if (key->op == EXPR_VALUE && key->value_type == EXPR_TYPE_KEYNAME) {
1370             tmp.haveSymbol = false;
1371             tmp.u.keyName = KeyNameToLong(key->value.keyName);
1372         }
1373         else if (ExprResolveKeySym(ctx, key, &sym)) {
1374             tmp.haveSymbol = true;
1375             tmp.u.keySym = sym;
1376         }
1377         else {
1378             log_err(info->keymap->ctx,
1379                     "Modmap entries may contain only key names or keysyms; "
1380                     "Illegal definition for %s modifier ignored\n",
1381                     ModIndexText(tmp.modifier));
1382             continue;
1383         }
1384
1385         ok = AddModMapEntry(info, &tmp) && ok;
1386     }
1387     return ok;
1388 }
1389
1390 static void
1391 HandleSymbolsFile(SymbolsInfo *info, XkbFile *file, enum merge_mode merge)
1392 {
1393     bool ok;
1394     ParseCommon *stmt;
1395
1396     free(info->name);
1397     info->name = strdup_safe(file->name);
1398
1399     stmt = file->defs;
1400     for (stmt = file->defs; stmt; stmt = stmt->next) {
1401         switch (stmt->type) {
1402         case STMT_INCLUDE:
1403             ok = HandleIncludeSymbols(info, (IncludeStmt *) stmt);
1404             break;
1405         case STMT_SYMBOLS:
1406             ok = HandleSymbolsDef(info, (SymbolsDef *) stmt);
1407             break;
1408         case STMT_VAR:
1409             ok = HandleSymbolsVar(info, (VarDef *) stmt);
1410             break;
1411         case STMT_VMOD:
1412             ok = HandleVModDef((VModDef *) stmt, info->keymap, merge,
1413                                &info->vmods);
1414             break;
1415         case STMT_MODMAP:
1416             ok = HandleModMapDef(info, (ModMapDef *) stmt);
1417             break;
1418         default:
1419             log_err(info->keymap->ctx,
1420                     "Interpretation files may not include other types; "
1421                     "Ignoring %s\n", stmt_type_to_string(stmt->type));
1422             ok = false;
1423             break;
1424         }
1425
1426         if (!ok)
1427             info->errorCount++;
1428
1429         if (info->errorCount > 10) {
1430             log_err(info->keymap->ctx, "Abandoning symbols file \"%s\"\n",
1431                     file->topName);
1432             break;
1433         }
1434     }
1435 }
1436
1437 /**
1438  * Given a keysym @sym, return a key which generates it, or NULL.
1439  * This is used for example in a modifier map definition, such as:
1440  *      modifier_map Lock           { Caps_Lock };
1441  * where we want to add the Lock modifier to the modmap of the key
1442  * which matches the keysym Caps_Lock.
1443  * Since there can be many keys which generates the keysym, the key
1444  * is chosen first by lowest group in which the keysym appears, than
1445  * by lowest level and than by lowest key code.
1446  */
1447 static struct xkb_key *
1448 FindKeyForSymbol(struct xkb_keymap *keymap, xkb_keysym_t sym)
1449 {
1450     struct xkb_key *key, *ret = NULL;
1451     xkb_group_index_t group, min_group = UINT32_MAX;
1452     xkb_level_index_t level, min_level = UINT16_MAX;
1453
1454     xkb_foreach_key(key, keymap) {
1455         for (group = 0; group < key->num_groups; group++) {
1456             for (level = 0; level < XkbKeyGroupWidth(keymap, key, group);
1457                  level++) {
1458                 if (XkbKeyNumSyms(key, group, level) != 1 ||
1459                     (XkbKeySymEntry(key, group, level))[0] != sym)
1460                     continue;
1461
1462                 /*
1463                  * If the keysym was found in a group or level > 0, we must
1464                  * keep looking since we might find a key in which the keysym
1465                  * is in a lower group or level.
1466                  */
1467                 if (group < min_group ||
1468                     (group == min_group && level < min_level)) {
1469                     ret = key;
1470                     if (group == 0 && level == 0) {
1471                         return ret;
1472                     }
1473                     else {
1474                         min_group = group;
1475                         min_level = level;
1476                     }
1477                 }
1478             }
1479         }
1480     }
1481
1482     return ret;
1483 }
1484
1485 /**
1486  * Find the given name in the keymap->map->types and return its index.
1487  *
1488  * @param name The name to search for.
1489  * @param type_rtrn Set to the index of the name if found.
1490  *
1491  * @return true if found, false otherwise.
1492  */
1493 static bool
1494 FindNamedType(struct xkb_keymap *keymap, xkb_atom_t name, unsigned *type_rtrn)
1495 {
1496     unsigned int i;
1497
1498     for (i = 0; i < keymap->num_types; i++) {
1499         if (keymap->types[i].name == name) {
1500             *type_rtrn = i;
1501             return true;
1502         }
1503     }
1504
1505     return false;
1506 }
1507
1508 /**
1509  * Assign a type to the given sym and return the Atom for the type assigned.
1510  *
1511  * Simple recipe:
1512  * - ONE_LEVEL for width 0/1
1513  * - ALPHABETIC for 2 shift levels, with lower/upercase
1514  * - KEYPAD for keypad keys.
1515  * - TWO_LEVEL for other 2 shift level keys.
1516  * and the same for four level keys.
1517  *
1518  * @param width Number of sysms in syms.
1519  * @param syms The keysyms for the given key (must be size width).
1520  * @param typeNameRtrn Set to the Atom of the type name.
1521  *
1522  * @returns true if a type could be found, false otherwise.
1523  *
1524  * FIXME: I need to take the KeyInfo so I can look at symsMapIndex and
1525  *        all that fun stuff rather than just assuming there's always one
1526  *        symbol per level.
1527  */
1528 static bool
1529 FindAutomaticType(struct xkb_keymap *keymap, xkb_level_index_t width,
1530                   const xkb_keysym_t *syms, xkb_atom_t *typeNameRtrn,
1531                   bool *autoType)
1532 {
1533     *autoType = false;
1534     if ((width == 1) || (width == 0)) {
1535         *typeNameRtrn = xkb_atom_intern(keymap->ctx, "ONE_LEVEL");
1536         *autoType = true;
1537     }
1538     else if (width == 2) {
1539         if (syms && xkb_keysym_is_lower(syms[0]) &&
1540             xkb_keysym_is_upper(syms[1])) {
1541             *typeNameRtrn = xkb_atom_intern(keymap->ctx, "ALPHABETIC");
1542         }
1543         else if (syms && (xkb_keysym_is_keypad(syms[0]) ||
1544                           xkb_keysym_is_keypad(syms[1]))) {
1545             *typeNameRtrn = xkb_atom_intern(keymap->ctx, "KEYPAD");
1546             *autoType = true;
1547         }
1548         else {
1549             *typeNameRtrn = xkb_atom_intern(keymap->ctx, "TWO_LEVEL");
1550             *autoType = true;
1551         }
1552     }
1553     else if (width <= 4) {
1554         if (syms && xkb_keysym_is_lower(syms[0]) &&
1555             xkb_keysym_is_upper(syms[1]))
1556             if (xkb_keysym_is_lower(syms[2]) && xkb_keysym_is_upper(syms[3]))
1557                 *typeNameRtrn =
1558                     xkb_atom_intern(keymap->ctx, "FOUR_LEVEL_ALPHABETIC");
1559             else
1560                 *typeNameRtrn = xkb_atom_intern(keymap->ctx,
1561                                                 "FOUR_LEVEL_SEMIALPHABETIC");
1562
1563         else if (syms && (xkb_keysym_is_keypad(syms[0]) ||
1564                           xkb_keysym_is_keypad(syms[1])))
1565             *typeNameRtrn = xkb_atom_intern(keymap->ctx, "FOUR_LEVEL_KEYPAD");
1566         else
1567             *typeNameRtrn = xkb_atom_intern(keymap->ctx, "FOUR_LEVEL");
1568         /* XXX: why not set autoType here? */
1569     }
1570     return width <= 4;
1571 }
1572
1573 /**
1574  * Ensure the given KeyInfo is in a coherent state, i.e. no gaps between the
1575  * groups, and reduce to one group if all groups are identical anyway.
1576  */
1577 static void
1578 PrepareKeyDef(KeyInfo *keyi)
1579 {
1580     xkb_group_index_t i, lastGroup;
1581     const GroupInfo *group0;
1582     bool identical;
1583
1584     /* get highest group number */
1585     for (i = XKB_NUM_GROUPS - 1; i > 0; i--)
1586         if (keyi->groups[i].defined)
1587             break;
1588     lastGroup = i;
1589
1590     if (lastGroup == 0)
1591         return;
1592
1593     group0 = &keyi->groups[0];
1594
1595     /* If there are empty groups between non-empty ones fill them with data */
1596     /* from the first group. */
1597     /* We can make a wrong assumption here. But leaving gaps is worse. */
1598     for (i = lastGroup; i > 0; i--) {
1599         GroupInfo *groupi = &keyi->groups[i];
1600
1601         if (groupi->defined)
1602             continue;
1603
1604         if (group0->defined & GROUP_FIELD_TYPE) {
1605             groupi->type = group0->type;
1606             groupi->defined |= GROUP_FIELD_TYPE;
1607         }
1608         if ((group0->defined & GROUP_FIELD_ACTS) &&
1609             !darray_empty(group0->acts)) {
1610             darray_copy(groupi->acts, group0->acts);
1611             groupi->defined |= GROUP_FIELD_ACTS;
1612         }
1613         if ((group0->defined & GROUP_FIELD_SYMS) &&
1614             !darray_empty(group0->syms)) {
1615             darray_copy(groupi->syms, group0->syms);
1616             darray_copy(groupi->symsMapIndex, group0->symsMapIndex);
1617             darray_copy(groupi->symsMapNumEntries, group0->symsMapNumEntries);
1618             groupi->defined |= GROUP_FIELD_SYMS;
1619         }
1620         if (group0->defined)
1621             groupi->numLevels = group0->numLevels;
1622     }
1623
1624     /* If all groups are completely identical remove them all */
1625     /* exept the first one. */
1626     identical = true;
1627     for (i = lastGroup; i > 0; i--) {
1628         GroupInfo *groupi = &keyi->groups[i];
1629
1630         if (groupi->numLevels != group0->numLevels ||
1631             groupi->type != group0->type) {
1632             identical = false;
1633             break;
1634         }
1635         if (!darray_same(groupi->syms, group0->syms) &&
1636             (darray_empty(groupi->syms) || darray_empty(group0->syms) ||
1637              darray_size(groupi->syms) != darray_size(group0->syms) ||
1638              memcmp(darray_mem(groupi->syms, 0),
1639                     darray_mem(group0->syms, 0),
1640                     sizeof(xkb_keysym_t) * darray_size(group0->syms)))) {
1641             identical = false;
1642             break;
1643         }
1644         if (!darray_same(groupi->symsMapIndex, group0->symsMapIndex) &&
1645             (darray_empty(groupi->symsMapIndex) ||
1646              darray_empty(group0->symsMapIndex) ||
1647              memcmp(darray_mem(groupi->symsMapIndex, 0),
1648                     darray_mem(group0->symsMapIndex, 0),
1649                     group0->numLevels * sizeof(int)))) {
1650             identical = false;
1651             continue;
1652         }
1653         if (!darray_same(groupi->symsMapNumEntries,
1654                          group0->symsMapNumEntries) &&
1655             (darray_empty(groupi->symsMapNumEntries) ||
1656              darray_empty(group0->symsMapNumEntries) ||
1657              memcmp(darray_mem(groupi->symsMapNumEntries, 0),
1658                     darray_mem(group0->symsMapNumEntries, 0),
1659                     group0->numLevels * sizeof(size_t)))) {
1660             identical = false;
1661             continue;
1662         }
1663         if (!darray_same(groupi->acts, group0->acts) &&
1664             (darray_empty(groupi->acts) || darray_empty(group0->acts) ||
1665              memcmp(darray_mem(groupi->acts, 0),
1666                     darray_mem(group0->acts, 0),
1667                     group0->numLevels * sizeof(union xkb_action)))) {
1668             identical = false;
1669             break;
1670         }
1671     }
1672
1673     if (identical)
1674         for (i = lastGroup; i > 0; i--)
1675             ClearGroupInfo(&keyi->groups[i]);
1676 }
1677
1678 /**
1679  * Copy the KeyInfo into the keyboard description.
1680  *
1681  * This function recurses.
1682  */
1683 static bool
1684 CopySymbolsDef(SymbolsInfo *info, KeyInfo *keyi,
1685                xkb_keycode_t start_from)
1686 {
1687     struct xkb_keymap *keymap = info->keymap;
1688     xkb_keycode_t kc;
1689     struct xkb_key *key;
1690     size_t sizeSyms = 0;
1691     xkb_group_index_t i, nGroups;
1692     xkb_level_index_t width, tmp;
1693     struct xkb_key_type * type;
1694     bool haveActions, autoType, useAlias;
1695     unsigned types[XKB_NUM_GROUPS];
1696     unsigned int symIndex = 0;
1697
1698     useAlias = (start_from == 0);
1699
1700     key = FindNamedKey(keymap, keyi->name, useAlias, start_from);
1701     if (!key) {
1702         if (start_from == 0)
1703             log_vrb(info->keymap->ctx, 5,
1704                     "Key %s not found in keycodes; Symbols ignored\n",
1705                     LongKeyNameText(keyi->name));
1706         return false;
1707     }
1708     kc = XkbKeyGetKeycode(keymap, key);
1709
1710     haveActions = false;
1711     width = 0;
1712     for (i = nGroups = 0; i < XKB_NUM_GROUPS; i++) {
1713         GroupInfo *groupi = &keyi->groups[i];
1714
1715         if (i + 1 > nGroups && groupi->defined)
1716             nGroups = i + 1;
1717
1718         if (!darray_empty(groupi->acts))
1719             haveActions = true;
1720
1721         autoType = false;
1722
1723         /* Assign the type to the key, if it is missing. */
1724         if (groupi->type == XKB_ATOM_NONE) {
1725             if (keyi->dfltType != XKB_ATOM_NONE)
1726                 groupi->type = keyi->dfltType;
1727             else if (FindAutomaticType(keymap, groupi->numLevels,
1728                                        darray_mem(groupi->syms, 0),
1729                                        &groupi->type, &autoType)) { }
1730             else
1731                 log_vrb(info->keymap->ctx, 5,
1732                         "No automatic type for %d symbols; "
1733                         "Using %s for the %s key (keycode %d)\n",
1734                         groupi->numLevels,
1735                         xkb_atom_text(keymap->ctx, groupi->type),
1736                         LongKeyNameText(keyi->name), kc);
1737         }
1738
1739         if (FindNamedType(keymap, groupi->type, &types[i])) {
1740             if (!autoType || groupi->numLevels > 2)
1741                 key->explicit_groups |= (1 << i);
1742         }
1743         else {
1744             log_vrb(info->keymap->ctx, 3,
1745                     "Type \"%s\" is not defined; "
1746                     "Using default type for the %s key (keycode %d)\n",
1747                     xkb_atom_text(keymap->ctx, groupi->type),
1748                     LongKeyNameText(keyi->name), kc);
1749             /*
1750              * Index 0 is guaranteed to contain something, usually
1751              * ONE_LEVEL or at least some default one-level type.
1752              */
1753             types[i] = 0;
1754         }
1755
1756         /* if the type specifies fewer levels than the key has, shrink the key */
1757         type = &keymap->types[types[i]];
1758         if (type->num_levels < groupi->numLevels) {
1759             log_vrb(info->keymap->ctx, 1,
1760                     "Type \"%s\" has %d levels, but %s has %d symbols; "
1761                     "Ignoring extra symbols\n",
1762                     xkb_atom_text(keymap->ctx, type->name),
1763                     type->num_levels,
1764                     LongKeyNameText(keyi->name),
1765                     groupi->numLevels);
1766             groupi->numLevels = type->num_levels;
1767         }
1768
1769         width = MAX3(width, groupi->numLevels, type->num_levels);
1770         sizeSyms += darray_size(groupi->syms);
1771     }
1772
1773     darray_resize0(key->syms, sizeSyms);
1774
1775     key->num_groups = nGroups;
1776
1777     key->width = width;
1778
1779     key->sym_index = calloc(nGroups * width, sizeof(*key->sym_index));
1780
1781     key->num_syms = calloc(nGroups * width, sizeof(*key->num_syms));
1782
1783     if (haveActions) {
1784         key->actions = calloc(nGroups * width, sizeof(*key->actions));
1785         key->explicit |= EXPLICIT_INTERP;
1786     }
1787
1788     key->out_of_range_group_number = keyi->out_of_range_group_number;
1789     key->out_of_range_group_action = keyi->out_of_range_group_action;
1790
1791     for (i = 0; i < nGroups; i++) {
1792         GroupInfo *groupi = &keyi->groups[i];
1793
1794         /* assign kt_index[i] to the index of the type in map->types.
1795          * kt_index[i] may have been set by a previous run (if we have two
1796          * layouts specified). Let's not overwrite it with the ONE_LEVEL
1797          * default group if we dont even have keys for this group anyway.
1798          *
1799          * FIXME: There should be a better fix for this.
1800          */
1801         if (groupi->numLevels)
1802             key->kt_index[i] = types[i];
1803
1804         if (!darray_empty(groupi->syms)) {
1805             /* fill key to "width" symbols*/
1806             for (tmp = 0; tmp < width; tmp++) {
1807                 if (tmp < groupi->numLevels &&
1808                     darray_item(groupi->symsMapNumEntries, tmp) != 0) {
1809                     memcpy(darray_mem(key->syms, symIndex),
1810                            darray_mem(groupi->syms,
1811                                       darray_item(groupi->symsMapIndex, tmp)),
1812                            darray_item(groupi->symsMapNumEntries, tmp) * sizeof(xkb_keysym_t));
1813                     key->sym_index[(i * width) + tmp] = symIndex;
1814                     key->num_syms[(i * width) + tmp] =
1815                         darray_item(groupi->symsMapNumEntries, tmp);
1816                     symIndex += key->num_syms[(i * width) + tmp];
1817                 }
1818                 else {
1819                     key->sym_index[(i * width) + tmp] = -1;
1820                     key->num_syms[(i * width) + tmp] = 0;
1821                 }
1822
1823                 if (key->actions && !darray_empty(groupi->acts)) {
1824                     if (tmp < groupi->numLevels)
1825                         key->actions[tmp] = darray_item(groupi->acts, tmp);
1826                     else
1827                         key->actions[tmp].type = ACTION_TYPE_NONE;
1828                 }
1829             }
1830         }
1831     }
1832
1833     if (keyi->defined & KEY_FIELD_VMODMAP) {
1834         key->vmodmap = keyi->vmodmap;
1835         key->explicit |= EXPLICIT_VMODMAP;
1836     }
1837
1838     if (keyi->repeat != KEY_REPEAT_UNDEFINED) {
1839         key->repeats = (keyi->repeat == KEY_REPEAT_YES);
1840         key->explicit |= EXPLICIT_REPEAT;
1841     }
1842
1843     /* do the same thing for the next key */
1844     CopySymbolsDef(info, keyi, kc + 1);
1845     return true;
1846 }
1847
1848 static bool
1849 CopyModMapDef(SymbolsInfo *info, ModMapEntry *entry)
1850 {
1851     struct xkb_key *key;
1852     struct xkb_keymap *keymap = info->keymap;
1853
1854     if (!entry->haveSymbol) {
1855         key = FindNamedKey(keymap, entry->u.keyName, true, 0);
1856         if (!key) {
1857             log_vrb(info->keymap->ctx, 5,
1858                     "Key %s not found in keycodes; "
1859                     "Modifier map entry for %s not updated\n",
1860                     LongKeyNameText(entry->u.keyName),
1861                     ModIndexText(entry->modifier));
1862             return false;
1863         }
1864     }
1865     else {
1866         key = FindKeyForSymbol(keymap, entry->u.keySym);
1867         if (!key) {
1868             log_vrb(info->keymap->ctx, 5,
1869                     "Key \"%s\" not found in symbol map; "
1870                     "Modifier map entry for %s not updated\n",
1871                     KeysymText(entry->u.keySym),
1872                     ModIndexText(entry->modifier));
1873             return false;
1874         }
1875     }
1876
1877     key->modmap |= (1 << entry->modifier);
1878     return true;
1879 }
1880
1881 /**
1882  * Handle the xkb_symbols section of an xkb file.
1883  *
1884  * @param file The parsed xkb_symbols section of the xkb file.
1885  * @param keymap Handle to the keyboard description to store the symbols in.
1886  * @param merge Merge strategy (e.g. MERGE_OVERRIDE).
1887  */
1888 bool
1889 CompileSymbols(XkbFile *file, struct xkb_keymap *keymap,
1890                enum merge_mode merge)
1891 {
1892     xkb_group_index_t i;
1893     struct xkb_key *key;
1894     SymbolsInfo info;
1895     ActionsInfo *actions;
1896     KeyInfo *keyi;
1897     ModMapEntry *mm;
1898
1899     actions = NewActionsInfo();
1900     if (!actions)
1901         return false;
1902
1903     InitSymbolsInfo(&info, keymap, file->id, actions);
1904     info.dflt.merge = merge;
1905
1906     HandleSymbolsFile(&info, file, merge);
1907
1908     if (darray_empty(info.keys))
1909         goto err_info;
1910
1911     if (info.errorCount != 0)
1912         goto err_info;
1913
1914     if (info.name)
1915         keymap->symbols_section_name = strdup(info.name);
1916
1917     for (i = 0; i < XKB_NUM_GROUPS; i++)
1918         if (info.groupNames[i] != XKB_ATOM_NONE)
1919             keymap->group_names[i] = info.groupNames[i];
1920
1921     /* sanitize keys */
1922     darray_foreach(keyi, info.keys)
1923         PrepareKeyDef(keyi);
1924
1925     /* copy! */
1926     darray_foreach(keyi, info.keys)
1927         if (!CopySymbolsDef(&info, keyi, 0))
1928             info.errorCount++;
1929
1930     if (xkb_get_log_verbosity(keymap->ctx) > 3) {
1931         xkb_foreach_key(key, keymap) {
1932             if (key->name[0] == '\0')
1933                 continue;
1934
1935             if (key->num_groups < 1)
1936                 log_info(info.keymap->ctx,
1937                          "No symbols defined for %s (keycode %d)\n",
1938                          KeyNameText(key->name),
1939                          XkbKeyGetKeycode(keymap, key));
1940         }
1941     }
1942
1943     darray_foreach(mm, info.modMaps)
1944         if (!CopyModMapDef(&info, mm))
1945             info.errorCount++;
1946
1947     ClearSymbolsInfo(&info);
1948     FreeActionsInfo(actions);
1949     return true;
1950
1951 err_info:
1952     FreeActionsInfo(actions);
1953     ClearSymbolsInfo(&info);
1954     return false;
1955 }