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