types: add "Effects on keymap" to overview
[platform/upstream/libxkbcommon.git] / src / xkbcomp / types.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 #include "xkbcomp-priv.h"
28 #include "text.h"
29 #include "vmod.h"
30 #include "expr.h"
31 #include "include.h"
32
33 /*
34  * The xkb_types section
35  * =====================
36  * This section is the second to be processesed, after xkb_keycodes.
37  * However, it is completely independent and could have been the first
38  * to be processed (it does not refer to specific keys as specified in
39  * the xkb_keycodes section).
40  *
41  * This section defines key types, which, given a key and a keyboard
42  * state (i.e. modifier state and group), determine the shift level to
43  * be used in translating the key to keysyms. These types are assigned
44  * to each group in each key, in the xkb_symbols section.
45  *
46  * Key types are called this way because, in a way, they really describe
47  * the "type" of the key (or more correctly, a specific group of the
48  * key). For example, an ordinary keymap will provide a type called
49  * "KEYPAD", which consists of two levels, with the second level being
50  * chosen according to the state of the Num Lock (or Shift) modifiers.
51  * Another example is a type called "ONE_LEVEL", which is usually
52  * assigned to keys such as Escape; these have just one level and are
53  * not affected by the modifier state. Yet more common examples are
54  * "TWO_LEVEL" (with Shift choosing the second level), "ALPHABETIC"
55  * (where Caps Lock may also choose the second level), etc.
56  *
57  * Type definitions
58  * ----------------
59  *  Statements of the form:
60  *      type "FOUR_LEVEL" { ... }
61  *
62  * The above would create a new type named "FOUR_LEVEL".
63  * The body of the definition may include statements of the following
64  * forms:
65  *
66  * - level_name statements (mandatory for each level in the type):
67  *      level_name[Level1] = "Base";
68  *
69  *   Gives each level in this type a descriptive name. It isn't used
70  *   for any thing.
71  *   Note: A level may be specified as Level[1-8] or just a number (can
72  *   be more than 8).
73  *
74  * - modifiers statement (mandatory, should be specified only once):
75  *      modifiers = Shift+Lock+LevelThree;
76  *
77  *   A mask of real and virtual modifiers. These are the only modifiers
78  *   being considered when matching the modifier state against the type.
79  *   The other modifiers, whether active or not, are masked out in the
80  *   calculation.
81  *
82  * - map entry statements (should have at least as many mappings as there
83  *   are levels in the type):
84  *      map[Shift+LevelThree] = Level4;
85  *
86  *   If the active modifiers, masked with the type's modifiers (as stated
87  *   above), match (i.e. equal) the modifiers inside the map[] statement,
88  *   then the level in the right hand side is chosen. For example, in the
89  *   above, if in the current keyboard state the Shift and LevelThree
90  *   modifiers are active, while the Lock modifier is not, then the
91  *   keysym(s) in the 4th level of the group will be returned to the
92  *   user.
93  *
94  * - preserve statements:
95  *      map[Shift+Lock+LevelThree] = Level5;
96  *      preserve[Shift+Lock+LevelThree] = Lock;
97  *
98  *   When a map entry matches the active modifiers and the level it
99  *   specified is chosen, then these modifiers are said to be "consumed";
100  *   for example, in a simple US keymap where the "g" key is assigned an
101  *   ordinary ALPHABETIC key type, if the Lock (Caps Lock) modifier is
102  *   active and the key is pressed, then a "G" keysym is produced (as
103  *   opposed to lower-case "g"). This is because the type definition has
104  *   a map entry like the following:
105  *      map[Lock] = Level2;
106  *   And as such the Lock modifier is consumed. This information is
107  *   relevant for applications which further process the modifiers,
108  *   since by then the consumed modifiers have already "done their part"
109  *   and should be masked out.
110  *
111  *   However, sometimes even if a modifier is actually used to choose
112  *   the shift level (as Lock above), it should *not* be reported as
113  *   consumed, for various reasons. In this case, a preserve[] statement
114  *   can be used to augment the map entry. The modifiers inside the square
115  *   brackets should match one of the map[] statements in the type. The
116  *   right hand side should consists of modifiers from the left hand
117  *   side; these modifiers are then "preserved" and not reported as
118  *   consumed.
119  *
120  * Virtual modifier statements
121  * ---------------------------
122  * Statements of the form:
123  *     virtual_modifiers LControl;
124  *
125  * Can appear in the xkb_types, xkb_compat, xkb_symbols sections.
126  * TODO
127  *
128  * Effect on keymap
129  * ----------------
130  * After all of the xkb_types sections have been compiled, the following
131  * members of struct xkb_keymap are finalized:
132  *      struct xkb_key_type *types;
133  *      unsigned int num_types;
134  *      char *types_section_name;
135  * TODO: virtual modifiers.
136  */
137
138 enum type_field {
139     TYPE_FIELD_MASK       = (1 << 0),
140     TYPE_FIELD_MAP        = (1 << 1),
141     TYPE_FIELD_PRESERVE   = (1 << 2),
142     TYPE_FIELD_LEVEL_NAME = (1 << 3),
143 };
144
145 typedef struct _KeyTypeInfo {
146     enum type_field defined;
147     unsigned file_id;
148     enum merge_mode merge;
149     struct list entry;
150
151     xkb_atom_t name;
152     xkb_mod_mask_t mods;
153     xkb_level_index_t num_levels;
154     darray(struct xkb_kt_map_entry) entries;
155     darray(xkb_atom_t) level_names;
156 } KeyTypeInfo;
157
158 typedef struct _KeyTypesInfo {
159     char *name;
160     int errorCount;
161     unsigned file_id;
162     unsigned num_types;
163     struct list types;
164     VModInfo vmods;
165     struct xkb_keymap *keymap;
166 } KeyTypesInfo;
167
168 /***====================================================================***/
169
170 static inline const char *
171 MapEntryTxt(KeyTypesInfo *info, struct xkb_kt_map_entry *entry)
172 {
173     return VModMaskText(info->keymap, entry->mods.mods);
174 }
175
176 static inline const char *
177 TypeTxt(KeyTypesInfo *info, KeyTypeInfo *type)
178 {
179     return xkb_atom_text(info->keymap->ctx, type->name);
180 }
181
182 static inline const char *
183 TypeMaskTxt(KeyTypesInfo *info, KeyTypeInfo *type)
184 {
185     return VModMaskText(info->keymap, type->mods);
186 }
187
188 static inline bool
189 ReportTypeShouldBeArray(KeyTypesInfo *info, KeyTypeInfo *type,
190                         const char *field)
191 {
192     return ReportShouldBeArray(info->keymap, "key type", field,
193                                TypeTxt(info, type));
194 }
195
196 static inline bool
197 ReportTypeBadType(KeyTypesInfo *info, KeyTypeInfo *type,
198                   const char *field, const char *wanted)
199 {
200     return ReportBadType(info->keymap->ctx, "key type", field,
201                          TypeTxt(info, type), wanted);
202 }
203
204 static inline bool
205 ReportTypeBadWidth(KeyTypesInfo *info, const char *type, int has, int needs)
206 {
207     log_err(info->keymap->ctx,
208             "Key type \"%s\" has %d levels, must have %d; "
209             "Illegal type definition ignored\n",
210             type, has, needs);
211     return false;
212 }
213
214 /***====================================================================***/
215
216 static void
217 InitKeyTypesInfo(KeyTypesInfo *info, struct xkb_keymap *keymap,
218                  unsigned file_id)
219 {
220     info->name = strdup("default");
221     info->errorCount = 0;
222     info->num_types = 0;
223     list_init(&info->types);
224     info->file_id = file_id;
225     InitVModInfo(&info->vmods, keymap);
226     info->keymap = keymap;
227 }
228
229 static void
230 FreeKeyTypeInfo(KeyTypeInfo * type)
231 {
232     darray_free(type->entries);
233     darray_free(type->level_names);
234 }
235
236 static void
237 FreeKeyTypesInfo(KeyTypesInfo * info)
238 {
239     KeyTypeInfo *type, *next_type;
240     free(info->name);
241     info->name = NULL;
242     list_foreach_safe(type, next_type, &info->types, entry) {
243         FreeKeyTypeInfo(type);
244         free(type);
245     }
246 }
247
248 static KeyTypeInfo *
249 NextKeyType(KeyTypesInfo * info)
250 {
251     KeyTypeInfo *type;
252
253     type = calloc(1, sizeof(*type));
254     if (!type)
255         return NULL;
256
257     type->file_id = info->file_id;
258
259     list_append(&type->entry, &info->types);
260     info->num_types++;
261     return type;
262 }
263
264 static KeyTypeInfo *
265 FindMatchingKeyType(KeyTypesInfo *info, xkb_atom_t name)
266 {
267     KeyTypeInfo *old;
268
269     list_foreach(old, &info->types, entry)
270         if (old->name == name)
271             return old;
272
273     return NULL;
274 }
275
276 static bool
277 AddKeyType(KeyTypesInfo *info, KeyTypeInfo *new)
278 {
279     KeyTypeInfo *old;
280     struct list entry;
281     int verbosity = xkb_get_log_verbosity(info->keymap->ctx);
282
283     old = FindMatchingKeyType(info, new->name);
284     if (old) {
285         if (new->merge == MERGE_REPLACE || new->merge == MERGE_OVERRIDE) {
286             if ((old->file_id == new->file_id && verbosity > 0) ||
287                 verbosity > 9) {
288                 log_warn(info->keymap->ctx,
289                          "Multiple definitions of the %s key type; "
290                          "Earlier definition ignored\n",
291                          xkb_atom_text(info->keymap->ctx, new->name));
292             }
293
294             entry = old->entry;
295             FreeKeyTypeInfo(old);
296             *old = *new;
297             old->entry = entry;
298             darray_init(new->entries);
299             darray_init(new->level_names);
300             return true;
301         }
302
303         if (old->file_id == new->file_id)
304             log_lvl(info->keymap->ctx, 4,
305                     "Multiple definitions of the %s key type; "
306                     "Later definition ignored\n",
307                     xkb_atom_text(info->keymap->ctx, new->name));
308
309         FreeKeyTypeInfo(new);
310         return true;
311     }
312
313     old = NextKeyType(info);
314     if (!old)
315         return false;
316
317     entry = old->entry;
318     *old = *new;
319     old->entry = entry;
320     darray_init(new->entries);
321     darray_init(new->level_names);
322     return true;
323 }
324
325 /***====================================================================***/
326
327 static void
328 MergeIncludedKeyTypes(KeyTypesInfo *into, KeyTypesInfo *from,
329                       enum merge_mode merge)
330 {
331     KeyTypeInfo *type, *next_type;
332
333     if (from->errorCount > 0) {
334         into->errorCount += from->errorCount;
335         return;
336     }
337
338     if (into->name == NULL) {
339         into->name = from->name;
340         from->name = NULL;
341     }
342
343     list_foreach_safe(type, next_type, &from->types, entry) {
344         type->merge = (merge == MERGE_DEFAULT ? type->merge : merge);
345         if (!AddKeyType(into, type))
346             into->errorCount++;
347     }
348 }
349
350 static void
351 HandleKeyTypesFile(KeyTypesInfo *info, XkbFile *file, enum merge_mode merge);
352
353 static bool
354 HandleIncludeKeyTypes(KeyTypesInfo *info, IncludeStmt *stmt)
355 {
356     enum merge_mode merge = MERGE_DEFAULT;
357     XkbFile *rtrn;
358     KeyTypesInfo included, next_incl;
359
360     InitKeyTypesInfo(&included, info->keymap, info->file_id);
361     if (stmt->stmt) {
362         free(included.name);
363         included.name = stmt->stmt;
364         stmt->stmt = NULL;
365     }
366
367     for (; stmt; stmt = stmt->next_incl) {
368         if (!ProcessIncludeFile(info->keymap->ctx, stmt, FILE_TYPE_TYPES,
369                                 &rtrn, &merge)) {
370             info->errorCount += 10;
371             FreeKeyTypesInfo(&included);
372             return false;
373         }
374
375         InitKeyTypesInfo(&next_incl, info->keymap, rtrn->id);
376
377         HandleKeyTypesFile(&next_incl, rtrn, merge);
378
379         MergeIncludedKeyTypes(&included, &next_incl, merge);
380
381         FreeKeyTypesInfo(&next_incl);
382         FreeXkbFile(rtrn);
383     }
384
385     MergeIncludedKeyTypes(info, &included, merge);
386     FreeKeyTypesInfo(&included);
387
388     return (info->errorCount == 0);
389 }
390
391 /***====================================================================***/
392
393 static bool
394 SetModifiers(KeyTypesInfo *info, KeyTypeInfo *type, ExprDef *arrayNdx,
395              ExprDef *value)
396 {
397     xkb_mod_mask_t mods;
398
399     if (arrayNdx)
400         log_warn(info->keymap->ctx,
401                  "The modifiers field of a key type is not an array; "
402                  "Illegal array subscript ignored\n");
403
404     /* get modifier mask for current type */
405     if (!ExprResolveVModMask(info->keymap, value, &mods)) {
406         log_err(info->keymap->ctx,
407                 "Key type mask field must be a modifier mask; "
408                 "Key type definition ignored\n");
409         return false;
410     }
411
412     if (type->defined & TYPE_FIELD_MASK) {
413         log_warn(info->keymap->ctx,
414                  "Multiple modifier mask definitions for key type %s; "
415                  "Using %s, ignoring %s\n",
416                  xkb_atom_text(info->keymap->ctx, type->name),
417                  TypeMaskTxt(info, type),
418                  VModMaskText(info->keymap, mods));
419         return false;
420     }
421
422     type->mods = mods;
423     return true;
424 }
425
426 /***====================================================================***/
427
428 static struct xkb_kt_map_entry *
429 FindMatchingMapEntry(KeyTypeInfo *type, xkb_mod_mask_t mods)
430 {
431     struct xkb_kt_map_entry *entry;
432
433     darray_foreach(entry, type->entries)
434         if (entry->mods.mods == mods)
435             return entry;
436
437     return NULL;
438 }
439
440 /**
441  * Add a new KTMapEntry to the given key type. If an entry with the same mods
442  * already exists, the level is updated (if clobber is TRUE). Otherwise, a new
443  * entry is created.
444  *
445  * @param clobber Overwrite existing entry.
446  * @param report true if a warning is to be printed on.
447  */
448 static bool
449 AddMapEntry(KeyTypesInfo *info, KeyTypeInfo *type,
450             struct xkb_kt_map_entry *new, bool clobber, bool report)
451 {
452     struct xkb_kt_map_entry * old;
453
454     old = FindMatchingMapEntry(type, new->mods.mods);
455     if (old) {
456         if (report && old->level != new->level) {
457             log_warn(info->keymap->ctx,
458                      "Multiple map entries for %s in %s; "
459                      "Using %d, ignoring %d\n",
460                      MapEntryTxt(info, new), TypeTxt(info, type),
461                      (clobber ? new->level : old->level) + 1,
462                      (clobber ? old->level : new->level) + 1);
463         }
464         else {
465             log_lvl(info->keymap->ctx, 10,
466                     "Multiple occurences of map[%s]= %d in %s; Ignored\n",
467                     MapEntryTxt(info, new), new->level + 1,
468                     TypeTxt(info, type));
469             return true;
470         }
471
472         if (clobber) {
473             if (new->level >= type->num_levels)
474                 type->num_levels = new->level + 1;
475             old->level = new->level;
476         }
477
478         return true;
479     }
480
481     if (new->level >= type->num_levels)
482         type->num_levels = new->level + 1;
483
484     darray_append(type->entries, *new);
485     return true;
486 }
487
488 static bool
489 SetMapEntry(KeyTypesInfo *info, KeyTypeInfo *type, ExprDef *arrayNdx,
490             ExprDef *value)
491 {
492     struct xkb_kt_map_entry entry;
493
494     if (arrayNdx == NULL)
495         return ReportTypeShouldBeArray(info, type, "map entry");
496
497     if (!ExprResolveVModMask(info->keymap, arrayNdx, &entry.mods.mods))
498         return ReportTypeBadType(info, type, "map entry", "modifier mask");
499
500     if (entry.mods.mods & (~type->mods)) {
501         log_lvl(info->keymap->ctx, 1,
502                 "Map entry for unused modifiers in %s; "
503                 "Using %s instead of %s\n",
504                 TypeTxt(info, type),
505                 VModMaskText(info->keymap, entry.mods.mods & type->mods),
506                 MapEntryTxt(info, &entry));
507         entry.mods.mods &= type->mods;
508     }
509
510     if (!ExprResolveLevel(info->keymap->ctx, value, &entry.level)) {
511         log_err(info->keymap->ctx,
512                 "Level specifications in a key type must be integer; "
513                 "Ignoring malformed level specification\n");
514         return false;
515     }
516
517     entry.preserve.mods = 0;
518
519     return AddMapEntry(info, type, &entry, true, true);
520 }
521
522 /***====================================================================***/
523
524 static bool
525 AddPreserve(KeyTypesInfo *info, KeyTypeInfo *type,
526             xkb_mod_mask_t mods, xkb_mod_mask_t preserve_mods)
527 {
528     struct xkb_kt_map_entry *entry;
529     struct xkb_kt_map_entry new;
530
531     darray_foreach(entry, type->entries) {
532         if (entry->mods.mods != mods)
533             continue;
534
535         /* Map exists without previous preserve (or "None"); override. */
536         if (entry->preserve.mods == 0) {
537             entry->preserve.mods = preserve_mods;
538             return true;
539         }
540
541         /* Map exists with same preserve; do nothing. */
542         if (entry->preserve.mods == preserve_mods) {
543             log_lvl(info->keymap->ctx, 10,
544                     "Identical definitions for preserve[%s] in %s; "
545                     "Ignored\n",
546                     VModMaskText(info->keymap, mods),
547                     TypeTxt(info, type));
548             return true;
549         }
550
551         /* Map exists with different preserve; latter wins. */
552         log_lvl(info->keymap->ctx, 1,
553                 "Multiple definitions for preserve[%s] in %s; "
554                 "Using %s, ignoring %s\n",
555                 VModMaskText(info->keymap, mods),
556                 TypeTxt(info, type),
557                 VModMaskText(info->keymap, preserve_mods),
558                 VModMaskText(info->keymap, entry->preserve.mods));
559
560         entry->preserve.mods = preserve_mods;
561         return true;
562     }
563
564     /*
565      * Map does not exist, i.e. preserve[] came before map[].
566      * Create a map with the specified mask mapping to Level1. The level
567      * may be overriden later with an explicit map[] statement.
568      */
569     new.level = 0;
570     new.mods.mods = mods;
571     new.preserve.mods = preserve_mods;
572     darray_append(type->entries, new);
573     return true;
574 }
575
576 static bool
577 SetPreserve(KeyTypesInfo *info, KeyTypeInfo *type, ExprDef *arrayNdx,
578             ExprDef *value)
579 {
580     xkb_mod_mask_t mods, preserve_mods;
581
582     if (arrayNdx == NULL)
583         return ReportTypeShouldBeArray(info, type, "preserve entry");
584
585     if (!ExprResolveVModMask(info->keymap, arrayNdx, &mods))
586         return ReportTypeBadType(info, type, "preserve entry",
587                                  "modifier mask");
588
589     if (mods & ~type->mods) {
590         const char *before, *after;
591
592         before = VModMaskText(info->keymap, mods);
593         mods &= type->mods;
594         after = VModMaskText(info->keymap, mods);
595
596         log_lvl(info->keymap->ctx, 1,
597                 "Preserve for modifiers not used by the %s type; "
598                 "Index %s converted to %s\n",
599                 TypeTxt(info, type), before, after);
600     }
601
602     if (!ExprResolveVModMask(info->keymap, value, &preserve_mods)) {
603         log_err(info->keymap->ctx,
604                 "Preserve value in a key type is not a modifier mask; "
605                 "Ignoring preserve[%s] in type %s\n",
606                 VModMaskText(info->keymap, mods),
607                 TypeTxt(info, type));
608         return false;
609     }
610
611     if (preserve_mods & ~mods) {
612         const char *before, *after;
613
614         before = VModMaskText(info->keymap, preserve_mods);
615         preserve_mods &= mods;
616         after = VModMaskText(info->keymap, preserve_mods);
617
618         log_lvl(info->keymap->ctx, 1,
619                 "Illegal value for preserve[%s] in type %s; "
620                 "Converted %s to %s\n",
621                 VModMaskText(info->keymap, mods),
622                 TypeTxt(info, type), before, after);
623     }
624
625     return AddPreserve(info, type, mods, preserve_mods);
626 }
627
628 /***====================================================================***/
629
630 static bool
631 AddLevelName(KeyTypesInfo *info, KeyTypeInfo *type,
632              xkb_level_index_t level, xkb_atom_t name, bool clobber)
633 {
634     /* New name. */
635     if (level >= darray_size(type->level_names)) {
636         darray_resize0(type->level_names, level + 1);
637         goto finish;
638     }
639
640     /* Same level, same name. */
641     if (darray_item(type->level_names, level) == name) {
642         log_lvl(info->keymap->ctx, 10,
643                 "Duplicate names for level %d of key type %s; Ignored\n",
644                 level + 1, TypeTxt(info, type));
645         return true;
646     }
647
648     /* Same level, different name. */
649     if (darray_item(type->level_names, level) != XKB_ATOM_NONE) {
650         const char *old, *new;
651         old = xkb_atom_text(info->keymap->ctx,
652                             darray_item(type->level_names, level));
653         new = xkb_atom_text(info->keymap->ctx, name);
654         log_lvl(info->keymap->ctx, 1,
655                 "Multiple names for level %d of key type %s; "
656                 "Using %s, ignoring %s\n",
657                 level + 1, TypeTxt(info, type),
658                 (clobber ? new : old), (clobber ? old : new));
659
660         if (!clobber)
661             return true;
662     }
663
664     /* XXX: What about different level, same name? */
665
666 finish:
667     darray_item(type->level_names, level) = name;
668     return true;
669 }
670
671 static bool
672 SetLevelName(KeyTypesInfo *info, KeyTypeInfo *type, ExprDef *arrayNdx,
673              ExprDef *value)
674 {
675     xkb_level_index_t level;
676     xkb_atom_t level_name;
677     struct xkb_context *ctx = info->keymap->ctx;
678     const char *str;
679
680     if (arrayNdx == NULL)
681         return ReportTypeShouldBeArray(info, type, "level name");
682
683     if (!ExprResolveLevel(ctx, arrayNdx, &level))
684         return ReportTypeBadType(info, type, "level name", "integer");
685
686     if (!ExprResolveString(ctx, value, &str)) {
687         log_err(info->keymap->ctx,
688                 "Non-string name for level %d in key type %s; "
689                 "Ignoring illegal level name definition\n",
690                 level + 1, xkb_atom_text(ctx, type->name));
691         return false;
692     }
693
694     level_name = xkb_atom_intern(ctx, str);
695
696     return AddLevelName(info, type, level, level_name, true);
697 }
698
699 /***====================================================================***/
700
701 /**
702  * Parses the fields in a type "..." { } description.
703  *
704  * @param field The field to parse (e.g. modifiers, map, level_name)
705  */
706 static bool
707 SetKeyTypeField(KeyTypesInfo *info, KeyTypeInfo *type,
708                 const char *field, ExprDef *arrayNdx, ExprDef *value)
709 {
710     bool ok = false;
711     enum type_field type_field = 0;
712
713     if (istreq(field, "modifiers")) {
714         type_field = TYPE_FIELD_MASK;
715         ok = SetModifiers(info, type, arrayNdx, value);
716     }
717     else if (istreq(field, "map")) {
718         type_field = TYPE_FIELD_MAP;
719         ok = SetMapEntry(info, type, arrayNdx, value);
720     }
721     else if (istreq(field, "preserve")) {
722         type_field = TYPE_FIELD_PRESERVE;
723         ok = SetPreserve(info, type, arrayNdx, value);
724     }
725     else if (istreq(field, "levelname") || istreq(field, "level_name")) {
726         type_field = TYPE_FIELD_LEVEL_NAME;
727         ok = SetLevelName(info, type, arrayNdx, value);
728     } else {
729         log_err(info->keymap->ctx,
730                 "Unknown field %s in key type %s; Definition ignored\n",
731                 field, TypeTxt(info, type));
732     }
733
734     type->defined |= type_field;
735     return ok;
736 }
737
738 static bool
739 HandleKeyTypeBody(KeyTypesInfo *info, VarDef *def, KeyTypeInfo *type)
740 {
741     bool ok = true;
742     const char *elem, *field;
743     ExprDef *arrayNdx;
744
745     for (; def; def = (VarDef *) def->common.next) {
746         ok = ExprResolveLhs(info->keymap->ctx, def->name, &elem, &field,
747                             &arrayNdx);
748         if (!ok)
749             continue;
750
751         if (elem && istreq(elem, "type")) {
752             log_err(info->keymap->ctx,
753                     "Support for changing the default type has been removed; "
754                     "Statement ignored\n");
755             continue;
756         }
757
758         ok = SetKeyTypeField(info, type, field, arrayNdx, def->value);
759     }
760
761     return ok;
762 }
763
764 /**
765  * Process a type "XYZ" { } specification in the xkb_types section.
766  *
767  */
768 static bool
769 HandleKeyTypeDef(KeyTypesInfo *info, KeyTypeDef *def, enum merge_mode merge)
770 {
771     KeyTypeInfo type = {
772         .defined = 0,
773         .file_id = info->file_id,
774         .merge = (def->merge == MERGE_DEFAULT ? merge : def->merge),
775         .name = def->name,
776         .mods = 0,
777         .num_levels = 1,
778         .entries = darray_new(),
779         .level_names = darray_new(),
780     };
781
782     /* Parse the actual content. */
783     if (!HandleKeyTypeBody(info, def->body, &type)) {
784         info->errorCount++;
785         return false;
786     }
787
788     /* Now add the new keytype to the info struct */
789     if (!AddKeyType(info, &type)) {
790         info->errorCount++;
791         return false;
792     }
793
794     return true;
795 }
796
797 /**
798  * Process an xkb_types section.
799  *
800  * @param file The parsed xkb_types section.
801  * @param merge Merge Strategy (e.g. MERGE_OVERRIDE)
802  * @param info Pointer to memory where the outcome will be stored.
803  */
804 static void
805 HandleKeyTypesFile(KeyTypesInfo *info, XkbFile *file, enum merge_mode merge)
806 {
807     bool ok;
808     ParseCommon *stmt;
809
810     free(info->name);
811     info->name = strdup_safe(file->name);
812
813     for (stmt = file->defs; stmt; stmt = stmt->next) {
814         switch (stmt->type) {
815         case STMT_INCLUDE:
816             ok = HandleIncludeKeyTypes(info, (IncludeStmt *) stmt);
817             break;
818         case STMT_TYPE: /* e.g. type "ONE_LEVEL" */
819             ok = HandleKeyTypeDef(info, (KeyTypeDef *) stmt, merge);
820             break;
821         case STMT_VAR:
822             log_err(info->keymap->ctx,
823                     "Support for changing the default type has been removed; "
824                     "Statement ignored\n");
825             ok = true;
826             break;
827         case STMT_VMOD: /* virtual_modifiers NumLock, ... */
828             ok = HandleVModDef((VModDef *) stmt, info->keymap, merge,
829                                &info->vmods);
830             break;
831         default:
832             log_err(info->keymap->ctx,
833                     "Key type files may not include other declarations; "
834                     "Ignoring %s\n", StmtTypeToString(stmt->type));
835             ok = false;
836             break;
837         }
838
839         if (!ok)
840             info->errorCount++;
841
842         if (info->errorCount > 10) {
843             log_err(info->keymap->ctx,
844                     "Abandoning keytypes file \"%s\"\n", file->topName);
845             break;
846         }
847     }
848 }
849
850 static bool
851 CopyDefToKeyType(KeyTypesInfo *info, KeyTypeInfo *def,
852                  struct xkb_key_type *type)
853 {
854     type->mods.mods = def->mods;
855     type->num_levels = def->num_levels;
856     type->map = darray_mem(def->entries, 0);
857     type->num_entries = darray_size(def->entries);
858     darray_init(def->entries);
859     type->name = def->name;
860     type->level_names = darray_mem(def->level_names, 0);
861     darray_init(def->level_names);
862
863     return true;
864 }
865
866 bool
867 CompileKeyTypes(XkbFile *file, struct xkb_keymap *keymap,
868                 enum merge_mode merge)
869 {
870     unsigned int i;
871     unsigned int num_types;
872     KeyTypesInfo info;
873     KeyTypeInfo *def;
874
875     InitKeyTypesInfo(&info, keymap, file->id);
876
877     HandleKeyTypesFile(&info, file, merge);
878
879     if (info.errorCount != 0)
880         goto err_info;
881
882     if (info.name)
883         keymap->types_section_name = strdup(info.name);
884
885     num_types = info.num_types ? info.num_types : 1;
886     keymap->types = calloc(num_types, sizeof(*keymap->types));
887     if (!keymap->types)
888         goto err_info;
889     keymap->num_types = num_types;
890
891     /*
892      * If no types were specified, a default unnamed one-level type is
893      * used for all keys.
894      */
895     if (info.num_types == 0) {
896         KeyTypeInfo dflt = {
897             .name = xkb_atom_intern(keymap->ctx, "default"),
898             .mods = 0,
899             .num_levels = 1,
900             .entries = darray_new(),
901             .level_names = darray_new(),
902         };
903
904         if (!CopyDefToKeyType(&info, &dflt, &keymap->types[0]))
905             goto err_info;
906     } else {
907         i = 0;
908         list_foreach(def, &info.types, entry)
909             if (!CopyDefToKeyType(&info, def, &keymap->types[i++]))
910                 goto err_info;
911     }
912
913     FreeKeyTypesInfo(&info);
914     return true;
915
916 err_info:
917     FreeKeyTypesInfo(&info);
918     return false;
919 }