Use XKB_MOD_INVALID instead of XkbNoModifier
[platform/upstream/libxkbcommon.git] / src / xkbcomp / compat.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 "expr.h"
30 #include "action.h"
31 #include "vmod.h"
32 #include "include.h"
33
34 /*
35  * The xkb_compat section
36  * =====================
37  * This section is the third to be processesed, after xkb_keycodes and
38  * xkb_types.
39  *
40  * Interpret statements
41  * --------------------
42  * Statements of the form:
43  *      interpret Num_Lock+Any { ... }
44  *
45  * The body of the statment may include statements of the following
46  * forms:
47  *
48  * - action statement:
49  *      action = LockMods(modifiers=NumLock);
50  *
51  * - virtual modifier statement:
52  *      virtualModifier = NumLock;
53  *
54  * - repeat statement:
55  *      repeat = True;
56  *
57  * - useModMapMods statement:
58  *      useModMapMods = level1;
59  *
60  * Indicator map statements
61  * ------------------------
62  * Statements of the form:
63  *      indicator "Shift Lock" { ... }
64  *
65  *   This statement specifies the behavior and binding of the indicator
66  *   with the given name ("Shift Lock" above). The name should have been
67  *   declared previously in the xkb_keycodes section (see Indicator name
68  *   statement), and given an index there. If it wasn't, it is created
69  *   with the next free index.
70  *   The body of the statement describes the conditions of the keyboard
71  *   state which will cause the indicator to be lit. It may include the
72  *   following statements:
73  *
74  * - modifiers statment:
75  *      modifiers = ScrollLock;
76  *
77  *   If the given modifiers are in the required state (see below), the
78  *   led is lit.
79  *
80  * - whichModifierState statment:
81  *      whichModState = Latched + Locked;
82  *
83  *   Can be any combination of:
84  *      base, latched, locked, effective
85  *      any (i.e. all of the above)
86  *      none (i.e. none of the above)
87  *      compat (this is legal, but unused)
88  *   This will cause the respective portion of the modifer state (see
89  *   struct xkb_state) to be matched against the modifiers given in the
90  *   "modifiers" statement.
91  *
92  *   Here's a simple example:
93  *      indicator "Num Lock" {
94  *          modifiers = NumLock;
95  *          whichModState = Locked;
96  *      };
97  *   Whenever the NumLock modifier is locked, the Num Lock indicator
98  *   will light up.
99  *
100  * - groups statment:
101  *      groups = All - group1;
102  *
103  *   If the given groups are in the required state (see below), the led
104  *   is lit.
105  *
106  * - whichGroupState statment:
107  *      whichGroupState = Effective;
108  *
109  *   Can be any combination of:
110  *      base, latched, locked, effective
111  *      any (i.e. all of the above)
112  *      none (i.e. none of the above)
113  *   This will cause the respective portion of the group state (see
114  *   struct xkb_state) to be matched against the groups given in the
115  *   "groups" statement.
116  *
117  *   Note: the above conditions are disjunctive, i.e. if any of them are
118  *   satisfied the led is lit.
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_compat sections have been compiled, the following
131  * members of struct xkb_keymap are finalized:
132  *      darray(struct xkb_sym_interpret) sym_interpret;
133  *      struct xkb_indicator_map indicators[XkbNumIndicators];
134  *      char *compat_section_name;
135  * TODO: virtual modifiers.
136  */
137
138 enum si_field {
139     SI_FIELD_VIRTUAL_MOD    = (1 << 0),
140     SI_FIELD_ACTION         = (1 << 1),
141     SI_FIELD_AUTO_REPEAT    = (1 << 2),
142     SI_FIELD_LEVEL_ONE_ONLY = (1 << 3),
143 };
144
145 typedef struct _SymInterpInfo {
146     enum si_field defined;
147     unsigned file_id;
148     enum merge_mode merge;
149
150     struct xkb_sym_interpret interp;
151 } SymInterpInfo;
152
153 enum led_field {
154     LED_FIELD_MODS       = (1 << 0),
155     LED_FIELD_GROUPS     = (1 << 1),
156     LED_FIELD_CTRLS      = (1 << 2),
157 };
158
159 typedef struct _LEDInfo {
160     enum led_field defined;
161     unsigned file_id;
162     enum merge_mode merge;
163
164     xkb_atom_t name;
165     unsigned char which_mods;
166     xkb_mod_mask_t mods;
167     unsigned char which_groups;
168     uint32_t groups;
169     unsigned int ctrls;
170 } LEDInfo;
171
172 typedef struct _CompatInfo {
173     char *name;
174     unsigned file_id;
175     int errorCount;
176     SymInterpInfo dflt;
177     darray(SymInterpInfo) interps;
178     LEDInfo ledDflt;
179     darray(LEDInfo) leds;
180     VModInfo vmods;
181     ActionsInfo *actions;
182     struct xkb_keymap *keymap;
183 } CompatInfo;
184
185 static const char *
186 siText(SymInterpInfo *si, CompatInfo *info)
187 {
188     static char buf[128];
189
190     if (si == &info->dflt)
191         return "default";
192
193     snprintf(buf, sizeof(buf), "%s+%s(%s)",
194              KeysymText(si->interp.sym),
195              SIMatchText(si->interp.match),
196              ModMaskText(si->interp.mods));
197     return buf;
198 }
199
200 static inline bool
201 ReportSINotArray(CompatInfo *info, SymInterpInfo *si, const char *field)
202 {
203     return ReportNotArray(info->keymap, "symbol interpretation", field,
204                           siText(si, info));
205 }
206
207 static inline bool
208 ReportSIBadType(CompatInfo *info, SymInterpInfo *si, const char *field,
209                 const char *wanted)
210 {
211     return ReportBadType(info->keymap->ctx, "symbol interpretation", field,
212                          siText(si, info), wanted);
213 }
214
215 static inline bool
216 ReportIndicatorBadType(CompatInfo *info, LEDInfo *led,
217                        const char *field, const char *wanted)
218 {
219     return ReportBadType(info->keymap->ctx, "indicator map", field,
220                          xkb_atom_text(info->keymap->ctx, led->name),
221                          wanted);
222 }
223
224 static inline bool
225 ReportIndicatorNotArray(CompatInfo *info, LEDInfo *led,
226                         const char *field)
227 {
228     return ReportNotArray(info->keymap, "indicator map", field,
229                           xkb_atom_text(info->keymap->ctx, led->name));
230 }
231
232 static void
233 ClearIndicatorMapInfo(struct xkb_context *ctx, LEDInfo *info)
234 {
235     info->name = xkb_atom_intern(ctx, "default");
236     info->which_mods = 0;
237     info->mods = 0;
238     info->which_groups = info->groups = 0;
239     info->ctrls = 0;
240 }
241
242 static void
243 InitCompatInfo(CompatInfo *info, struct xkb_keymap *keymap, unsigned file_id,
244                ActionsInfo *actions)
245 {
246     info->keymap = keymap;
247     info->name = NULL;
248     info->file_id = file_id;
249     info->errorCount = 0;
250     darray_init(info->interps);
251     info->actions = actions;
252     info->dflt.file_id = file_id;
253     info->dflt.defined = 0;
254     info->dflt.merge = MERGE_OVERRIDE;
255     info->dflt.interp.flags = 0;
256     info->dflt.interp.virtual_mod = XKB_MOD_INVALID;
257     memset(&info->dflt.interp.act, 0, sizeof(info->dflt.interp.act));
258     info->dflt.interp.act.type = XkbSA_NoAction;
259     ClearIndicatorMapInfo(keymap->ctx, &info->ledDflt);
260     info->ledDflt.file_id = file_id;
261     info->ledDflt.defined = 0;
262     info->ledDflt.merge = MERGE_OVERRIDE;
263     darray_init(info->leds);
264     InitVModInfo(&info->vmods, keymap);
265 }
266
267 static void
268 ClearCompatInfo(CompatInfo *info)
269 {
270     struct xkb_keymap *keymap = info->keymap;
271
272     free(info->name);
273     info->name = NULL;
274     info->dflt.defined = 0;
275     info->dflt.merge = MERGE_AUGMENT;
276     info->dflt.interp.flags = 0;
277     info->dflt.interp.virtual_mod = XKB_MOD_INVALID;
278     memset(&info->dflt.interp.act, 0, sizeof(info->dflt.interp.act));
279     info->dflt.interp.act.type = XkbSA_NoAction;
280     ClearIndicatorMapInfo(keymap->ctx, &info->ledDflt);
281     darray_free(info->interps);
282     darray_free(info->leds);
283     info->actions = NULL;
284     info->keymap = NULL;
285     ClearVModInfo(&info->vmods);
286 }
287
288 static SymInterpInfo *
289 FindMatchingInterp(CompatInfo *info, SymInterpInfo *new)
290 {
291     SymInterpInfo *old;
292
293     darray_foreach(old, info->interps)
294         if (old->interp.sym == new->interp.sym &&
295             old->interp.mods == new->interp.mods &&
296             old->interp.match == new->interp.match)
297             return old;
298
299     return NULL;
300 }
301
302 static bool
303 UseNewInterpField(enum si_field field, SymInterpInfo *old, SymInterpInfo *new,
304                   bool report, enum si_field *collide)
305 {
306     if (!(old->defined & field))
307         return true;
308
309     if (new->defined & field) {
310         if (report)
311             *collide |= field;
312
313         if (new->merge != MERGE_AUGMENT)
314             return true;
315     }
316
317     return false;
318 }
319
320 static bool
321 AddInterp(CompatInfo *info, SymInterpInfo *new)
322 {
323     enum si_field collide = 0;
324     SymInterpInfo *old;
325
326     old = FindMatchingInterp(info, new);
327     if (old) {
328         int verbosity = xkb_get_log_verbosity(info->keymap->ctx);
329         bool report = ((old->file_id == new->file_id && verbosity > 0) ||
330                        verbosity > 9);
331
332         if (new->merge == MERGE_REPLACE) {
333             if (report)
334                 log_warn(info->keymap->ctx,
335                          "Multiple definitions for \"%s\"; "
336                          "Earlier interpretation ignored\n",
337                          siText(new, info));
338             *old = *new;
339             return true;
340         }
341
342         if (UseNewInterpField(SI_FIELD_VIRTUAL_MOD, old, new, report,
343                               &collide)) {
344             old->interp.virtual_mod = new->interp.virtual_mod;
345             old->defined |= SI_FIELD_VIRTUAL_MOD;
346         }
347         if (UseNewInterpField(SI_FIELD_ACTION, old, new, report,
348                               &collide)) {
349             old->interp.act = new->interp.act;
350             old->defined |= SI_FIELD_ACTION;
351         }
352         if (UseNewInterpField(SI_FIELD_AUTO_REPEAT, old, new, report,
353                               &collide)) {
354             old->interp.flags &= ~XkbSI_AutoRepeat;
355             old->interp.flags |= (new->interp.flags & XkbSI_AutoRepeat);
356             old->defined |= SI_FIELD_AUTO_REPEAT;
357         }
358         if (UseNewInterpField(SI_FIELD_LEVEL_ONE_ONLY, old, new, report,
359                               &collide)) {
360             old->interp.match &= ~XkbSI_LevelOneOnly;
361             old->interp.match |= (new->interp.match & XkbSI_LevelOneOnly);
362             old->defined |= SI_FIELD_LEVEL_ONE_ONLY;
363         }
364
365         if (collide) {
366             log_warn(info->keymap->ctx,
367                      "Multiple interpretations of \"%s\"; "
368                      "Using %s definition for duplicate fields\n",
369                      siText(new, info),
370                      (new->merge != MERGE_AUGMENT ? "last" : "first"));
371         }
372
373         return true;
374     }
375
376     darray_append(info->interps, *new);
377     return true;
378 }
379
380
381 /***====================================================================***/
382
383 static bool
384 ResolveStateAndPredicate(ExprDef *expr, unsigned *pred_rtrn,
385                          xkb_mod_mask_t *mods_rtrn, CompatInfo *info)
386 {
387     if (expr == NULL) {
388         *pred_rtrn = XkbSI_AnyOfOrNone;
389         *mods_rtrn = ~0;
390         return true;
391     }
392
393     *pred_rtrn = XkbSI_Exactly;
394     if (expr->op == EXPR_ACTION_DECL) {
395         const char *pred_txt = xkb_atom_text(info->keymap->ctx,
396                                              expr->value.action.name);
397         if (istreq(pred_txt, "noneof"))
398             *pred_rtrn = XkbSI_NoneOf;
399         else if (istreq(pred_txt, "anyofornone"))
400             *pred_rtrn = XkbSI_AnyOfOrNone;
401         else if (istreq(pred_txt, "anyof"))
402             *pred_rtrn = XkbSI_AnyOf;
403         else if (istreq(pred_txt, "allof"))
404             *pred_rtrn = XkbSI_AllOf;
405         else if (istreq(pred_txt, "exactly"))
406             *pred_rtrn = XkbSI_Exactly;
407         else {
408             log_err(info->keymap->ctx,
409                     "Illegal modifier predicate \"%s\"; Ignored\n", pred_txt);
410             return false;
411         }
412         expr = expr->value.action.args;
413     }
414     else if (expr->op == EXPR_IDENT) {
415         const char *pred_txt = xkb_atom_text(info->keymap->ctx,
416                                              expr->value.str);
417         if (pred_txt && istreq(pred_txt, "any")) {
418             *pred_rtrn = XkbSI_AnyOf;
419             *mods_rtrn = 0xff;
420             return true;
421         }
422     }
423
424     return ExprResolveModMask(info->keymap->ctx, expr, mods_rtrn);
425 }
426
427 /***====================================================================***/
428
429 static bool
430 UseNewLEDField(enum led_field field, LEDInfo *old, LEDInfo *new,
431                bool report, enum led_field *collide)
432 {
433     if (!(old->defined & field))
434         return true;
435
436     if (new->defined & field) {
437         if (report)
438             *collide |= field;
439
440         if (new->merge != MERGE_AUGMENT)
441             return true;
442     }
443
444     return false;
445 }
446
447 static bool
448 AddIndicatorMap(CompatInfo *info, LEDInfo *new)
449 {
450     LEDInfo *old;
451     enum led_field collide;
452     struct xkb_context *ctx = info->keymap->ctx;
453     int verbosity = xkb_get_log_verbosity(ctx);
454
455     darray_foreach(old, info->leds) {
456         bool report;
457
458         if (old->name != new->name)
459             continue;
460
461         if (old->mods == new->mods &&
462             old->groups == new->groups &&
463             old->ctrls == new->ctrls &&
464             old->which_mods == new->which_mods &&
465             old->which_groups == new->which_groups) {
466             old->defined |= new->defined;
467             return true;
468         }
469
470         report = ((old->file_id == new->file_id && verbosity > 0) ||
471                   verbosity > 9);
472
473         if (new->merge == MERGE_REPLACE) {
474             if (report)
475                 log_warn(info->keymap->ctx,
476                          "Map for indicator %s redefined; "
477                          "Earlier definition ignored\n",
478                          xkb_atom_text(ctx, old->name));
479             *old = *new;
480             return true;
481         }
482
483         collide = 0;
484         if (UseNewLEDField(LED_FIELD_MODS, old, new, report, &collide)) {
485             old->which_mods = new->which_mods;
486             old->mods = new->mods;
487             old->defined |= LED_FIELD_MODS;
488         }
489         if (UseNewLEDField(LED_FIELD_GROUPS, old, new, report, &collide)) {
490             old->which_groups = new->which_groups;
491             old->groups = new->groups;
492             old->defined |= LED_FIELD_GROUPS;
493         }
494         if (UseNewLEDField(LED_FIELD_CTRLS, old, new, report, &collide)) {
495             old->ctrls = new->ctrls;
496             old->defined |= LED_FIELD_CTRLS;
497         }
498
499         if (collide) {
500             log_warn(info->keymap->ctx,
501                      "Map for indicator %s redefined; "
502                      "Using %s definition for duplicate fields\n",
503                      xkb_atom_text(ctx, old->name),
504                      (new->merge == MERGE_AUGMENT ? "first" : "last"));
505         }
506
507         return true;
508     }
509
510     darray_append(info->leds, *new);
511     return true;
512 }
513
514 static void
515 MergeIncludedCompatMaps(CompatInfo *into, CompatInfo *from,
516                         enum merge_mode merge)
517 {
518     SymInterpInfo *si;
519     LEDInfo *led;
520
521     if (from->errorCount > 0) {
522         into->errorCount += from->errorCount;
523         return;
524     }
525
526     if (into->name == NULL) {
527         into->name = from->name;
528         from->name = NULL;
529     }
530
531     darray_foreach(si, from->interps) {
532         si->merge = (merge == MERGE_DEFAULT ? si->merge : merge);
533         if (!AddInterp(into, si))
534             into->errorCount++;
535     }
536
537     darray_foreach(led, from->leds) {
538         led->merge = (merge == MERGE_DEFAULT ? led->merge : merge);
539         if (!AddIndicatorMap(into, led))
540             into->errorCount++;
541     }
542 }
543
544 static void
545 HandleCompatMapFile(CompatInfo *info, XkbFile *file, enum merge_mode merge);
546
547 static bool
548 HandleIncludeCompatMap(CompatInfo *info, IncludeStmt *stmt)
549 {
550     enum merge_mode merge = MERGE_DEFAULT;
551     XkbFile *rtrn;
552     CompatInfo included, next_incl;
553
554     InitCompatInfo(&included, info->keymap, info->file_id, info->actions);
555     if (stmt->stmt) {
556         free(included.name);
557         included.name = stmt->stmt;
558         stmt->stmt = NULL;
559     }
560
561     for (; stmt; stmt = stmt->next_incl) {
562         if (!ProcessIncludeFile(info->keymap->ctx, stmt, FILE_TYPE_COMPAT,
563                                 &rtrn, &merge)) {
564             info->errorCount += 10;
565             ClearCompatInfo(&included);
566             return false;
567         }
568
569         InitCompatInfo(&next_incl, info->keymap, rtrn->id, info->actions);
570         next_incl.file_id = rtrn->id;
571         next_incl.dflt = info->dflt;
572         next_incl.dflt.file_id = rtrn->id;
573         next_incl.dflt.merge = merge;
574         next_incl.ledDflt.file_id = rtrn->id;
575         next_incl.ledDflt.merge = merge;
576
577         HandleCompatMapFile(&next_incl, rtrn, MERGE_OVERRIDE);
578
579         MergeIncludedCompatMaps(&included, &next_incl, merge);
580
581         ClearCompatInfo(&next_incl);
582         FreeXkbFile(rtrn);
583     }
584
585     MergeIncludedCompatMaps(info, &included, merge);
586     ClearCompatInfo(&included);
587
588     return (info->errorCount == 0);
589 }
590
591 static const LookupEntry useModMapValues[] = {
592     { "levelone", 1 },
593     { "level1", 1 },
594     { "anylevel", 0 },
595     { "any", 0 },
596     { NULL, 0 }
597 };
598
599 static bool
600 SetInterpField(CompatInfo *info, SymInterpInfo *si, const char *field,
601                ExprDef *arrayNdx, ExprDef *value)
602 {
603     struct xkb_keymap *keymap = info->keymap;
604     xkb_mod_index_t ndx;
605
606     if (istreq(field, "action")) {
607         if (arrayNdx)
608             return ReportSINotArray(info, si, field);
609
610         if (!HandleActionDef(value, keymap, &si->interp.act, info->actions))
611             return false;
612
613         si->defined |= SI_FIELD_ACTION;
614     }
615     else if (istreq(field, "virtualmodifier") ||
616              istreq(field, "virtualmod")) {
617         if (arrayNdx)
618             return ReportSINotArray(info, si, field);
619
620         if (!ResolveVirtualModifier(value, keymap, &ndx, &info->vmods))
621             return ReportSIBadType(info, si, field, "virtual modifier");
622
623         si->interp.virtual_mod = ndx;
624         si->defined |= SI_FIELD_VIRTUAL_MOD;
625     }
626     else if (istreq(field, "repeat")) {
627         bool set;
628
629         if (arrayNdx)
630             return ReportSINotArray(info, si, field);
631
632         if (!ExprResolveBoolean(keymap->ctx, value, &set))
633             return ReportSIBadType(info, si, field, "boolean");
634
635         if (set)
636             si->interp.flags |= XkbSI_AutoRepeat;
637         else
638             si->interp.flags &= ~XkbSI_AutoRepeat;
639
640         si->defined |= SI_FIELD_AUTO_REPEAT;
641     }
642     else if (istreq(field, "locking")) {
643         log_dbg(info->keymap->ctx,
644                 "The \"locking\" field in symbol interpretation is unsupported; "
645                 "Ignored\n");
646     }
647     else if (istreq(field, "usemodmap") ||
648              istreq(field, "usemodmapmods")) {
649         unsigned int val;
650
651         if (arrayNdx)
652             return ReportSINotArray(info, si, field);
653
654         if (!ExprResolveEnum(keymap->ctx, value, &val, useModMapValues))
655             return ReportSIBadType(info, si, field, "level specification");
656
657         if (val)
658             si->interp.match |= XkbSI_LevelOneOnly;
659         else
660             si->interp.match &= ~XkbSI_LevelOneOnly;
661
662         si->defined |= SI_FIELD_LEVEL_ONE_ONLY;
663     }
664     else {
665         return ReportBadField(keymap, "symbol interpretation", field,
666                               siText(si, info));
667     }
668
669     return true;
670 }
671
672 static const LookupEntry modComponentNames[] = {
673     {"base", XkbIM_UseBase},
674     {"latched", XkbIM_UseLatched},
675     {"locked", XkbIM_UseLocked},
676     {"effective", XkbIM_UseEffective},
677     {"compat", XkbIM_UseCompat},
678     {"any", XkbIM_UseAnyMods},
679     {"none", 0},
680     {NULL, 0}
681 };
682
683 static const LookupEntry groupComponentNames[] = {
684     {"base", XkbIM_UseBase},
685     {"latched", XkbIM_UseLatched},
686     {"locked", XkbIM_UseLocked},
687     {"effective", XkbIM_UseEffective},
688     {"any", XkbIM_UseAnyGroup},
689     {"none", 0},
690     {NULL, 0}
691 };
692
693 static const LookupEntry groupNames[] = {
694     {"group1", 0x01},
695     {"group2", 0x02},
696     {"group3", 0x04},
697     {"group4", 0x08},
698     {"group5", 0x10},
699     {"group6", 0x20},
700     {"group7", 0x40},
701     {"group8", 0x80},
702     {"none", 0x00},
703     {"all", 0xff},
704     {NULL, 0}
705 };
706
707 static bool
708 SetIndicatorMapField(CompatInfo *info, LEDInfo *led,
709                      const char *field, ExprDef *arrayNdx, ExprDef *value)
710 {
711     bool ok = true;
712     struct xkb_keymap *keymap = info->keymap;
713
714     if (istreq(field, "modifiers") || istreq(field, "mods")) {
715         if (arrayNdx)
716             return ReportIndicatorNotArray(info, led, field);
717
718         if (!ExprResolveVModMask(keymap, value, &led->mods))
719             return ReportIndicatorBadType(info, led, field, "modifier mask");
720
721         led->defined |= LED_FIELD_MODS;
722     }
723     else if (istreq(field, "groups")) {
724         unsigned int mask;
725
726         if (arrayNdx)
727             return ReportIndicatorNotArray(info, led, field);
728
729         if (!ExprResolveMask(keymap->ctx, value, &mask, groupNames))
730             return ReportIndicatorBadType(info, led, field, "group mask");
731
732         led->groups = mask;
733         led->defined |= LED_FIELD_GROUPS;
734     }
735     else if (istreq(field, "controls") || istreq(field, "ctrls")) {
736         unsigned int mask;
737
738         if (arrayNdx)
739             return ReportIndicatorNotArray(info, led, field);
740
741         if (!ExprResolveMask(keymap->ctx, value, &mask, ctrlNames))
742             return ReportIndicatorBadType(info, led, field,
743                                           "controls mask");
744
745         led->ctrls = mask;
746         led->defined |= LED_FIELD_CTRLS;
747     }
748     else if (istreq(field, "allowexplicit")) {
749         log_dbg(info->keymap->ctx,
750                 "The \"allowExplicit\" field in indicator statements is unsupported; "
751                 "Ignored\n");
752     }
753     else if (istreq(field, "whichmodstate") ||
754              istreq(field, "whichmodifierstate")) {
755         unsigned int mask;
756
757         if (arrayNdx)
758             return ReportIndicatorNotArray(info, led, field);
759
760         if (!ExprResolveMask(keymap->ctx, value, &mask, modComponentNames))
761             return ReportIndicatorBadType(info, led, field,
762                                           "mask of modifier state components");
763
764         led->which_mods = mask;
765     }
766     else if (istreq(field, "whichgroupstate")) {
767         unsigned mask;
768
769         if (arrayNdx)
770             return ReportIndicatorNotArray(info, led, field);
771
772         if (!ExprResolveMask(keymap->ctx, value, &mask, groupComponentNames))
773             return ReportIndicatorBadType(info, led, field,
774                                           "mask of group state components");
775
776         led->which_groups = mask;
777     }
778     else if (istreq(field, "driveskbd") ||
779              istreq(field, "driveskeyboard") ||
780              istreq(field, "leddriveskbd") ||
781              istreq(field, "leddriveskeyboard") ||
782              istreq(field, "indicatordriveskbd") ||
783              istreq(field, "indicatordriveskeyboard")) {
784         log_dbg(info->keymap->ctx,
785                 "The \"%s\" field in indicator statements is unsupported; "
786                 "Ignored\n", field);
787     }
788     else if (istreq(field, "index")) {
789         /* Users should see this, it might cause unexpected behavior. */
790         log_err(info->keymap->ctx,
791                 "The \"index\" field in indicator statements is unsupported; "
792                 "Ignored\n");
793     }
794     else {
795         log_err(info->keymap->ctx,
796                 "Unknown field %s in map for %s indicator; "
797                 "Definition ignored\n",
798                 field, xkb_atom_text(keymap->ctx, led->name));
799         ok = false;
800     }
801
802     return ok;
803 }
804
805 static bool
806 HandleGlobalVar(CompatInfo *info, VarDef *stmt)
807 {
808     const char *elem, *field;
809     ExprDef *ndx;
810     bool ret;
811
812     if (!ExprResolveLhs(info->keymap->ctx, stmt->name, &elem, &field, &ndx))
813         ret = false;
814     else if (elem && istreq(elem, "interpret"))
815         ret = SetInterpField(info, &info->dflt, field, ndx, stmt->value);
816     else if (elem && istreq(elem, "indicator"))
817         ret = SetIndicatorMapField(info, &info->ledDflt, field, ndx,
818                                    stmt->value);
819     else
820         ret = SetActionField(info->keymap, elem, field, ndx, stmt->value,
821                              info->actions);
822     return ret;
823 }
824
825 static bool
826 HandleInterpBody(CompatInfo *info, VarDef *def, SymInterpInfo *si)
827 {
828     bool ok = true;
829     const char *elem, *field;
830     ExprDef *arrayNdx;
831
832     for (; def; def = (VarDef *) def->common.next) {
833         if (def->name && def->name->op == EXPR_FIELD_REF) {
834             log_err(info->keymap->ctx,
835                     "Cannot set a global default value from within an interpret statement; "
836                     "Move statements to the global file scope\n");
837             ok = false;
838             continue;
839         }
840
841         ok = ExprResolveLhs(info->keymap->ctx, def->name, &elem, &field,
842                             &arrayNdx);
843         if (!ok)
844             continue;
845
846         ok = SetInterpField(info, si, field, arrayNdx, def->value);
847     }
848
849     return ok;
850 }
851
852 static bool
853 HandleInterpDef(CompatInfo *info, InterpDef *def, enum merge_mode merge)
854 {
855     unsigned pred, mods;
856     SymInterpInfo si;
857
858     if (!ResolveStateAndPredicate(def->match, &pred, &mods, info)) {
859         log_err(info->keymap->ctx,
860                 "Couldn't determine matching modifiers; "
861                 "Symbol interpretation ignored\n");
862         return false;
863     }
864
865     si = info->dflt;
866
867     si.merge = merge = (def->merge == MERGE_DEFAULT ? merge : def->merge);
868
869     if (!LookupKeysym(def->sym, &si.interp.sym)) {
870         log_err(info->keymap->ctx,
871                 "Could not resolve keysym %s; "
872                 "Symbol interpretation ignored\n",
873                 def->sym);
874         return false;
875     }
876
877     si.interp.match = pred & XkbSI_OpMask;
878
879     si.interp.mods = mods;
880
881     if (!HandleInterpBody(info, def->def, &si)) {
882         info->errorCount++;
883         return false;
884     }
885
886     if (!AddInterp(info, &si)) {
887         info->errorCount++;
888         return false;
889     }
890
891     return true;
892 }
893
894 static bool
895 HandleIndicatorMapDef(CompatInfo *info, IndicatorMapDef *def,
896                       enum merge_mode merge)
897 {
898     LEDInfo led;
899     VarDef *var;
900     bool ok;
901
902     if (def->merge != MERGE_DEFAULT)
903         merge = def->merge;
904
905     led = info->ledDflt;
906     led.merge = merge;
907     led.name = def->name;
908
909     ok = true;
910     for (var = def->body; var != NULL; var = (VarDef *) var->common.next) {
911         const char *elem, *field;
912         ExprDef *arrayNdx;
913         if (!ExprResolveLhs(info->keymap->ctx, var->name, &elem, &field,
914                             &arrayNdx)) {
915             ok = false;
916             continue;
917         }
918
919         if (elem) {
920             log_err(info->keymap->ctx,
921                     "Cannot set defaults for \"%s\" element in indicator map; "
922                     "Assignment to %s.%s ignored\n", elem, elem, field);
923             ok = false;
924         }
925         else {
926             ok = SetIndicatorMapField(info, &led, field, arrayNdx,
927                                       var->value) && ok;
928         }
929     }
930
931     if (ok)
932         return AddIndicatorMap(info, &led);
933
934     return false;
935 }
936
937 static void
938 HandleCompatMapFile(CompatInfo *info, XkbFile *file, enum merge_mode merge)
939 {
940     bool ok;
941     ParseCommon *stmt;
942
943     merge = (merge == MERGE_DEFAULT ? MERGE_AUGMENT : merge);
944
945     free(info->name);
946     info->name = strdup_safe(file->name);
947
948     for (stmt = file->defs; stmt; stmt = stmt->next) {
949         switch (stmt->type) {
950         case STMT_INCLUDE:
951             ok = HandleIncludeCompatMap(info, (IncludeStmt *) stmt);
952             break;
953         case STMT_INTERP:
954             ok = HandleInterpDef(info, (InterpDef *) stmt, merge);
955             break;
956         case STMT_GROUP_COMPAT:
957             log_dbg(info->keymap->ctx,
958                     "The \"group\" statement in compat is unsupported; "
959                     "Ignored\n");
960             ok = true;
961             break;
962         case STMT_INDICATOR_MAP:
963             ok = HandleIndicatorMapDef(info, (IndicatorMapDef *) stmt, merge);
964             break;
965         case STMT_VAR:
966             ok = HandleGlobalVar(info, (VarDef *) stmt);
967             break;
968         case STMT_VMOD:
969             ok = HandleVModDef((VModDef *) stmt, info->keymap, merge,
970                                &info->vmods);
971             break;
972         default:
973             log_err(info->keymap->ctx,
974                     "Interpretation files may not include other types; "
975                     "Ignoring %s\n", stmt_type_to_string(stmt->type));
976             ok = false;
977             break;
978         }
979
980         if (!ok)
981             info->errorCount++;
982
983         if (info->errorCount > 10) {
984             log_err(info->keymap->ctx,
985                     "Abandoning compatibility map \"%s\"\n", file->topName);
986             break;
987         }
988     }
989 }
990
991 static void
992 CopyInterps(CompatInfo *info, bool needSymbol, unsigned pred)
993 {
994     SymInterpInfo *si;
995
996     darray_foreach(si, info->interps) {
997         if (((si->interp.match & XkbSI_OpMask) != pred) ||
998             (needSymbol && si->interp.sym == XKB_KEY_NoSymbol) ||
999             (!needSymbol && si->interp.sym != XKB_KEY_NoSymbol))
1000             continue;
1001
1002         darray_append(info->keymap->sym_interpret, si->interp);
1003     }
1004 }
1005
1006 static void
1007 CopyIndicatorMapDefs(CompatInfo *info)
1008 {
1009     LEDInfo *led;
1010     struct xkb_indicator_map *im;
1011     xkb_led_index_t i;
1012     struct xkb_keymap *keymap = info->keymap;
1013
1014     darray_foreach(led, info->leds) {
1015         const char *name = xkb_atom_text(keymap->ctx, led->name);
1016
1017         /*
1018          * Find the indicator with the given name, if it was already
1019          * declared in keycodes.
1020          */
1021         im = NULL;
1022         for (i = 0; i < XkbNumIndicators; i++) {
1023             if (streq_not_null(keymap->indicator_names[i], name)) {
1024                 im = &keymap->indicators[i];
1025                 break;
1026             }
1027         }
1028
1029         /* Not previously declared; create it with next free index. */
1030         if (!im) {
1031             log_dbg(keymap->ctx,
1032                     "Indicator name \"%s\" was not declared in the keycodes section; "
1033                     "Adding new indicator\n", name);
1034
1035             for (i = 0; i < XkbNumIndicators; i++) {
1036                 if (keymap->indicator_names[i])
1037                     continue;
1038
1039                 keymap->indicator_names[i] = name;
1040                 im = &keymap->indicators[i];
1041                 break;
1042             }
1043
1044             /* Not place to put the it; ignore. */
1045             if (!im) {
1046                 log_err(keymap->ctx,
1047                         "Too many indicators (maximum is %d); "
1048                         "Indicator name \"%s\" ignored\n",
1049                         XkbNumIndicators, name);
1050                 continue;
1051             }
1052         }
1053
1054         if (led->groups != 0 && led->which_groups == 0)
1055             im->which_groups = XkbIM_UseEffective;
1056         else
1057             im->which_groups = led->which_groups;
1058         im->groups = led->groups;
1059         if (led->mods != 0 && led->which_mods == 0)
1060             im->which_mods = XkbIM_UseEffective;
1061         else
1062             im->which_mods = led->which_mods;
1063         im->mods.mods = led->mods;
1064         im->ctrls = led->ctrls;
1065     }
1066 }
1067
1068 static bool
1069 CopyCompatToKeymap(struct xkb_keymap *keymap, CompatInfo *info)
1070 {
1071     keymap->compat_section_name = strdup_safe(info->name);
1072
1073     if (!darray_empty(info->interps)) {
1074         /* Most specific to least specific. */
1075         CopyInterps(info, true, XkbSI_Exactly);
1076         CopyInterps(info, true, XkbSI_AllOf | XkbSI_NoneOf);
1077         CopyInterps(info, true, XkbSI_AnyOf);
1078         CopyInterps(info, true, XkbSI_AnyOfOrNone);
1079         CopyInterps(info, false, XkbSI_Exactly);
1080         CopyInterps(info, false, XkbSI_AllOf | XkbSI_NoneOf);
1081         CopyInterps(info, false, XkbSI_AnyOf);
1082         CopyInterps(info, false, XkbSI_AnyOfOrNone);
1083     }
1084
1085     CopyIndicatorMapDefs(info);
1086
1087     return true;
1088 }
1089
1090 bool
1091 CompileCompatMap(XkbFile *file, struct xkb_keymap *keymap,
1092                  enum merge_mode merge)
1093 {
1094     CompatInfo info;
1095     ActionsInfo *actions;
1096
1097     actions = NewActionsInfo();
1098     if (!actions)
1099         return false;
1100
1101     InitCompatInfo(&info, keymap, file->id, actions);
1102     info.dflt.merge = merge;
1103     info.ledDflt.merge = merge;
1104
1105     HandleCompatMapFile(&info, file, merge);
1106     if (info.errorCount != 0)
1107         goto err_info;
1108
1109     if (!CopyCompatToKeymap(keymap, &info))
1110         goto err_info;
1111
1112     ClearCompatInfo(&info);
1113     FreeActionsInfo(actions);
1114     return true;
1115
1116 err_info:
1117     ClearCompatInfo(&info);
1118     FreeActionsInfo(actions);
1119     return false;
1120 }