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