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