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