aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

kmap-vendor.c (23313B)


      1 // kmap-vendor.c: writes every keyboard layout of xkeyboard-config's default
      2 // ruleset (base.lst's layouts and variants, the set alpine ships as
      3 // kbd-bkeymaps) as a kmap file, the portable text kmap reads, with the pc
      4 // keyboard under them (pc.kmap), the xkb options that change keys
      5 // (options/<group>/<name>.kmap) and the key codes, types and compatibility
      6 // every xkb keymap shares (xkb/), so kmap -x writes whole keymaps alone. it was run once,
      7 // on a machine with libxkbcommon, to write share/kmap, which is kept as it
      8 // came out and installed as it is; nothing builds or runs this:
      9 //
     10 //   cc -o kmap-vendor scripts/kmap/kmap-vendor.c -lxkbcommon -lxkbregistry
     11 //   ./kmap-vendor share/kmap
     12 //
     13 // a kmap names keys by their xkb position (AE01 is the key under 1), which no
     14 // system owns, and gives each its levels: base, shift, level3 (altgr), level3
     15 // with shift, and up to eight for the layouts that have them. the typing block
     16 // is written always, any other key only where the layout makes it other than
     17 // us does. see aruu's shared/kmap.h for the format
     18 #include <errno.h>
     19 #include <stdio.h>
     20 #include <stdlib.h>
     21 #include <string.h>
     22 #include <sys/stat.h>
     23 #include <xkbcommon/xkbcommon.h>
     24 #include <xkbcommon/xkbregistry.h>
     25 
     26 // the keys layouts differ in: the typing block, the key between left shift
     27 // and z, and the keypad's decimal key. their evdev codes, xkb's minus 8
     28 static const struct {
     29   const char *name;
     30   int         evdev;
     31 } keys[] = {
     32     {"TLDE", 41}, {"AE01", 2},   {"AE02", 3},  {"AE03", 4},  {"AE04", 5},  {"AE05", 6},
     33     {"AE06", 7},  {"AE07", 8},   {"AE08", 9},  {"AE09", 10}, {"AE10", 11}, {"AE11", 12},
     34     {"AE12", 13}, {"AE13", 124}, {"AD01", 16}, {"AD02", 17}, {"AD03", 18}, {"AD04", 19},
     35     {"AD05", 20}, {"AD06", 21},  {"AD07", 22}, {"AD08", 23}, {"AD09", 24}, {"AD10", 25},
     36     {"AD11", 26}, {"AD12", 27},  {"BKSL", 43}, {"AC01", 30}, {"AC02", 31}, {"AC03", 32},
     37     {"AC04", 33}, {"AC05", 34},  {"AC06", 35}, {"AC07", 36}, {"AC08", 37}, {"AC09", 38},
     38     {"AC10", 39}, {"AC11", 40},  {"LSGT", 86}, {"AB01", 44}, {"AB02", 45}, {"AB03", 46},
     39     {"AB04", 47}, {"AB05", 48},  {"AB06", 49}, {"AB07", 50}, {"AB08", 51}, {"AB09", 52},
     40     {"AB10", 53}, {"AB11", 89},  {"SPCE", 57}, {"KPDL", 83},
     41 };
     42 
     43 static void
     44 put_utf8(FILE *fp, unsigned c)
     45 {
     46   if (c < 0x80)
     47     fputc(c, fp);
     48   else if (c < 0x800)
     49     fprintf(fp, "%c%c", 0xc0 | c >> 6, 0x80 | (c & 0x3f));
     50   else if (c < 0x10000)
     51     fprintf(fp, "%c%c%c", 0xe0 | c >> 12, 0x80 | (c >> 6 & 0x3f), 0x80 | (c & 0x3f));
     52   else
     53     fprintf(
     54         fp,
     55         "%c%c%c%c",
     56         0xf0 | c >> 18,
     57         0x80 | (c >> 12 & 0x3f),
     58         0x80 | (c >> 6 & 0x3f),
     59         0x80 | (c & 0x3f)
     60     );
     61 }
     62 
     63 // a symbol as a word: the character it types when it types one that reads as
     64 // itself, else its keysym name. a quote or # is rc quoted
     65 // every keysym written by name, which the vendored compatibility must know:
     66 // the dead keys, the modifiers, the group switches
     67 static xkb_keysym_t named[4096];
     68 static int          nnamed;
     69 
     70 static void
     71 add_named(xkb_keysym_t ks)
     72 {
     73   for (int i = 0; i < nnamed; i++)
     74     if (named[i] == ks)
     75       return;
     76   if (nnamed < (int)(sizeof(named) / sizeof(named[0])))
     77     named[nnamed++] = ks;
     78 }
     79 
     80 static void
     81 put_sym(FILE *fp, xkb_keysym_t ks)
     82 {
     83   char     name[64];
     84   unsigned c;
     85 
     86   if (ks == XKB_KEY_NoSymbol) {
     87     fputs(" none", fp);
     88     return;
     89   }
     90   c = xkb_keysym_to_utf32(ks);
     91   fputc(' ', fp);
     92   // the character only when it is that character's own keysym: KP_1 types
     93   // 1 but is the keypad's, and xkb tells them apart
     94   if (xkb_utf32_to_keysym(c) == ks && c > 0x20 && c != 0x7f && !(c >= 0x80 && c < 0xa0) && c != 0xa0
     95       && !(c >= 0x300 && c < 0x370) && !(c >= 0x200b && c <= 0x200f)) {
     96     if (c == '\'')
     97       fputs("''''", fp);
     98     else if (c == '#')
     99       fputs("'#'", fp);
    100     else
    101       put_utf8(fp, c);
    102     return;
    103   }
    104   xkb_keysym_get_name(ks, name, sizeof(name));
    105   fputs(name, fp);
    106   add_named(ks);
    107 }
    108 
    109 static int
    110 is_main(int evdev)
    111 {
    112   unsigned i;
    113 
    114   for (i = 0; i < sizeof(keys) / sizeof(keys[0]); i++)
    115     if (keys[i].evdev == evdev)
    116       return 1;
    117   return 0;
    118 }
    119 
    120 static struct xkb_keymap  *us;
    121 static struct xkb_context *ctx;
    122 
    123 // the xkb types a key may have, from the complete set xkeyboard-config
    124 // compiles every keymap with
    125 static const char *types[] = {
    126     "ONE_LEVEL",
    127     "TWO_LEVEL",
    128     "ALPHABETIC",
    129     "KEYPAD",
    130     "SHIFT+ALT",
    131     "CTRL+ALT",
    132     "THREE_LEVEL",
    133     "FOUR_LEVEL",
    134     "FOUR_LEVEL_ALPHABETIC",
    135     "FOUR_LEVEL_SEMIALPHABETIC",
    136     "FOUR_LEVEL_MIXED_KEYPAD",
    137     "FOUR_LEVEL_X",
    138     "FOUR_LEVEL_KEYPAD",
    139     "FOUR_LEVEL_PLUS_LOCK",
    140     "FOUR_LEVEL_LOCKABLE_LEVEL2",
    141     "SEPARATE_CAPS_AND_SHIFT_ALPHABETIC",
    142     "EIGHT_LEVEL",
    143     "EIGHT_LEVEL_ALPHABETIC",
    144     "EIGHT_LEVEL_SEMIALPHABETIC",
    145     "EIGHT_LEVEL_WITH_LEVEL5_LOCK",
    146     "EIGHT_LEVEL_ALPHABETIC_WITH_LEVEL5_LOCK",
    147     "PC_ALT_LEVEL2",
    148     "PC_CONTROL_LEVEL2",
    149     "PC_SUPER_LEVEL2",
    150     "PC_SHIFT_SUPER_LEVEL2",
    151     "PC_CONTROL_SUPER_LEVEL2",
    152 };
    153 #define NTYPES (sizeof(types) / sizeof(types[0]))
    154 
    155 struct key {
    156   char          name[8];
    157   xkb_keycode_t kc;
    158   xkb_keysym_t  lv[8];
    159   int           n, caps;
    160   const char   *type; // NULL when xkb chooses the one the layout has
    161 };
    162 
    163 // how a key's levels are reached: for each, the modifier sets that select it
    164 struct sig {
    165   int            levels;
    166   int            cnt[8];
    167   xkb_mod_mask_t m[8][16];
    168 };
    169 
    170 static void
    171 signature(struct xkb_keymap *km, xkb_keycode_t kc, struct sig *s)
    172 {
    173   int l, i, j;
    174 
    175   memset(s, 0, sizeof(*s));
    176   s->levels = xkb_keymap_num_levels_for_key(km, kc, 0);
    177   if (s->levels > 8)
    178     s->levels = 8;
    179   for (l = 0; l < s->levels; l++) {
    180     s->cnt[l] = xkb_keymap_key_get_mods_for_level(km, kc, 0, l, s->m[l], 16);
    181     for (i = 1; i < s->cnt[l]; i++)
    182       for (j = i; j > 0 && s->m[l][j - 1] > s->m[l][j]; j--) {
    183         xkb_mod_mask_t t = s->m[l][j];
    184         s->m[l][j]       = s->m[l][j - 1];
    185         s->m[l][j - 1]   = t;
    186       }
    187   }
    188 }
    189 
    190 // a keymap of the pc board with keys as given, each of type type (NULL:
    191 // xkb's own choice): what the generated kmap compiles to, but for the types
    192 static struct xkb_keymap *
    193 probe(const struct key *k, int nkeys, const char *type)
    194 {
    195   char              *buf;
    196   size_t             len;
    197   FILE              *fp = open_memstream(&buf, &len);
    198   struct xkb_keymap *km;
    199   int                i, l;
    200 
    201   fputs(
    202       "xkb_keymap { xkb_keycodes { include \"evdev+aliases(qwerty)\" };"
    203       " xkb_types { include \"complete\" }; xkb_compat { include \"complete\" };"
    204       " xkb_symbols { include \"pc+inet(evdev)\"\n",
    205       fp
    206   );
    207   for (i = 0; i < nkeys; i++) {
    208     fprintf(fp, "replace key <%s> { ", k[i].name);
    209     if (type)
    210       fprintf(fp, "type = \"%s\", ", type);
    211     fputs("[ ", fp);
    212     for (l = 0; l < k[i].n; l++)
    213       fprintf(fp, "%s0x%x", l ? ", " : "", k[i].lv[l]);
    214     fputs(" ] };\n", fp);
    215   }
    216   fputs("}; };\n", fp);
    217   fclose(fp);
    218   km = xkb_keymap_new_from_string(ctx, buf, XKB_KEYMAP_FORMAT_TEXT_V1, 0);
    219   free(buf);
    220   return km;
    221 }
    222 
    223 static int
    224 collect(struct xkb_keymap *km, xkb_keycode_t kc, const char *name, struct key *k)
    225 {
    226   const xkb_keysym_t *syms;
    227   unsigned            l;
    228 
    229   memset(k, 0, sizeof(*k));
    230   snprintf(k->name, sizeof(k->name), "%s", name);
    231   k->kc = kc;
    232   for (l = 0; l < 8; l++)
    233     if (xkb_keymap_key_get_syms_by_level(km, kc, 0, l, &syms) >= 1) {
    234       k->lv[l] = syms[0];
    235       k->n     = l + 1;
    236     }
    237   // caps lock shifts it when its second level is the first's capital
    238   k->caps =
    239       k->lv[0] && k->lv[1] && k->lv[0] != k->lv[1] && xkb_keysym_to_upper(k->lv[0]) == k->lv[1];
    240   // a key the layout leaves without symbols where the pc keyboard has some
    241   // is written as none, else the pc keyboard's would show through
    242   if (!k->n && km != us && xkb_keymap_num_levels_for_key(us, kc, 0) > 0) {
    243     const xkb_keysym_t *s0;
    244 
    245     if (xkb_keymap_key_get_syms_by_level(us, kc, 0, 0, &s0) >= 1)
    246       k->n = 1;
    247   }
    248   return k->n > 0;
    249 }
    250 
    251 // whether km gives kc other symbols than us does
    252 static int
    253 differs(struct xkb_keymap *km, xkb_keycode_t kc)
    254 {
    255   const xkb_keysym_t *a, *b;
    256   unsigned            l;
    257 
    258   for (l = 0; l < 8; l++) {
    259     int na = xkb_keymap_key_get_syms_by_level(km, kc, 0, l, &a);
    260     int nb = xkb_keymap_key_get_syms_by_level(us, kc, 0, l, &b);
    261 
    262     if ((na > 0 ? a[0] : 0) != (nb > 0 ? b[0] : 0))
    263       return 1;
    264   }
    265   return 0;
    266 }
    267 
    268 // the type each key needs written: none where xkb's own choice reaches the
    269 // levels the way the layout does, else the first standard type that does
    270 static void
    271 find_types(struct xkb_keymap *ref, struct key *k, int n)
    272 {
    273   struct xkb_keymap *auto_km = probe(k, n, NULL);
    274   struct sig         want, got;
    275   int                i, left = 0;
    276   unsigned           t;
    277 
    278   if (!auto_km)
    279     return;
    280   for (i = 0; i < n; i++) {
    281     signature(ref, k[i].kc, &want);
    282     signature(auto_km, k[i].kc, &got);
    283     if (memcmp(&want, &got, sizeof(want))) {
    284       k[i].type = "?";
    285       left++;
    286     }
    287   }
    288   xkb_keymap_unref(auto_km);
    289   for (t = 0; t < NTYPES && left; t++) {
    290     struct xkb_keymap *km = probe(k, n, types[t]);
    291 
    292     if (!km)
    293       continue;
    294     for (i = 0; i < n; i++) {
    295       if (!k[i].type || strcmp(k[i].type, "?"))
    296         continue;
    297       signature(ref, k[i].kc, &want);
    298       signature(km, k[i].kc, &got);
    299       if (!memcmp(&want, &got, sizeof(want))) {
    300         k[i].type = types[t];
    301         left--;
    302       }
    303     }
    304     xkb_keymap_unref(km);
    305   }
    306   for (i = 0; i < n; i++)
    307     if (k[i].type && !strcmp(k[i].type, "?")) {
    308       fprintf(stderr, "kmap-vendor: no type reaches %s's levels as the layout does\n", k[i].name);
    309       k[i].type = NULL;
    310     }
    311 }
    312 
    313 // key lines: the name, the levels, caps when caps lock shifts it, and the
    314 // type when xkb would choose another
    315 static void
    316 put_keys(FILE *fp, const struct key *k, int n)
    317 {
    318   for (int i = 0; i < n; i++) {
    319     fprintf(fp, "key %s", k[i].name);
    320     for (int l = 0; l < k[i].n; l++)
    321       put_sym(fp, k[i].lv[l]);
    322     if (k[i].caps)
    323       fputs(" caps", fp);
    324     if (k[i].type)
    325       fprintf(fp, " type=%s", k[i].type);
    326     fputc('\n', fp);
    327   }
    328 }
    329 
    330 static int
    331 write_layout(const char *dir, const char *layout, const char *variant, const char *desc)
    332 {
    333   struct xkb_rule_names names = {"evdev", "pc105", layout, variant, NULL};
    334   struct xkb_keymap    *km    = xkb_keymap_new_from_names(ctx, &names, 0);
    335   static struct key     k[1024];
    336   char                  path[1024], id[256];
    337   const xkb_keysym_t   *syms;
    338   int                   n = 0, i;
    339   FILE                 *fp;
    340 
    341   if (!km) {
    342     fprintf(
    343         stderr, "kmap-vendor: %s %s does not compile, left out\n", layout, variant ? variant : ""
    344     );
    345     return -1;
    346   }
    347   for (i = 0; i < (int)(sizeof(keys) / sizeof(keys[0])); i++)
    348     n += collect(km, keys[i].evdev + 8, keys[i].name, &k[n]);
    349   // the rest of the board where the layout changes it: the keypad, the
    350   // modifiers some layouts move. the virtual keys stay as xkb keeps them
    351   for (xkb_keycode_t kc = 8; kc <= xkb_keymap_max_keycode(km) && n < 1024; kc++) {
    352     const char *kn = xkb_keymap_key_get_name(km, kc);
    353 
    354     if (!kn || is_main(kc - 8))
    355       continue;
    356     // right alt as a bare level 3 switch is the level3 line; anything more
    357     // (a second level, another modifier) is written as the key
    358     if (kc == 100 + 8 && xkb_keymap_num_levels_for_key(km, kc, 0) == 1
    359         && xkb_keymap_key_get_syms_by_level(km, kc, 0, 0, &syms) == 1
    360         && syms[0] == XKB_KEY_ISO_Level3_Shift)
    361       continue;
    362     if (!strcmp(kn, "LVL3") || !strcmp(kn, "MDSW"))
    363       continue;
    364     if (differs(km, kc))
    365       n += collect(km, kc, kn, &k[n]);
    366   }
    367   find_types(km, k, n);
    368 
    369   snprintf(id, sizeof(id), "%s%s%s", layout, variant ? "-" : "", variant ? variant : "");
    370   snprintf(path, sizeof(path), "%s/%s", dir, layout);
    371   if (mkdir(path, 0755) != 0 && errno != EEXIST)
    372     return -1;
    373   snprintf(path, sizeof(path), "%s/%s/%s.kmap", dir, layout, variant ? variant : layout);
    374   if (!(fp = fopen(path, "w")))
    375     return -1;
    376   fprintf(fp, "kmap 1\nid %s\nlayout %s\n", id, layout);
    377   if (variant)
    378     fprintf(fp, "variant %s\n", variant);
    379   // a name with a quote in it is rc quoted whole
    380   fputs("name ", fp);
    381   if (strchr(desc, '\'')) {
    382     fputc('\'', fp);
    383     for (const char *c = desc; *c; c++)
    384       fputs(*c == '\'' ? "''" : (char[2]){*c, 0}, fp);
    385     fputc('\'', fp);
    386   } else
    387     fputs(desc, fp);
    388   fputc('\n', fp);
    389   if (xkb_keymap_key_get_syms_by_level(km, 100 + 8, 0, 0, &syms) == 1
    390       && syms[0] == XKB_KEY_ISO_Level3_Shift)
    391     fputs("level3 ralt\n", fp);
    392   put_keys(fp, k, n);
    393   fclose(fp);
    394   xkb_keymap_unref(km);
    395   return 0;
    396 }
    397 
    398 // the parts of a serialized keymap that are no layout's: its key codes, key
    399 // types and compatibility, written once as they are, xkb_<part> heads and all
    400 static int
    401 write_section(const char *dir, const char *text, const char *head, const char *file)
    402 {
    403   const char *a = strstr(text, head), *b;
    404   char        path[1024];
    405   FILE       *fp;
    406 
    407   if (!a || !(b = strstr(a, "\n};\n")))
    408     return -1;
    409   snprintf(path, sizeof(path), "%s/xkb/%s", dir, file);
    410   if (!(fp = fopen(path, "w")))
    411     return -1;
    412   fwrite(a, 1, (size_t)(b - a) + 3, fp);
    413   fputc('\n', fp);
    414   return fclose(fp);
    415 }
    416 
    417 // the keys km has, every one with symbols
    418 static int
    419 all_keys(struct xkb_keymap *km, struct key *k, int max)
    420 {
    421   int n = 0;
    422 
    423   for (xkb_keycode_t kc = xkb_keymap_min_keycode(km); kc <= xkb_keymap_max_keycode(km) && n < max;
    424        kc++) {
    425     const char *kn = xkb_keymap_key_get_name(km, kc);
    426 
    427     if (kn)
    428       n += collect(km, kc, kn, &k[n]);
    429   }
    430   return n;
    431 }
    432 
    433 // the modifier maps of a serialized keymap, by the keysyms of the keys they
    434 // list: a layout or option that moves a keysym moves its modifier with it,
    435 // as xkeyboard-config's own maps do
    436 static void
    437 put_modmaps(FILE *fp, struct xkb_keymap *km, const char *text)
    438 {
    439   const char *p = text;
    440 
    441   while ((p = strstr(p, "modifier_map "))) {
    442     char         mod[16], name[64];
    443     const char  *q = p + strlen("modifier_map "), *end = strchr(p, ';');
    444     xkb_keysym_t seen[64];
    445     int          nseen = 0;
    446 
    447     if (!end || sscanf(q, "%15s", mod) != 1)
    448       break;
    449     fprintf(fp, "modmap %s", mod);
    450     for (q = strchr(q, '<'); q && q < end; q = strchr(q + 1, '<')) {
    451       xkb_keycode_t kc;
    452 
    453       if (sscanf(q, "<%63[^>]>", name) != 1
    454           || (kc = xkb_keymap_key_by_name(km, name)) == XKB_KEYCODE_INVALID)
    455         continue;
    456       for (int l = 0; l < 8; l++) {
    457         const xkb_keysym_t *syms;
    458         char                ks[64];
    459         int                 dup = 0;
    460 
    461         if (xkb_keymap_key_get_syms_by_level(km, kc, 0, l, &syms) < 1
    462             || syms[0] == XKB_KEY_NoSymbol)
    463           continue;
    464         for (int i = 0; i < nseen; i++)
    465           dup |= seen[i] == syms[0];
    466         if (dup || nseen == 64)
    467           continue;
    468         seen[nseen++] = syms[0];
    469         xkb_keysym_get_name(syms[0], ks, sizeof(ks));
    470         fprintf(fp, " %s", ks);
    471       }
    472     }
    473     fputc('\n', fp);
    474     p = end;
    475   }
    476 }
    477 
    478 // a keymap that keeps all of xkb's types and every compatibility entry the
    479 // vendored keymaps can need: xkb writes out only what its keys use, so spare
    480 // key codes carry each type and each named keysym. its key types and
    481 // compatibility are what kmap -x writes, whole
    482 static char *
    483 full_base(void)
    484 {
    485   char              *buf;
    486   size_t             len;
    487   FILE              *fp = open_memstream(&buf, &len);
    488   struct xkb_keymap *km;
    489   unsigned           t;
    490   int                i, nkeys = (int)NTYPES + (nnamed + 7) / 8;
    491 
    492   // key codes of its own, past every real one: only this keymap has them,
    493   // and only its types and compatibility are kept
    494   fputs("xkb_keymap { xkb_keycodes { include \"evdev+aliases(qwerty)\"\n", fp);
    495   for (i = 0; i < nkeys; i++)
    496     fprintf(fp, "<Z%03d> = %d;\n", i, 2000 + i);
    497   fputs(
    498       "}; xkb_types { include \"complete\" }; xkb_compat { include \"complete\" };"
    499       " xkb_symbols { include \"pc+us+inet(evdev)\"\n",
    500       fp
    501   );
    502   for (t = 0; t < NTYPES; t++)
    503     fprintf(fp, "key <Z%03u> { type = \"%s\", [ a ] };\n", t, types[t]);
    504   for (i = 0; i < nnamed; i += 8) {
    505     fprintf(fp, "key <Z%03d> { type = \"EIGHT_LEVEL\", [ ", (int)NTYPES + i / 8);
    506     for (int l = 0; l < 8; l++)
    507       fprintf(fp, "%s0x%x", l ? ", " : "", i + l < nnamed ? named[i + l] : XKB_KEY_NoSymbol);
    508     fputs(" ] };\n", fp);
    509   }
    510   fputs("}; };\n", fp);
    511   fclose(fp);
    512   km = xkb_keymap_new_from_string(ctx, buf, XKB_KEYMAP_FORMAT_TEXT_V1, 0);
    513   free(buf);
    514   if (!km) {
    515     fprintf(stderr, "kmap-vendor: the base keymap does not compile\n");
    516     return NULL;
    517   }
    518   buf = xkb_keymap_get_as_string(km, XKB_KEYMAP_FORMAT_TEXT_V1);
    519   xkb_keymap_unref(km);
    520   return buf;
    521 }
    522 
    523 // the whole pc keyboard as kmap's own keys and modifier maps, and the xkb
    524 // parts every keymap shares: what kmap -x builds a complete keymap from
    525 static int
    526 write_pc(const char *dir, const char *full)
    527 {
    528   static struct key k[1024];
    529   char             *text = xkb_keymap_get_as_string(us, XKB_KEYMAP_FORMAT_TEXT_V1);
    530   char              path[1024];
    531   FILE             *fp;
    532   int               n;
    533 
    534   snprintf(path, sizeof(path), "%s/xkb", dir);
    535   if (!text || (mkdir(path, 0755) != 0 && errno != EEXIST))
    536     return -1;
    537   if (write_section(dir, text, "xkb_keycodes", "keycodes.xkb")
    538       || write_section(dir, full, "xkb_types", "types.xkb")
    539       || write_section(dir, full, "xkb_compatibility", "compat.xkb"))
    540     return -1;
    541   n = all_keys(us, k, 1024);
    542   find_types(us, k, n);
    543   snprintf(path, sizeof(path), "%s/pc.kmap", dir);
    544   if (!(fp = fopen(path, "w")))
    545     return -1;
    546   fputs("kmap 1\nid pc\nname the pc keyboard, its keys and modifiers, under every layout\n", fp);
    547   put_keys(fp, k, n);
    548   put_modmaps(fp, us, strstr(text, "xkb_symbols"));
    549   free(text);
    550   return fclose(fp);
    551 }
    552 
    553 // whether every line of [a, ae) is a line of [b, be)
    554 static int
    555 lines_within(const char *a, const char *ae, const char *b, const char *be)
    556 {
    557   if (!a || !ae || !b || !be)
    558     return 0;
    559   while (a < ae) {
    560     const char *nl    = memchr(a, '\n', (size_t)(ae - a)), *p;
    561     size_t      len   = nl ? (size_t)(nl - a) : (size_t)(ae - a);
    562     int         found = 0;
    563 
    564     // the virtual modifiers declared are listed whole, and differ by which
    565     // a keymap's parts use: not a part of their own
    566     if (strstr(a, "virtual_modifiers") && strstr(a, "virtual_modifiers") < a + len) {
    567       a += len + 1;
    568       continue;
    569     }
    570 
    571     for (p = b; p < be && !found;) {
    572       const char *q  = memchr(p, '\n', (size_t)(be - p));
    573       size_t      l2 = q ? (size_t)(q - p) : (size_t)(be - p);
    574 
    575       found = l2 == len && !memcmp(p, a, len);
    576       p     = q ? q + 1 : be;
    577     }
    578     if (!found)
    579       return 0;
    580     a += len + 1;
    581   }
    582   return 1;
    583 }
    584 
    585 // an xkb option as the keys it changes on the pc keyboard, a kmap laid over
    586 // the layouts. an option that changes the key types or compatibility too is
    587 // left out, said, as kmap writes those as they are
    588 static int
    589 write_option(const char *dir, const char *name, const char *base_text, int dry)
    590 {
    591   struct xkb_rule_names names = {"evdev", "pc105", "us", NULL, name};
    592   struct xkb_keymap    *km    = xkb_keymap_new_from_names(ctx, &names, 0);
    593   static struct key     k[1024];
    594   char                 *mine, *base, path[1024], group[64];
    595   const char           *colon = strchr(name, ':');
    596   int                   n = 0, rc = 0;
    597   FILE                 *fp;
    598 
    599   if (!km || !colon)
    600     return km ? (xkb_keymap_unref(km), 0) : 0;
    601   mine = xkb_keymap_get_as_string(km, XKB_KEYMAP_FORMAT_TEXT_V1);
    602   base = strdup(base_text ? base_text : "");
    603   // the first pass only learns the keysyms the option's keys carry
    604   if (dry) {
    605     for (xkb_keycode_t kc = xkb_keymap_min_keycode(km); kc <= xkb_keymap_max_keycode(km); kc++) {
    606       const xkb_keysym_t *syms;
    607 
    608       if (!xkb_keymap_key_get_name(km, kc) || !differs(km, kc))
    609         continue;
    610       for (int l = 0; l < 8; l++)
    611         if (xkb_keymap_key_get_syms_by_level(km, kc, 0, l, &syms) >= 1
    612             && !xkb_keysym_to_utf32(syms[0]))
    613           add_named(syms[0]);
    614     }
    615     goto done;
    616   }
    617   // xkb writes only the compatibility its keys use, so an option that takes
    618   // a key away has less of it: what matters is that it adds none
    619   if (!lines_within(
    620           strstr(mine, "xkb_types"),
    621           strstr(mine, "xkb_symbols"),
    622           strstr(base, "xkb_types"),
    623           strstr(base, "xkb_symbols")
    624       )) {
    625     fprintf(stderr, "kmap-vendor: option %s changes more than keys, left out\n", name);
    626     goto done;
    627   }
    628   for (xkb_keycode_t kc = xkb_keymap_min_keycode(km); kc <= xkb_keymap_max_keycode(km) && n < 1024;
    629        kc++) {
    630     const char *kn = xkb_keymap_key_get_name(km, kc);
    631 
    632     if (kn && differs(km, kc))
    633       n += collect(km, kc, kn, &k[n]);
    634   }
    635   if (!n)
    636     goto done;
    637   find_types(km, k, n);
    638   snprintf(group, sizeof(group), "%.*s", (int)(colon - name), name);
    639   snprintf(path, sizeof(path), "%s/options/%s", dir, group);
    640   if (mkdir(path, 0755) != 0 && errno != EEXIST)
    641     goto done;
    642   snprintf(path, sizeof(path), "%s/options/%s/%s.kmap", dir, group, colon + 1);
    643   if (!(fp = fopen(path, "w")))
    644     goto done;
    645   fprintf(fp, "kmap 1\nid %s\n", name);
    646   put_keys(fp, k, n);
    647   fclose(fp);
    648   rc = 1;
    649 done:
    650   free(mine);
    651   free(base);
    652   xkb_keymap_unref(km);
    653   return rc;
    654 }
    655 
    656 int
    657 main(int argc, char *argv[])
    658 {
    659   struct rxkb_context *rx;
    660   struct rxkb_layout  *lay;
    661   int                  n = 0, bad = 0;
    662 
    663   if (argc != 2) {
    664     fprintf(stderr, "usage: kmap-vendor dir\n");
    665     return 1;
    666   }
    667   if (mkdir(argv[1], 0755) != 0 && errno != EEXIST) {
    668     perror(argv[1]);
    669     return 1;
    670   }
    671   rx  = rxkb_context_new(RXKB_CONTEXT_NO_FLAGS);
    672   ctx = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
    673   {
    674     struct xkb_rule_names un = {"evdev", "pc105", "us", NULL, NULL};
    675 
    676     us = ctx ? xkb_keymap_new_from_names(ctx, &un, 0) : NULL;
    677   }
    678   if (!rx || !ctx || !rxkb_context_parse_default_ruleset(rx)) {
    679     fprintf(stderr, "kmap-vendor: no xkb data\n");
    680     return 1;
    681   }
    682   for (lay = rxkb_layout_first(rx); lay; lay = rxkb_layout_next(lay)) {
    683     if (write_layout(
    684             argv[1],
    685             rxkb_layout_get_name(lay),
    686             rxkb_layout_get_variant(lay),
    687             rxkb_layout_get_description(lay)
    688         )
    689         == 0)
    690       n++;
    691     else
    692       bad++;
    693   }
    694   fprintf(stderr, "kmap-vendor: %d layouts, %d left out\n", n, bad);
    695   {
    696     char path[1024], *full;
    697     int  nopt = 0;
    698 
    699     // the options' keysyms join the layouts' before the base is made,
    700     // then each option is checked against that base and written
    701     for (struct rxkb_option_group *g = rxkb_option_group_first(rx); g;
    702          g                           = rxkb_option_group_next(g))
    703       for (struct rxkb_option *o = rxkb_option_first(g); o; o = rxkb_option_next(o))
    704         write_option(argv[1], rxkb_option_get_name(o), NULL, 1);
    705     if (!(full = full_base()) || write_pc(argv[1], full) != 0) {
    706       fprintf(stderr, "kmap-vendor: could not write the pc keyboard\n");
    707       return 1;
    708     }
    709     snprintf(path, sizeof(path), "%s/options", argv[1]);
    710     mkdir(path, 0755);
    711     for (struct rxkb_option_group *g = rxkb_option_group_first(rx); g;
    712          g                           = rxkb_option_group_next(g))
    713       for (struct rxkb_option *o = rxkb_option_first(g); o; o = rxkb_option_next(o))
    714         nopt += write_option(argv[1], rxkb_option_get_name(o), full, 0);
    715     fprintf(stderr, "kmap-vendor: %d options that change keys\n", nopt);
    716     free(full);
    717   }
    718   return 0;
    719 }