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