compat: disallow changing global defaults from within an interpret
[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     ActionInfo *act;
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 {
245     info->keymap = keymap;
246     info->name = NULL;
247     info->file_id = file_id;
248     info->errorCount = 0;
249     darray_init(info->interps);
250     info->act = NULL;
251     info->dflt.file_id = file_id;
252     info->dflt.defined = 0;
253     info->dflt.merge = MERGE_OVERRIDE;
254     info->dflt.interp.flags = 0;
255     info->dflt.interp.virtual_mod = XkbNoModifier;
256     memset(&info->dflt.interp.act, 0, sizeof(info->dflt.interp.act));
257     info->dflt.interp.act.type = XkbSA_NoAction;
258     ClearIndicatorMapInfo(keymap->ctx, &info->ledDflt);
259     info->ledDflt.file_id = file_id;
260     info->ledDflt.defined = 0;
261     info->ledDflt.merge = MERGE_OVERRIDE;
262     darray_init(info->leds);
263     InitVModInfo(&info->vmods, keymap);
264 }
265
266 static void
267 ClearCompatInfo(CompatInfo *info)
268 {
269     struct xkb_keymap *keymap = info->keymap;
270
271     free(info->name);
272     info->name = NULL;
273     info->dflt.defined = 0;
274     info->dflt.merge = MERGE_AUGMENT;
275     info->dflt.interp.flags = 0;
276     info->dflt.interp.virtual_mod = XkbNoModifier;
277     memset(&info->dflt.interp.act, 0, sizeof(info->dflt.interp.act));
278     info->dflt.interp.act.type = XkbSA_NoAction;
279     ClearIndicatorMapInfo(keymap->ctx, &info->ledDflt);
280     darray_free(info->interps);
281     darray_free(info->leds);
282     FreeActionInfo(info->act);
283     info->act = NULL;
284     info->keymap = NULL;
285     ClearVModInfo(&info->vmods, keymap);
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                   int verbosity, enum si_field *collide)
305 {
306     if (!(old->defined & field))
307         return true;
308
309     if (new->defined & field) {
310         if ((old->file_id == new->file_id && verbosity > 0) || verbosity > 9)
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;
324     SymInterpInfo *old;
325     int verbosity = xkb_get_log_verbosity(info->keymap->ctx);
326
327     collide = 0;
328     old = FindMatchingInterp(info, new);
329     if (old != NULL) {
330         if (new->merge == MERGE_REPLACE) {
331             if ((old->file_id == new->file_id && verbosity > 0) ||
332                 verbosity > 9)
333                 log_warn(info->keymap->ctx,
334                          "Multiple definitions for \"%s\"; "
335                          "Earlier interpretation ignored\n",
336                          siText(new, info));
337             *old = *new;
338             return true;
339         }
340
341         if (UseNewInterpField(SI_FIELD_VIRTUAL_MOD, old, new, verbosity,
342                               &collide)) {
343             old->interp.virtual_mod = new->interp.virtual_mod;
344             old->defined |= SI_FIELD_VIRTUAL_MOD;
345         }
346         if (UseNewInterpField(SI_FIELD_ACTION, old, new, verbosity,
347                               &collide)) {
348             old->interp.act = new->interp.act;
349             old->defined |= SI_FIELD_ACTION;
350         }
351         if (UseNewInterpField(SI_FIELD_AUTO_REPEAT, old, new, verbosity,
352                               &collide)) {
353             old->interp.flags &= ~XkbSI_AutoRepeat;
354             old->interp.flags |= (new->interp.flags & XkbSI_AutoRepeat);
355             old->defined |= SI_FIELD_AUTO_REPEAT;
356         }
357         if (UseNewInterpField(SI_FIELD_LEVEL_ONE_ONLY, old, new, verbosity,
358                               &collide)) {
359             old->interp.match &= ~XkbSI_LevelOneOnly;
360             old->interp.match |= (new->interp.match & XkbSI_LevelOneOnly);
361             old->defined |= SI_FIELD_LEVEL_ONE_ONLY;
362         }
363
364         if (collide) {
365             log_warn(info->keymap->ctx,
366                      "Multiple interpretations of \"%s\"; "
367                      "Using %s definition for duplicate fields\n",
368                      siText(new, info),
369                      (new->merge != MERGE_AUGMENT ? "last" : "first"));
370         }
371
372         return true;
373     }
374
375     darray_append(info->interps, *new);
376     return true;
377 }
378
379
380 /***====================================================================***/
381
382 static bool
383 ResolveStateAndPredicate(ExprDef *expr, unsigned *pred_rtrn,
384                          xkb_mod_mask_t *mods_rtrn, CompatInfo *info)
385 {
386     if (expr == NULL) {
387         *pred_rtrn = XkbSI_AnyOfOrNone;
388         *mods_rtrn = ~0;
389         return true;
390     }
391
392     *pred_rtrn = XkbSI_Exactly;
393     if (expr->op == EXPR_ACTION_DECL) {
394         const char *pred_txt = xkb_atom_text(info->keymap->ctx,
395                                              expr->value.action.name);
396         if (istreq(pred_txt, "noneof"))
397             *pred_rtrn = XkbSI_NoneOf;
398         else if (istreq(pred_txt, "anyofornone"))
399             *pred_rtrn = XkbSI_AnyOfOrNone;
400         else if (istreq(pred_txt, "anyof"))
401             *pred_rtrn = XkbSI_AnyOf;
402         else if (istreq(pred_txt, "allof"))
403             *pred_rtrn = XkbSI_AllOf;
404         else if (istreq(pred_txt, "exactly"))
405             *pred_rtrn = XkbSI_Exactly;
406         else {
407             log_err(info->keymap->ctx,
408                     "Illegal modifier predicate \"%s\"; Ignored\n", pred_txt);
409             return false;
410         }
411         expr = expr->value.action.args;
412     }
413     else if (expr->op == EXPR_IDENT) {
414         const char *pred_txt = xkb_atom_text(info->keymap->ctx,
415                                              expr->value.str);
416         if (pred_txt && istreq(pred_txt, "any")) {
417             *pred_rtrn = XkbSI_AnyOf;
418             *mods_rtrn = 0xff;
419             return true;
420         }
421     }
422
423     return ExprResolveModMask(info->keymap->ctx, expr, mods_rtrn);
424 }
425
426 /***====================================================================***/
427
428 static bool
429 UseNewLEDField(enum led_field field, LEDInfo *old, LEDInfo *new,
430                int verbosity, enum led_field *collide)
431 {
432     if (!(old->defined & field))
433         return true;
434
435     if (new->defined & field) {
436         if ((old->file_id == new->file_id && verbosity > 0) || verbosity > 9)
437             *collide |= field;
438
439         if (new->merge != MERGE_AUGMENT)
440             return true;
441     }
442
443     return false;
444 }
445
446 static bool
447 AddIndicatorMap(CompatInfo *info, LEDInfo *new)
448 {
449     LEDInfo *old;
450     enum led_field collide;
451     struct xkb_context *ctx = info->keymap->ctx;
452     int verbosity = xkb_get_log_verbosity(ctx);
453
454     darray_foreach(old, info->leds) {
455         if (old->name != new->name)
456             continue;
457
458         if (old->mods == new->mods &&
459             old->groups == new->groups &&
460             old->ctrls == new->ctrls &&
461             old->which_mods == new->which_mods &&
462             old->which_groups == new->which_groups) {
463             old->defined |= new->defined;
464             return true;
465         }
466
467         if (new->merge == MERGE_REPLACE) {
468             if ((old->file_id == new->file_id && verbosity > 0) ||
469                 verbosity > 9)
470                 log_warn(info->keymap->ctx,
471                          "Map for indicator %s redefined; "
472                          "Earlier definition ignored\n",
473                          xkb_atom_text(ctx, old->name));
474             *old = *new;
475             return true;
476         }
477
478         collide = 0;
479         if (UseNewLEDField(LED_FIELD_MODS, old, new, verbosity,
480                            &collide)) {
481             old->which_mods = new->which_mods;
482             old->mods = new->mods;
483             old->defined |= LED_FIELD_MODS;
484         }
485         if (UseNewLEDField(LED_FIELD_GROUPS, old, new, verbosity,
486                            &collide)) {
487             old->which_groups = new->which_groups;
488             old->groups = new->groups;
489             old->defined |= LED_FIELD_GROUPS;
490         }
491         if (UseNewLEDField(LED_FIELD_CTRLS, old, new, verbosity,
492                            &collide)) {
493             old->ctrls = new->ctrls;
494             old->defined |= LED_FIELD_CTRLS;
495         }
496
497         if (collide) {
498             log_warn(info->keymap->ctx,
499                      "Map for indicator %s redefined; "
500                      "Using %s definition for duplicate fields\n",
501                      xkb_atom_text(ctx, old->name),
502                      (new->merge == MERGE_AUGMENT ? "first" : "last"));
503         }
504
505         return true;
506     }
507
508     darray_append(info->leds, *new);
509     return true;
510 }
511
512 static void
513 MergeIncludedCompatMaps(CompatInfo *into, CompatInfo *from,
514                         enum merge_mode merge)
515 {
516     SymInterpInfo *si;
517     LEDInfo *led;
518
519     if (from->errorCount > 0) {
520         into->errorCount += from->errorCount;
521         return;
522     }
523
524     if (into->name == NULL) {
525         into->name = from->name;
526         from->name = NULL;
527     }
528
529     darray_foreach(si, from->interps) {
530         si->merge = (merge == MERGE_DEFAULT ? si->merge : merge);
531         if (!AddInterp(into, si))
532             into->errorCount++;
533     }
534
535     darray_foreach(led, from->leds) {
536         led->merge = (merge == MERGE_DEFAULT ? led->merge : merge);
537         if (!AddIndicatorMap(into, led))
538             into->errorCount++;
539     }
540 }
541
542 static void
543 HandleCompatMapFile(CompatInfo *info, XkbFile *file, enum merge_mode merge);
544
545 static bool
546 HandleIncludeCompatMap(CompatInfo *info, IncludeStmt *stmt)
547 {
548     enum merge_mode merge = MERGE_DEFAULT;
549     XkbFile *rtrn;
550     CompatInfo included, next_incl;
551
552     InitCompatInfo(&included, info->keymap, info->file_id);
553     if (stmt->stmt) {
554         free(included.name);
555         included.name = stmt->stmt;
556         stmt->stmt = NULL;
557     }
558
559     for (; stmt; stmt = stmt->next_incl) {
560         if (!ProcessIncludeFile(info->keymap->ctx, stmt, FILE_TYPE_COMPAT,
561                                 &rtrn, &merge)) {
562             info->errorCount += 10;
563             ClearCompatInfo(&included);
564             return false;
565         }
566
567         InitCompatInfo(&next_incl, info->keymap, rtrn->id);
568         next_incl.file_id = rtrn->id;
569         next_incl.dflt = info->dflt;
570         next_incl.dflt.file_id = rtrn->id;
571         next_incl.dflt.merge = merge;
572         next_incl.ledDflt.file_id = rtrn->id;
573         next_incl.ledDflt.merge = merge;
574         next_incl.act = info->act;
575
576         HandleCompatMapFile(&next_incl, rtrn, MERGE_OVERRIDE);
577
578         MergeIncludedCompatMaps(&included, &next_incl, merge);
579         if (info->act)
580             next_incl.act = NULL;
581
582         ClearCompatInfo(&next_incl);
583         FreeXkbFile(rtrn);
584     }
585
586     MergeIncludedCompatMaps(info, &included, merge);
587     ClearCompatInfo(&included);
588
589     return (info->errorCount == 0);
590 }
591
592 static const LookupEntry useModMapValues[] = {
593     { "levelone", 1 },
594     { "level1", 1 },
595     { "anylevel", 0 },
596     { "any", 0 },
597     { NULL, 0 }
598 };
599
600 static bool
601 SetInterpField(CompatInfo *info, SymInterpInfo *si, const char *field,
602                ExprDef *arrayNdx, ExprDef *value)
603 {
604     struct xkb_keymap *keymap = info->keymap;
605     xkb_mod_index_t ndx;
606
607     if (istreq(field, "action")) {
608         if (arrayNdx)
609             return ReportSINotArray(info, si, field);
610
611         if (!HandleActionDef(value, keymap, &si->interp.act, info->act))
612             return false;
613
614         si->defined |= SI_FIELD_ACTION;
615     }
616     else if (istreq(field, "virtualmodifier") ||
617              istreq(field, "virtualmod")) {
618         if (arrayNdx)
619             return ReportSINotArray(info, si, field);
620
621         if (!ResolveVirtualModifier(value, keymap, &ndx, &info->vmods))
622             return ReportSIBadType(info, si, field, "virtual modifier");
623
624         si->interp.virtual_mod = ndx;
625         si->defined |= SI_FIELD_VIRTUAL_MOD;
626     }
627     else if (istreq(field, "repeat")) {
628         bool set;
629
630         if (arrayNdx)
631             return ReportSINotArray(info, si, field);
632
633         if (!ExprResolveBoolean(keymap->ctx, value, &set))
634             return ReportSIBadType(info, si, field, "boolean");
635
636         if (set)
637             si->interp.flags |= XkbSI_AutoRepeat;
638         else
639             si->interp.flags &= ~XkbSI_AutoRepeat;
640
641         si->defined |= SI_FIELD_AUTO_REPEAT;
642     }
643     else if (istreq(field, "locking")) {
644         log_dbg(info->keymap->ctx,
645                 "The \"locking\" field in symbol interpretation is unsupported; "
646                 "Ignored\n");
647     }
648     else if (istreq(field, "usemodmap") ||
649              istreq(field, "usemodmapmods")) {
650         unsigned int val;
651
652         if (arrayNdx)
653             return ReportSINotArray(info, si, field);
654
655         if (!ExprResolveEnum(keymap->ctx, value, &val, useModMapValues))
656             return ReportSIBadType(info, si, field, "level specification");
657
658         if (val)
659             si->interp.match |= XkbSI_LevelOneOnly;
660         else
661             si->interp.match &= ~XkbSI_LevelOneOnly;
662
663         si->defined |= SI_FIELD_LEVEL_ONE_ONLY;
664     }
665     else {
666         return ReportBadField(keymap, "symbol interpretation", field,
667                               siText(si, info));
668     }
669
670     return true;
671 }
672
673 static const LookupEntry modComponentNames[] = {
674     {"base", XkbIM_UseBase},
675     {"latched", XkbIM_UseLatched},
676     {"locked", XkbIM_UseLocked},
677     {"effective", XkbIM_UseEffective},
678     {"compat", XkbIM_UseCompat},
679     {"any", XkbIM_UseAnyMods},
680     {"none", 0},
681     {NULL, 0}
682 };
683
684 static const LookupEntry groupComponentNames[] = {
685     {"base", XkbIM_UseBase},
686     {"latched", XkbIM_UseLatched},
687     {"locked", XkbIM_UseLocked},
688     {"effective", XkbIM_UseEffective},
689     {"any", XkbIM_UseAnyGroup},
690     {"none", 0},
691     {NULL, 0}
692 };
693
694 static const LookupEntry groupNames[] = {
695     {"group1", 0x01},
696     {"group2", 0x02},
697     {"group3", 0x04},
698     {"group4", 0x08},
699     {"group5", 0x10},
700     {"group6", 0x20},
701     {"group7", 0x40},
702     {"group8", 0x80},
703     {"none", 0x00},
704     {"all", 0xff},
705     {NULL, 0}
706 };
707
708 static bool
709 SetIndicatorMapField(CompatInfo *info, LEDInfo *led,
710                      const char *field, ExprDef *arrayNdx, ExprDef *value)
711 {
712     bool ok = true;
713     struct xkb_keymap *keymap = info->keymap;
714
715     if (istreq(field, "modifiers") || istreq(field, "mods")) {
716         if (arrayNdx)
717             return ReportIndicatorNotArray(info, led, field);
718
719         if (!ExprResolveVModMask(keymap, value, &led->mods))
720             return ReportIndicatorBadType(info, led, field, "modifier mask");
721
722         led->defined |= LED_FIELD_MODS;
723     }
724     else if (istreq(field, "groups")) {
725         unsigned int mask;
726
727         if (arrayNdx)
728             return ReportIndicatorNotArray(info, led, field);
729
730         if (!ExprResolveMask(keymap->ctx, value, &mask, groupNames))
731             return ReportIndicatorBadType(info, led, field, "group mask");
732
733         led->groups = mask;
734         led->defined |= LED_FIELD_GROUPS;
735     }
736     else if (istreq(field, "controls") || istreq(field, "ctrls")) {
737         unsigned int mask;
738
739         if (arrayNdx)
740             return ReportIndicatorNotArray(info, led, field);
741
742         if (!ExprResolveMask(keymap->ctx, value, &mask, ctrlNames))
743             return ReportIndicatorBadType(info, led, field,
744                                           "controls mask");
745
746         led->ctrls = mask;
747         led->defined |= LED_FIELD_CTRLS;
748     }
749     else if (istreq(field, "allowexplicit")) {
750         log_dbg(info->keymap->ctx,
751                 "The \"allowExplicit\" field in indicator statements is unsupported; "
752                 "Ignored\n");
753     }
754     else if (istreq(field, "whichmodstate") ||
755              istreq(field, "whichmodifierstate")) {
756         unsigned int mask;
757
758         if (arrayNdx)
759             return ReportIndicatorNotArray(info, led, field);
760
761         if (!ExprResolveMask(keymap->ctx, value, &mask, modComponentNames))
762             return ReportIndicatorBadType(info, led, field,
763                                           "mask of modifier state components");
764
765         led->which_mods = mask;
766     }
767     else if (istreq(field, "whichgroupstate")) {
768         unsigned mask;
769
770         if (arrayNdx)
771             return ReportIndicatorNotArray(info, led, field);
772
773         if (!ExprResolveMask(keymap->ctx, value, &mask, groupComponentNames))
774             return ReportIndicatorBadType(info, led, field,
775                                           "mask of group state components");
776
777         led->which_groups = mask;
778     }
779     else if (istreq(field, "driveskbd") ||
780              istreq(field, "driveskeyboard") ||
781              istreq(field, "leddriveskbd") ||
782              istreq(field, "leddriveskeyboard") ||
783              istreq(field, "indicatordriveskbd") ||
784              istreq(field, "indicatordriveskeyboard")) {
785         log_dbg(info->keymap->ctx,
786                 "The \"%s\" field in indicator statements is unsupported; "
787                 "Ignored\n", field);
788     }
789     else if (istreq(field, "index")) {
790         /* Users should see this, it might cause unexpected behavior. */
791         log_err(info->keymap->ctx,
792                 "The \"index\" field in indicator statements is unsupported; "
793                 "Ignored\n");
794     }
795     else {
796         log_err(info->keymap->ctx,
797                 "Unknown field %s in map for %s indicator; "
798                 "Definition ignored\n",
799                 field, xkb_atom_text(keymap->ctx, led->name));
800         ok = false;
801     }
802
803     return ok;
804 }
805
806 static bool
807 HandleGlobalVar(CompatInfo *info, VarDef *stmt)
808 {
809     const char *elem, *field;
810     ExprDef *ndx;
811     bool ret;
812
813     if (!ExprResolveLhs(info->keymap->ctx, stmt->name, &elem, &field, &ndx))
814         ret = false;
815     else if (elem && istreq(elem, "interpret"))
816         ret = SetInterpField(info, &info->dflt, field, ndx, stmt->value);
817     else if (elem && istreq(elem, "indicator"))
818         ret = SetIndicatorMapField(info, &info->ledDflt, field, ndx,
819                                    stmt->value);
820     else
821         ret = SetActionField(info->keymap, elem, field, ndx, stmt->value,
822                              &info->act);
823     return ret;
824 }
825
826 static bool
827 HandleInterpBody(CompatInfo *info, VarDef *def, SymInterpInfo *si)
828 {
829     bool ok = true;
830     const char *elem, *field;
831     ExprDef *arrayNdx;
832
833     for (; def; def = (VarDef *) def->common.next) {
834         if (def->name && def->name->op == EXPR_FIELD_REF) {
835             log_err(info->keymap->ctx,
836                     "Cannot set a global default value from within an interpret statement; "
837                     "Move statements to the global file scope\n");
838             ok = false;
839             continue;
840         }
841
842         ok = ExprResolveLhs(info->keymap->ctx, def->name, &elem, &field,
843                             &arrayNdx);
844         if (!ok)
845             continue;
846
847         ok = SetInterpField(info, si, field, arrayNdx, def->value);
848     }
849
850     return ok;
851 }
852
853 static bool
854 HandleInterpDef(CompatInfo *info, InterpDef *def, enum merge_mode merge)
855 {
856     unsigned pred, mods;
857     SymInterpInfo si;
858
859     if (!ResolveStateAndPredicate(def->match, &pred, &mods, info)) {
860         log_err(info->keymap->ctx,
861                 "Couldn't determine matching modifiers; "
862                 "Symbol interpretation ignored\n");
863         return false;
864     }
865
866     si = info->dflt;
867
868     si.merge = merge = (def->merge == MERGE_DEFAULT ? merge : def->merge);
869
870     if (!LookupKeysym(def->sym, &si.interp.sym)) {
871         log_err(info->keymap->ctx,
872                 "Could not resolve keysym %s; "
873                 "Symbol interpretation ignored\n",
874                 def->sym);
875         return false;
876     }
877
878     si.interp.match = pred & XkbSI_OpMask;
879
880     si.interp.mods = mods;
881
882     if (!HandleInterpBody(info, def->def, &si)) {
883         info->errorCount++;
884         return false;
885     }
886
887     if (!AddInterp(info, &si)) {
888         info->errorCount++;
889         return false;
890     }
891
892     return true;
893 }
894
895 static bool
896 HandleIndicatorMapDef(CompatInfo *info, IndicatorMapDef *def,
897                       enum merge_mode merge)
898 {
899     LEDInfo led;
900     VarDef *var;
901     bool ok;
902
903     if (def->merge != MERGE_DEFAULT)
904         merge = def->merge;
905
906     led = info->ledDflt;
907     led.merge = merge;
908     led.name = def->name;
909
910     ok = true;
911     for (var = def->body; var != NULL; var = (VarDef *) var->common.next) {
912         const char *elem, *field;
913         ExprDef *arrayNdx;
914         if (!ExprResolveLhs(info->keymap->ctx, var->name, &elem, &field,
915                             &arrayNdx)) {
916             ok = false;
917             continue;
918         }
919
920         if (elem) {
921             log_err(info->keymap->ctx,
922                     "Cannot set defaults for \"%s\" element in indicator map; "
923                     "Assignment to %s.%s ignored\n", elem, elem, field);
924             ok = false;
925         }
926         else {
927             ok = SetIndicatorMapField(info, &led, field, arrayNdx,
928                                       var->value) && ok;
929         }
930     }
931
932     if (ok)
933         return AddIndicatorMap(info, &led);
934
935     return false;
936 }
937
938 static void
939 HandleCompatMapFile(CompatInfo *info, XkbFile *file, enum merge_mode merge)
940 {
941     bool ok;
942     ParseCommon *stmt;
943
944     merge = (merge == MERGE_DEFAULT ? MERGE_AUGMENT : merge);
945
946     free(info->name);
947     info->name = strdup_safe(file->name);
948
949     for (stmt = file->defs; stmt; stmt = stmt->next) {
950         switch (stmt->type) {
951         case STMT_INCLUDE:
952             ok = HandleIncludeCompatMap(info, (IncludeStmt *) stmt);
953             break;
954         case STMT_INTERP:
955             ok = HandleInterpDef(info, (InterpDef *) stmt, merge);
956             break;
957         case STMT_GROUP_COMPAT:
958             log_dbg(info->keymap->ctx,
959                     "The \"group\" statement in compat is unsupported; "
960                     "Ignored\n");
961             ok = true;
962             break;
963         case STMT_INDICATOR_MAP:
964             ok = HandleIndicatorMapDef(info, (IndicatorMapDef *) stmt, merge);
965             break;
966         case STMT_VAR:
967             ok = HandleGlobalVar(info, (VarDef *) stmt);
968             break;
969         case STMT_VMOD:
970             ok = HandleVModDef((VModDef *) stmt, info->keymap, merge,
971                                &info->vmods);
972             break;
973         default:
974             log_err(info->keymap->ctx,
975                     "Interpretation files may not include other types; "
976                     "Ignoring %s\n", StmtTypeToString(stmt->type));
977             ok = false;
978             break;
979         }
980
981         if (!ok)
982             info->errorCount++;
983
984         if (info->errorCount > 10) {
985             log_err(info->keymap->ctx,
986                     "Abandoning compatibility map \"%s\"\n", file->topName);
987             break;
988         }
989     }
990 }
991
992 static void
993 CopyInterps(CompatInfo *info, bool needSymbol, unsigned pred)
994 {
995     SymInterpInfo *si;
996
997     darray_foreach(si, info->interps) {
998         if (((si->interp.match & XkbSI_OpMask) != pred) ||
999             (needSymbol && si->interp.sym == XKB_KEY_NoSymbol) ||
1000             (!needSymbol && si->interp.sym != XKB_KEY_NoSymbol))
1001             continue;
1002
1003         darray_append(info->keymap->sym_interpret, si->interp);
1004     }
1005 }
1006
1007 static bool
1008 CopyIndicatorMapDefs(CompatInfo *info)
1009 {
1010     LEDInfo *led;
1011     struct xkb_indicator_map *im;
1012     xkb_led_index_t i;
1013     struct xkb_keymap *keymap = info->keymap;
1014
1015     darray_foreach(led, info->leds) {
1016         const char *name = xkb_atom_text(keymap->ctx, led->name);
1017
1018         /*
1019          * Find the indicator with the given name, if it was already
1020          * declared in keycodes.
1021          */
1022         im = NULL;
1023         for (i = 0; i < XkbNumIndicators; i++) {
1024             if (streq_not_null(keymap->indicator_names[i], name)) {
1025                 im = &keymap->indicators[i];
1026                 break;
1027             }
1028         }
1029
1030         /* Not previously declared; create it with next free index. */
1031         if (!im) {
1032             log_dbg(keymap->ctx,
1033                     "Indicator name \"%s\" was not declared in the keycodes section; "
1034                     "Adding new indicator\n", name);
1035
1036             for (i = 0; i < XkbNumIndicators; i++) {
1037                 if (keymap->indicator_names[i])
1038                     continue;
1039
1040                 keymap->indicator_names[i] = name;
1041                 im = &keymap->indicators[i];
1042                 break;
1043             }
1044
1045             /* Not place to put the it; ignore. */
1046             if (!im) {
1047                 log_err(keymap->ctx,
1048                         "Too many indicators (maximum is %d); "
1049                         "Indicator name \"%s\" ignored\n",
1050                         XkbNumIndicators, name);
1051                 continue;
1052             }
1053         }
1054
1055         if (led->groups != 0 && led->which_groups == 0)
1056             im->which_groups = XkbIM_UseEffective;
1057         else
1058             im->which_groups = led->which_groups;
1059         im->groups = led->groups;
1060         if (led->mods != 0 && led->which_mods == 0)
1061             im->which_mods = XkbIM_UseEffective;
1062         else
1063             im->which_mods = led->which_mods;
1064         im->mods.mods = led->mods;
1065         im->ctrls = led->ctrls;
1066     }
1067
1068     return true;
1069 }
1070
1071 bool
1072 CompileCompatMap(XkbFile *file, struct xkb_keymap *keymap,
1073                  enum merge_mode merge)
1074 {
1075     CompatInfo info;
1076
1077     InitCompatInfo(&info, keymap, file->id);
1078     info.dflt.merge = merge;
1079     info.ledDflt.merge = merge;
1080
1081     HandleCompatMapFile(&info, file, merge);
1082
1083     if (info.errorCount != 0)
1084         goto err_info;
1085
1086     if (info.name)
1087         keymap->compat_section_name = strdup(info.name);
1088
1089     if (!darray_empty(info.interps)) {
1090         CopyInterps(&info, true, XkbSI_Exactly);
1091         CopyInterps(&info, true, XkbSI_AllOf | XkbSI_NoneOf);
1092         CopyInterps(&info, true, XkbSI_AnyOf);
1093         CopyInterps(&info, true, XkbSI_AnyOfOrNone);
1094         CopyInterps(&info, false, XkbSI_Exactly);
1095         CopyInterps(&info, false, XkbSI_AllOf | XkbSI_NoneOf);
1096         CopyInterps(&info, false, XkbSI_AnyOf);
1097         CopyInterps(&info, false, XkbSI_AnyOfOrNone);
1098     }
1099
1100     if (!CopyIndicatorMapDefs(&info))
1101         info.errorCount++;
1102
1103     ClearCompatInfo(&info);
1104     return true;
1105
1106 err_info:
1107     ClearCompatInfo(&info);
1108     return false;
1109 }
1110
1111 static void
1112 ComputeEffectiveMask(struct xkb_keymap *keymap, struct xkb_mods *mods)
1113 {
1114     xkb_mod_index_t i;
1115     xkb_mod_mask_t vmask = mods->mods >> XkbNumModifiers;
1116
1117     /* The effective mask is only real mods for now. */
1118     mods->mask = mods->mods & 0xff;
1119
1120     for (i = 0; i < XkbNumVirtualMods; i++) {
1121         if (!(vmask & (1 << i)))
1122             continue;
1123         mods->mask |= keymap->vmods[i];
1124     }
1125 }
1126
1127 static void
1128 UpdateActionMods(struct xkb_keymap *keymap, union xkb_action *act,
1129                  xkb_mod_mask_t rmodmask)
1130 {
1131     unsigned int flags;
1132     struct xkb_mods *mods;
1133
1134     switch (act->type) {
1135     case XkbSA_SetMods:
1136     case XkbSA_LatchMods:
1137     case XkbSA_LockMods:
1138         flags = act->mods.flags;
1139         mods = &act->mods.mods;
1140         break;
1141
1142     case XkbSA_ISOLock:
1143         flags = act->iso.flags;
1144         mods = &act->iso.mods;
1145         break;
1146
1147     default:
1148         return;
1149     }
1150
1151     if (flags & XkbSA_UseModMapMods) {
1152         /* XXX: what's that. */
1153         mods->mods &= 0xff;
1154         mods->mods |= rmodmask;
1155     }
1156     ComputeEffectiveMask(keymap, mods);
1157 }
1158
1159 /**
1160  * Find an interpretation which applies to this particular level, either by
1161  * finding an exact match for the symbol and modifier combination, or a
1162  * generic XKB_KEY_NoSymbol match.
1163  */
1164 static struct xkb_sym_interpret *
1165 FindInterpForKey(struct xkb_keymap *keymap, struct xkb_key *key,
1166                  xkb_group_index_t group, xkb_level_index_t level)
1167 {
1168     struct xkb_sym_interpret *ret = NULL;
1169     struct xkb_sym_interpret *interp;
1170     const xkb_keysym_t *syms;
1171     int num_syms;
1172
1173     num_syms = xkb_key_get_syms_by_level(keymap, key, group, level, &syms);
1174     if (num_syms == 0)
1175         return NULL;
1176
1177     darray_foreach(interp, keymap->sym_interpret) {
1178         uint32_t mods;
1179         bool found;
1180
1181         if ((num_syms > 1 || interp->sym != syms[0]) &&
1182             interp->sym != XKB_KEY_NoSymbol)
1183             continue;
1184
1185         if (level == 0 || !(interp->match & XkbSI_LevelOneOnly))
1186             mods = key->modmap;
1187         else
1188             mods = 0;
1189
1190         switch (interp->match & XkbSI_OpMask) {
1191         case XkbSI_NoneOf:
1192             found = !(interp->mods & mods);
1193             break;
1194         case XkbSI_AnyOfOrNone:
1195             found = (!mods || (interp->mods & mods));
1196             break;
1197         case XkbSI_AnyOf:
1198             found = !!(interp->mods & mods);
1199             break;
1200         case XkbSI_AllOf:
1201             found = ((interp->mods & mods) == interp->mods);
1202             break;
1203         case XkbSI_Exactly:
1204             found = (interp->mods == mods);
1205             break;
1206         default:
1207             found = false;
1208             break;
1209         }
1210
1211         if (found && interp->sym != XKB_KEY_NoSymbol)
1212             return interp;
1213         else if (found && !ret)
1214             ret = interp;
1215     }
1216
1217     return ret;
1218 }
1219
1220 static bool
1221 ApplyInterpsToKey(struct xkb_keymap *keymap, struct xkb_key *key)
1222 {
1223 #define INTERP_SIZE (8 * 4)
1224     struct xkb_sym_interpret *interps[INTERP_SIZE];
1225     xkb_mod_mask_t vmodmask = 0;
1226     int num_acts = 0;
1227     xkb_group_index_t group;
1228     xkb_level_index_t level;
1229     unsigned int i;
1230
1231     /* If we've been told not to bind interps to this key, then don't. */
1232     if (key->explicit & XkbExplicitInterpretMask)
1233         return true;
1234
1235     for (i = 0; i < INTERP_SIZE; i++)
1236         interps[i] = NULL;
1237
1238     for (group = 0; group < key->num_groups; group++) {
1239         for (level = 0; level < XkbKeyGroupWidth(keymap, key, group);
1240              level++) {
1241             i = (group * key->width) + level;
1242             if (i >= INTERP_SIZE) /* XXX FIXME */
1243                 return false;
1244             interps[i] = FindInterpForKey(keymap, key, group, level);
1245             if (interps[i])
1246                 num_acts++;
1247         }
1248     }
1249
1250     if (num_acts && !key->actions) {
1251         key->actions = calloc(key->num_groups * key->width,
1252                               sizeof(*key->actions));
1253         if (!key->actions)
1254             return false;
1255     }
1256
1257     for (group = 0; group < key->num_groups; group++) {
1258         for (level = 0; level < XkbKeyGroupWidth(keymap, key, group);
1259              level++) {
1260             struct xkb_sym_interpret *interp;
1261
1262             i = (group * key->width) + level;
1263             interp = interps[i];
1264
1265             /* Infer default key behaviours from the base level. */
1266             if (group == 0 && level == 0) {
1267                 if (!(key->explicit & XkbExplicitAutoRepeatMask) &&
1268                     (!interp || (interp->flags & XkbSI_AutoRepeat)))
1269                     key->repeats = true;
1270             }
1271
1272             if (!interp)
1273                 continue;
1274
1275             if ((group == 0 && level == 0) ||
1276                 !(interp->match & XkbSI_LevelOneOnly)) {
1277                 if (interp->virtual_mod != XkbNoModifier)
1278                     vmodmask |= (1 << interp->virtual_mod);
1279             }
1280
1281             key->actions[i] = interp->act;
1282         }
1283     }
1284
1285     if (!(key->explicit & XkbExplicitVModMapMask))
1286         key->vmodmap = vmodmask;
1287
1288     return true;
1289 #undef INTERP_SIZE
1290 }
1291
1292 /**
1293  * This collects a bunch of disparate functions which was done in the server
1294  * at various points that really should've been done within xkbcomp.  Turns out
1295  * your actions and types are a lot more useful when any of your modifiers
1296  * other than Shift actually do something ...
1297  */
1298 bool
1299 UpdateModifiersFromCompat(struct xkb_keymap *keymap)
1300 {
1301     xkb_mod_index_t vmod;
1302     xkb_led_index_t led;
1303     unsigned int i, j;
1304     struct xkb_key *key;
1305
1306     /* Find all the interprets for the key and bind them to actions,
1307      * which will also update the vmodmap. */
1308     xkb_foreach_key(key, keymap)
1309         if (!ApplyInterpsToKey(keymap, key))
1310             return false;
1311
1312     /* Update keymap->vmods, the virtual -> real mod mapping. */
1313     for (vmod = 0; vmod < XkbNumVirtualMods; vmod++)
1314         keymap->vmods[vmod] = 0;
1315
1316     xkb_foreach_key(key, keymap) {
1317         if (!key->vmodmap)
1318             continue;
1319
1320         for (vmod = 0; vmod < XkbNumVirtualMods; vmod++) {
1321             if (!(key->vmodmap & (1 << vmod)))
1322                 continue;
1323             keymap->vmods[vmod] |= key->modmap;
1324         }
1325     }
1326
1327     /* Now update the level masks for all the types to reflect the vmods. */
1328     for (i = 0; i < keymap->num_types; i++) {
1329         ComputeEffectiveMask(keymap, &keymap->types[i].mods);
1330
1331         for (j = 0; j < keymap->types[i].num_entries; j++) {
1332             ComputeEffectiveMask(keymap, &keymap->types[i].map[j].mods);
1333             ComputeEffectiveMask(keymap, &keymap->types[i].map[j].preserve);
1334         }
1335     }
1336
1337     /* Update action modifiers. */
1338     xkb_foreach_key(key, keymap) {
1339         if (!key->actions)
1340             continue;
1341
1342         for (i = 0; i < key->num_groups * key->width; i++)
1343             UpdateActionMods(keymap, &key->actions[i], key->modmap);
1344     }
1345
1346     /* Update vmod -> indicator maps. */
1347     for (led = 0; led < XkbNumIndicators; led++)
1348         ComputeEffectiveMask(keymap, &keymap->indicators[led].mods);
1349
1350     /* Find maximum number of groups out of all keys in the keymap. */
1351     xkb_foreach_key(key, keymap)
1352         keymap->num_groups = MAX(keymap->num_groups, key->num_groups);
1353
1354     return true;
1355 }