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