Organize xkbcomp/ header files
[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
129 enum type_field {
130     TYPE_FIELD_MASK       = (1 << 0),
131     TYPE_FIELD_MAP        = (1 << 1),
132     TYPE_FIELD_PRESERVE   = (1 << 2),
133     TYPE_FIELD_LEVEL_NAME = (1 << 3),
134 };
135
136 typedef struct _KeyTypeInfo {
137     enum type_field defined;
138     unsigned file_id;
139     enum merge_mode merge;
140     struct list entry;
141
142     xkb_atom_t name;
143     xkb_mod_mask_t mods;
144     xkb_level_index_t num_levels;
145     darray(struct xkb_kt_map_entry) entries;
146     darray(xkb_atom_t) level_names;
147 } KeyTypeInfo;
148
149 typedef struct _KeyTypesInfo {
150     char *name;
151     int errorCount;
152     unsigned file_id;
153     unsigned num_types;
154     struct list types;
155     VModInfo vmods;
156     struct xkb_keymap *keymap;
157 } KeyTypesInfo;
158
159 /***====================================================================***/
160
161 static inline const char *
162 MapEntryTxt(KeyTypesInfo *info, struct xkb_kt_map_entry *entry)
163 {
164     return VModMaskText(info->keymap, entry->mods.mods);
165 }
166
167 static inline const char *
168 TypeTxt(KeyTypesInfo *info, KeyTypeInfo *type)
169 {
170     return xkb_atom_text(info->keymap->ctx, type->name);
171 }
172
173 static inline const char *
174 TypeMaskTxt(KeyTypesInfo *info, KeyTypeInfo *type)
175 {
176     return VModMaskText(info->keymap, type->mods);
177 }
178
179 static inline bool
180 ReportTypeShouldBeArray(KeyTypesInfo *info, KeyTypeInfo *type,
181                         const char *field)
182 {
183     return ReportShouldBeArray(info->keymap, "key type", field,
184                                TypeTxt(info, type));
185 }
186
187 static inline bool
188 ReportTypeBadType(KeyTypesInfo *info, KeyTypeInfo *type,
189                   const char *field, const char *wanted)
190 {
191     return ReportBadType(info->keymap->ctx, "key type", field,
192                          TypeTxt(info, type), wanted);
193 }
194
195 static inline bool
196 ReportTypeBadWidth(KeyTypesInfo *info, const char *type, int has, int needs)
197 {
198     log_err(info->keymap->ctx,
199             "Key type \"%s\" has %d levels, must have %d; "
200             "Illegal type definition ignored\n",
201             type, has, needs);
202     return false;
203 }
204
205 /***====================================================================***/
206
207 static void
208 InitKeyTypesInfo(KeyTypesInfo *info, struct xkb_keymap *keymap,
209                  unsigned file_id)
210 {
211     info->name = strdup("default");
212     info->errorCount = 0;
213     info->num_types = 0;
214     list_init(&info->types);
215     info->file_id = file_id;
216     InitVModInfo(&info->vmods, keymap);
217     info->keymap = keymap;
218 }
219
220 static void
221 FreeKeyTypeInfo(KeyTypeInfo * type)
222 {
223     darray_free(type->entries);
224     darray_free(type->level_names);
225 }
226
227 static void
228 FreeKeyTypesInfo(KeyTypesInfo * info)
229 {
230     KeyTypeInfo *type, *next_type;
231     free(info->name);
232     info->name = NULL;
233     list_foreach_safe(type, next_type, &info->types, entry) {
234         FreeKeyTypeInfo(type);
235         free(type);
236     }
237 }
238
239 static KeyTypeInfo *
240 NextKeyType(KeyTypesInfo * info)
241 {
242     KeyTypeInfo *type;
243
244     type = calloc(1, sizeof(*type));
245     if (!type)
246         return NULL;
247
248     type->file_id = info->file_id;
249
250     list_append(&type->entry, &info->types);
251     info->num_types++;
252     return type;
253 }
254
255 static KeyTypeInfo *
256 FindMatchingKeyType(KeyTypesInfo *info, xkb_atom_t name)
257 {
258     KeyTypeInfo *old;
259
260     list_foreach(old, &info->types, entry)
261         if (old->name == name)
262             return old;
263
264     return NULL;
265 }
266
267 static bool
268 AddKeyType(KeyTypesInfo *info, KeyTypeInfo *new)
269 {
270     KeyTypeInfo *old;
271     struct list entry;
272     int verbosity = xkb_get_log_verbosity(info->keymap->ctx);
273
274     old = FindMatchingKeyType(info, new->name);
275     if (old) {
276         if (new->merge == MERGE_REPLACE || new->merge == MERGE_OVERRIDE) {
277             if ((old->file_id == new->file_id && verbosity > 0) ||
278                 verbosity > 9) {
279                 log_warn(info->keymap->ctx,
280                          "Multiple definitions of the %s key type; "
281                          "Earlier definition ignored\n",
282                          xkb_atom_text(info->keymap->ctx, new->name));
283             }
284
285             entry = old->entry;
286             FreeKeyTypeInfo(old);
287             *old = *new;
288             old->entry = entry;
289             darray_init(new->entries);
290             darray_init(new->level_names);
291             return true;
292         }
293
294         if (old->file_id == new->file_id)
295             log_lvl(info->keymap->ctx, 4,
296                     "Multiple definitions of the %s key type; "
297                     "Later definition ignored\n",
298                     xkb_atom_text(info->keymap->ctx, new->name));
299
300         FreeKeyTypeInfo(new);
301         return true;
302     }
303
304     old = NextKeyType(info);
305     if (!old)
306         return false;
307
308     entry = old->entry;
309     *old = *new;
310     old->entry = entry;
311     darray_init(new->entries);
312     darray_init(new->level_names);
313     return true;
314 }
315
316 /***====================================================================***/
317
318 static void
319 MergeIncludedKeyTypes(KeyTypesInfo *into, KeyTypesInfo *from,
320                       enum merge_mode merge)
321 {
322     KeyTypeInfo *type, *next_type;
323
324     if (from->errorCount > 0) {
325         into->errorCount += from->errorCount;
326         return;
327     }
328
329     if (into->name == NULL) {
330         into->name = from->name;
331         from->name = NULL;
332     }
333
334     list_foreach_safe(type, next_type, &from->types, entry) {
335         type->merge = (merge == MERGE_DEFAULT ? type->merge : merge);
336         if (!AddKeyType(into, type))
337             into->errorCount++;
338     }
339 }
340
341 static void
342 HandleKeyTypesFile(KeyTypesInfo *info, XkbFile *file, enum merge_mode merge);
343
344 static bool
345 HandleIncludeKeyTypes(KeyTypesInfo *info, IncludeStmt *stmt)
346 {
347     enum merge_mode merge = MERGE_DEFAULT;
348     XkbFile *rtrn;
349     KeyTypesInfo included, next_incl;
350
351     InitKeyTypesInfo(&included, info->keymap, info->file_id);
352     if (stmt->stmt) {
353         free(included.name);
354         included.name = stmt->stmt;
355         stmt->stmt = NULL;
356     }
357
358     for (; stmt; stmt = stmt->next_incl) {
359         if (!ProcessIncludeFile(info->keymap->ctx, stmt, FILE_TYPE_TYPES,
360                                 &rtrn, &merge)) {
361             info->errorCount += 10;
362             FreeKeyTypesInfo(&included);
363             return false;
364         }
365
366         InitKeyTypesInfo(&next_incl, info->keymap, rtrn->id);
367
368         HandleKeyTypesFile(&next_incl, rtrn, merge);
369
370         MergeIncludedKeyTypes(&included, &next_incl, merge);
371
372         FreeKeyTypesInfo(&next_incl);
373         FreeXkbFile(rtrn);
374     }
375
376     MergeIncludedKeyTypes(info, &included, merge);
377     FreeKeyTypesInfo(&included);
378
379     return (info->errorCount == 0);
380 }
381
382 /***====================================================================***/
383
384 static bool
385 SetModifiers(KeyTypesInfo *info, KeyTypeInfo *type, ExprDef *arrayNdx,
386              ExprDef *value)
387 {
388     xkb_mod_mask_t mods;
389
390     if (arrayNdx)
391         log_warn(info->keymap->ctx,
392                  "The modifiers field of a key type is not an array; "
393                  "Illegal array subscript ignored\n");
394
395     /* get modifier mask for current type */
396     if (!ExprResolveVModMask(info->keymap, value, &mods)) {
397         log_err(info->keymap->ctx,
398                 "Key type mask field must be a modifier mask; "
399                 "Key type definition ignored\n");
400         return false;
401     }
402
403     if (type->defined & TYPE_FIELD_MASK) {
404         log_warn(info->keymap->ctx,
405                  "Multiple modifier mask definitions for key type %s; "
406                  "Using %s, ignoring %s\n",
407                  xkb_atom_text(info->keymap->ctx, type->name),
408                  TypeMaskTxt(info, type),
409                  VModMaskText(info->keymap, mods));
410         return false;
411     }
412
413     type->mods = mods;
414     return true;
415 }
416
417 /***====================================================================***/
418
419 static struct xkb_kt_map_entry *
420 FindMatchingMapEntry(KeyTypeInfo *type, xkb_mod_mask_t mods)
421 {
422     struct xkb_kt_map_entry *entry;
423
424     darray_foreach(entry, type->entries)
425         if (entry->mods.mods == mods)
426             return entry;
427
428     return NULL;
429 }
430
431 /**
432  * Add a new KTMapEntry to the given key type. If an entry with the same mods
433  * already exists, the level is updated (if clobber is TRUE). Otherwise, a new
434  * entry is created.
435  *
436  * @param clobber Overwrite existing entry.
437  * @param report true if a warning is to be printed on.
438  */
439 static bool
440 AddMapEntry(KeyTypesInfo *info, KeyTypeInfo *type,
441             struct xkb_kt_map_entry *new, bool clobber, bool report)
442 {
443     struct xkb_kt_map_entry * old;
444
445     old = FindMatchingMapEntry(type, new->mods.mods);
446     if (old) {
447         if (report && old->level != new->level) {
448             log_warn(info->keymap->ctx,
449                      "Multiple map entries for %s in %s; "
450                      "Using %d, ignoring %d\n",
451                      MapEntryTxt(info, new), TypeTxt(info, type),
452                      (clobber ? new->level : old->level) + 1,
453                      (clobber ? old->level : new->level) + 1);
454         }
455         else {
456             log_lvl(info->keymap->ctx, 10,
457                     "Multiple occurences of map[%s]= %d in %s; Ignored\n",
458                     MapEntryTxt(info, new), new->level + 1,
459                     TypeTxt(info, type));
460             return true;
461         }
462
463         if (clobber) {
464             if (new->level >= type->num_levels)
465                 type->num_levels = new->level + 1;
466             old->level = new->level;
467         }
468
469         return true;
470     }
471
472     if (new->level >= type->num_levels)
473         type->num_levels = new->level + 1;
474
475     darray_append(type->entries, *new);
476     return true;
477 }
478
479 static bool
480 SetMapEntry(KeyTypesInfo *info, KeyTypeInfo *type, ExprDef *arrayNdx,
481             ExprDef *value)
482 {
483     struct xkb_kt_map_entry entry;
484
485     if (arrayNdx == NULL)
486         return ReportTypeShouldBeArray(info, type, "map entry");
487
488     if (!ExprResolveVModMask(info->keymap, arrayNdx, &entry.mods.mods))
489         return ReportTypeBadType(info, type, "map entry", "modifier mask");
490
491     if (entry.mods.mods & (~type->mods)) {
492         log_lvl(info->keymap->ctx, 1,
493                 "Map entry for unused modifiers in %s; "
494                 "Using %s instead of %s\n",
495                 TypeTxt(info, type),
496                 VModMaskText(info->keymap, entry.mods.mods & type->mods),
497                 MapEntryTxt(info, &entry));
498         entry.mods.mods &= type->mods;
499     }
500
501     if (!ExprResolveLevel(info->keymap->ctx, value, &entry.level)) {
502         log_err(info->keymap->ctx,
503                 "Level specifications in a key type must be integer; "
504                 "Ignoring malformed level specification\n");
505         return false;
506     }
507
508     entry.preserve.mods = 0;
509
510     return AddMapEntry(info, type, &entry, true, true);
511 }
512
513 /***====================================================================***/
514
515 static bool
516 AddPreserve(KeyTypesInfo *info, KeyTypeInfo *type,
517             xkb_mod_mask_t mods, xkb_mod_mask_t preserve_mods)
518 {
519     struct xkb_kt_map_entry *entry;
520     struct xkb_kt_map_entry new;
521
522     darray_foreach(entry, type->entries) {
523         if (entry->mods.mods != mods)
524             continue;
525
526         /* Map exists without previous preserve (or "None"); override. */
527         if (entry->preserve.mods == 0) {
528             entry->preserve.mods = preserve_mods;
529             return true;
530         }
531
532         /* Map exists with same preserve; do nothing. */
533         if (entry->preserve.mods == preserve_mods) {
534             log_lvl(info->keymap->ctx, 10,
535                     "Identical definitions for preserve[%s] in %s; "
536                     "Ignored\n",
537                     VModMaskText(info->keymap, mods),
538                     TypeTxt(info, type));
539             return true;
540         }
541
542         /* Map exists with different preserve; latter wins. */
543         log_lvl(info->keymap->ctx, 1,
544                 "Multiple definitions for preserve[%s] in %s; "
545                 "Using %s, ignoring %s\n",
546                 VModMaskText(info->keymap, mods),
547                 TypeTxt(info, type),
548                 VModMaskText(info->keymap, preserve_mods),
549                 VModMaskText(info->keymap, entry->preserve.mods));
550
551         entry->preserve.mods = preserve_mods;
552         return true;
553     }
554
555     /*
556      * Map does not exist, i.e. preserve[] came before map[].
557      * Create a map with the specified mask mapping to Level1. The level
558      * may be overriden later with an explicit map[] statement.
559      */
560     new.level = 0;
561     new.mods.mods = mods;
562     new.preserve.mods = preserve_mods;
563     darray_append(type->entries, new);
564     return true;
565 }
566
567 static bool
568 SetPreserve(KeyTypesInfo *info, KeyTypeInfo *type, ExprDef *arrayNdx,
569             ExprDef *value)
570 {
571     xkb_mod_mask_t mods, preserve_mods;
572
573     if (arrayNdx == NULL)
574         return ReportTypeShouldBeArray(info, type, "preserve entry");
575
576     if (!ExprResolveVModMask(info->keymap, arrayNdx, &mods))
577         return ReportTypeBadType(info, type, "preserve entry",
578                                  "modifier mask");
579
580     if (mods & ~type->mods) {
581         const char *before, *after;
582
583         before = VModMaskText(info->keymap, mods);
584         mods &= type->mods;
585         after = VModMaskText(info->keymap, mods);
586
587         log_lvl(info->keymap->ctx, 1,
588                 "Preserve for modifiers not used by the %s type; "
589                 "Index %s converted to %s\n",
590                 TypeTxt(info, type), before, after);
591     }
592
593     if (!ExprResolveVModMask(info->keymap, value, &preserve_mods)) {
594         log_err(info->keymap->ctx,
595                 "Preserve value in a key type is not a modifier mask; "
596                 "Ignoring preserve[%s] in type %s\n",
597                 VModMaskText(info->keymap, mods),
598                 TypeTxt(info, type));
599         return false;
600     }
601
602     if (preserve_mods & ~mods) {
603         const char *before, *after;
604
605         before = VModMaskText(info->keymap, preserve_mods);
606         preserve_mods &= mods;
607         after = VModMaskText(info->keymap, preserve_mods);
608
609         log_lvl(info->keymap->ctx, 1,
610                 "Illegal value for preserve[%s] in type %s; "
611                 "Converted %s to %s\n",
612                 VModMaskText(info->keymap, mods),
613                 TypeTxt(info, type), before, after);
614     }
615
616     return AddPreserve(info, type, mods, preserve_mods);
617 }
618
619 /***====================================================================***/
620
621 static bool
622 AddLevelName(KeyTypesInfo *info, KeyTypeInfo *type,
623              xkb_level_index_t level, xkb_atom_t name, bool clobber)
624 {
625     /* New name. */
626     if (level >= darray_size(type->level_names)) {
627         darray_resize0(type->level_names, level + 1);
628         goto finish;
629     }
630
631     /* Same level, same name. */
632     if (darray_item(type->level_names, level) == name) {
633         log_lvl(info->keymap->ctx, 10,
634                 "Duplicate names for level %d of key type %s; Ignored\n",
635                 level + 1, TypeTxt(info, type));
636         return true;
637     }
638
639     /* Same level, different name. */
640     if (darray_item(type->level_names, level) != XKB_ATOM_NONE) {
641         const char *old, *new;
642         old = xkb_atom_text(info->keymap->ctx,
643                             darray_item(type->level_names, level));
644         new = xkb_atom_text(info->keymap->ctx, name);
645         log_lvl(info->keymap->ctx, 1,
646                 "Multiple names for level %d of key type %s; "
647                 "Using %s, ignoring %s\n",
648                 level + 1, TypeTxt(info, type),
649                 (clobber ? new : old), (clobber ? old : new));
650
651         if (!clobber)
652             return true;
653     }
654
655     /* XXX: What about different level, same name? */
656
657 finish:
658     darray_item(type->level_names, level) = name;
659     return true;
660 }
661
662 static bool
663 SetLevelName(KeyTypesInfo *info, KeyTypeInfo *type, ExprDef *arrayNdx,
664              ExprDef *value)
665 {
666     xkb_level_index_t level;
667     xkb_atom_t level_name;
668     struct xkb_context *ctx = info->keymap->ctx;
669     const char *str;
670
671     if (arrayNdx == NULL)
672         return ReportTypeShouldBeArray(info, type, "level name");
673
674     if (!ExprResolveLevel(ctx, arrayNdx, &level))
675         return ReportTypeBadType(info, type, "level name", "integer");
676
677     if (!ExprResolveString(ctx, value, &str)) {
678         log_err(info->keymap->ctx,
679                 "Non-string name for level %d in key type %s; "
680                 "Ignoring illegal level name definition\n",
681                 level + 1, xkb_atom_text(ctx, type->name));
682         return false;
683     }
684
685     level_name = xkb_atom_intern(ctx, str);
686
687     return AddLevelName(info, type, level, level_name, true);
688 }
689
690 /***====================================================================***/
691
692 /**
693  * Parses the fields in a type "..." { } description.
694  *
695  * @param field The field to parse (e.g. modifiers, map, level_name)
696  */
697 static bool
698 SetKeyTypeField(KeyTypesInfo *info, KeyTypeInfo *type,
699                 const char *field, ExprDef *arrayNdx, ExprDef *value)
700 {
701     bool ok = false;
702     enum type_field type_field = 0;
703
704     if (istreq(field, "modifiers")) {
705         type_field = TYPE_FIELD_MASK;
706         ok = SetModifiers(info, type, arrayNdx, value);
707     }
708     else if (istreq(field, "map")) {
709         type_field = TYPE_FIELD_MAP;
710         ok = SetMapEntry(info, type, arrayNdx, value);
711     }
712     else if (istreq(field, "preserve")) {
713         type_field = TYPE_FIELD_PRESERVE;
714         ok = SetPreserve(info, type, arrayNdx, value);
715     }
716     else if (istreq(field, "levelname") || istreq(field, "level_name")) {
717         type_field = TYPE_FIELD_LEVEL_NAME;
718         ok = SetLevelName(info, type, arrayNdx, value);
719     } else {
720         log_err(info->keymap->ctx,
721                 "Unknown field %s in key type %s; Definition ignored\n",
722                 field, TypeTxt(info, type));
723     }
724
725     type->defined |= type_field;
726     return ok;
727 }
728
729 static bool
730 HandleKeyTypeBody(KeyTypesInfo *info, VarDef *def, KeyTypeInfo *type)
731 {
732     bool ok = true;
733     const char *elem, *field;
734     ExprDef *arrayNdx;
735
736     for (; def; def = (VarDef *) def->common.next) {
737         ok = ExprResolveLhs(info->keymap->ctx, def->name, &elem, &field,
738                             &arrayNdx);
739         if (!ok)
740             continue;
741
742         if (elem && istreq(elem, "type")) {
743             log_err(info->keymap->ctx,
744                     "Support for changing the default type has been removed; "
745                     "Statement ignored\n");
746             continue;
747         }
748
749         ok = SetKeyTypeField(info, type, field, arrayNdx, def->value);
750     }
751
752     return ok;
753 }
754
755 /**
756  * Process a type "XYZ" { } specification in the xkb_types section.
757  *
758  */
759 static bool
760 HandleKeyTypeDef(KeyTypesInfo *info, KeyTypeDef *def, enum merge_mode merge)
761 {
762     KeyTypeInfo type = {
763         .defined = 0,
764         .file_id = info->file_id,
765         .merge = (def->merge == MERGE_DEFAULT ? merge : def->merge),
766         .name = def->name,
767         .mods = 0,
768         .num_levels = 1,
769         .entries = darray_new(),
770         .level_names = darray_new(),
771     };
772
773     /* Parse the actual content. */
774     if (!HandleKeyTypeBody(info, def->body, &type)) {
775         info->errorCount++;
776         return false;
777     }
778
779     /* Now add the new keytype to the info struct */
780     if (!AddKeyType(info, &type)) {
781         info->errorCount++;
782         return false;
783     }
784
785     return true;
786 }
787
788 /**
789  * Process an xkb_types section.
790  *
791  * @param file The parsed xkb_types section.
792  * @param merge Merge Strategy (e.g. MERGE_OVERRIDE)
793  * @param info Pointer to memory where the outcome will be stored.
794  */
795 static void
796 HandleKeyTypesFile(KeyTypesInfo *info, XkbFile *file, enum merge_mode merge)
797 {
798     bool ok;
799     ParseCommon *stmt;
800
801     free(info->name);
802     info->name = strdup_safe(file->name);
803
804     for (stmt = file->defs; stmt; stmt = stmt->next) {
805         switch (stmt->type) {
806         case STMT_INCLUDE:
807             ok = HandleIncludeKeyTypes(info, (IncludeStmt *) stmt);
808             break;
809         case STMT_TYPE: /* e.g. type "ONE_LEVEL" */
810             ok = HandleKeyTypeDef(info, (KeyTypeDef *) stmt, merge);
811             break;
812         case STMT_VAR:
813             log_err(info->keymap->ctx,
814                     "Support for changing the default type has been removed; "
815                     "Statement ignored\n");
816             ok = true;
817             break;
818         case STMT_VMOD: /* virtual_modifiers NumLock, ... */
819             ok = HandleVModDef((VModDef *) stmt, info->keymap, merge,
820                                &info->vmods);
821             break;
822         default:
823             log_err(info->keymap->ctx,
824                     "Key type files may not include other declarations; "
825                     "Ignoring %s\n", StmtTypeToString(stmt->type));
826             ok = false;
827             break;
828         }
829
830         if (!ok)
831             info->errorCount++;
832
833         if (info->errorCount > 10) {
834             log_err(info->keymap->ctx,
835                     "Abandoning keytypes file \"%s\"\n", file->topName);
836             break;
837         }
838     }
839 }
840
841 static bool
842 CopyDefToKeyType(KeyTypesInfo *info, KeyTypeInfo *def,
843                  struct xkb_key_type *type)
844 {
845     type->mods.mods = def->mods;
846     type->num_levels = def->num_levels;
847     type->map = darray_mem(def->entries, 0);
848     type->num_entries = darray_size(def->entries);
849     darray_init(def->entries);
850     type->name = def->name;
851     type->level_names = darray_mem(def->level_names, 0);
852     darray_init(def->level_names);
853
854     return true;
855 }
856
857 bool
858 CompileKeyTypes(XkbFile *file, struct xkb_keymap *keymap,
859                 enum merge_mode merge)
860 {
861     unsigned int i;
862     unsigned int num_types;
863     KeyTypesInfo info;
864     KeyTypeInfo *def;
865
866     InitKeyTypesInfo(&info, keymap, file->id);
867
868     HandleKeyTypesFile(&info, file, merge);
869
870     if (info.errorCount != 0)
871         goto err_info;
872
873     if (info.name)
874         keymap->types_section_name = strdup(info.name);
875
876     num_types = info.num_types ? info.num_types : 1;
877     keymap->types = calloc(num_types, sizeof(*keymap->types));
878     if (!keymap->types)
879         goto err_info;
880     keymap->num_types = num_types;
881
882     /*
883      * If no types were specified, a default unnamed one-level type is
884      * used for all keys.
885      */
886     if (info.num_types == 0) {
887         KeyTypeInfo dflt = {
888             .name = xkb_atom_intern(keymap->ctx, "default"),
889             .mods = 0,
890             .num_levels = 1,
891             .entries = darray_new(),
892             .level_names = darray_new(),
893         };
894
895         if (!CopyDefToKeyType(&info, &dflt, &keymap->types[0]))
896             goto err_info;
897     } else {
898         i = 0;
899         list_foreach(def, &info.types, entry)
900             if (!CopyDefToKeyType(&info, def, &keymap->types[i++]))
901                 goto err_info;
902     }
903
904     FreeKeyTypesInfo(&info);
905     return true;
906
907 err_info:
908     FreeKeyTypesInfo(&info);
909     return false;
910 }