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