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