2 * Copyright (c) 2002 Jonathan Belson <jon@witchspace.com>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * $FreeBSD: src/usr.sbin/kbdmap/kbdmap.c,v 1.2 2002/10/27 17:44:33 wollman Exp $
29 #include <sys/types.h>
30 #include <sys/queue.h>
39 #include <stringlist.h>
45 static const char *lang_default = DEFAULT_LANG;
46 static const char *font;
47 static const char *lang;
48 static const char *program;
49 static const char *keymapdir = DEFAULT_KEYMAP_DIR;
50 static const char *fontdir = DEFAULT_FONT_DIR;
51 static const char *sysconfig = DEFAULT_SYSCONFIG;
52 static const char *font_default = DEFAULT_FONT;
53 static const char *font_current;
54 static const char *dir;
55 static const char *menu = "";
67 SLIST_ENTRY(keymap) entries;
69 static SLIST_HEAD(slisthead, keymap) head = SLIST_HEAD_INITIALIZER(head);
73 * Get keymap entry for 'key', or NULL of not found
75 static struct keymap *
76 get_keymap(const char *key)
80 SLIST_FOREACH(km, &head, entries)
81 if (!strcmp(km->keym, key))
88 * Count the number of keymaps we found
96 SLIST_FOREACH(km, &head, entries)
103 * Remove any keymap with given keym
106 remove_keymap(const char *keym)
110 SLIST_FOREACH(km, &head, entries) {
111 if (!strcmp(keym, km->keym)) {
112 SLIST_REMOVE(&head, km, keymap, entries);
120 * Add to hash with 'key'
123 add_keymap(const char *desc, int mark, const char *keym)
125 struct keymap *km, *km_new;
127 /* Is there already an entry with this key? */
128 SLIST_FOREACH(km, &head, entries) {
129 if (!strcmp(km->keym, keym)) {
130 /* Reuse this entry */
132 km->desc = strdup(desc);
138 km_new = (struct keymap *) malloc (sizeof(struct keymap));
139 km_new->desc = strdup(desc);
140 km_new->keym = strdup(keym);
143 /* Add to keymap list */
144 SLIST_INSERT_HEAD(&head, km_new, entries);
148 * Figure out the default language to use.
155 if ((locale = getenv("LC_ALL")) == NULL &&
156 (locale = getenv("LC_CTYPE")) == NULL &&
157 (locale = getenv("LANG")) == NULL)
158 locale = lang_default;
160 /* Check for alias */
161 if (!strcmp(locale, "C"))
162 locale = DEFAULT_LANG;
168 * Extract filename part
171 extract_name(const char *name)
175 p = strrchr(name, '/');
176 if (p != NULL && p[1] != '\0')
183 * Return file extension or NULL
186 get_extension(const char *name)
190 p = strrchr(name, '.');
192 if (p != NULL && p[1] != '\0')
199 * Read font from /etc/rc.conf else return default.
200 * Freeing the memory is the caller's responsibility.
205 char line[256], buf[20];
208 FILE *fp = fopen(sysconfig, "r");
210 while (fgets(line, sizeof(line), fp)) {
216 matches = sscanf(line,
217 " font%dx%d = \"%20[-.0-9a-zA-Z_]",
220 if (strcmp(buf, "NO")) {
223 fnt = (char *) malloc(strlen(buf) + 1);
229 fprintf(stderr, "Could not open %s for reading\n", sysconfig);
235 * Set a font using 'vidcontrol'
238 vidcontrol(const char *fnt)
244 /* syscons test failed */
250 /* Extract font size */
251 p = strrchr(tmp, '-');
252 if (p && p[1] != '\0') {
254 /* Remove any '.fnt' extension */
255 if ((q = strstr(p, ".fnt")))
259 * Check font size is valid, with no trailing characters
260 * ('&ch' should not be matched)
262 if (sscanf(p, "%dx%d%c", &i, &i, &ch) != 2)
263 fprintf(stderr, "Which font size? %s\n", fnt);
266 asprintf(&cmd, "vidcontrol -f %s %s", p, fnt);
268 fprintf(stderr, "%s\n", cmd);
273 fprintf(stderr, "Which font size? %s\n", fnt);
279 * Execute 'kbdcontrol' with the appropriate arguments
282 do_kbdcontrol(struct keymap *km)
285 asprintf(&kbd_cmd, "kbdcontrol -l %s/%s", dir, km->keym);
290 printf("keymap=%s\n", km->keym);
295 * Call 'vidcontrol' with the appropriate arguments
298 do_vidfont(struct keymap *km)
300 char *vid_cmd, *tmp, *p, *q;
302 asprintf(&vid_cmd, "%s/%s", dir, km->keym);
306 tmp = strdup(km->keym);
307 p = strrchr(tmp, '-');
308 if (p && p[1]!='\0') {
310 q = get_extension(p);
313 printf("font%s=%s\n", p, km->keym);
320 * Display dialog from 'keymaps[]'
323 show_dialog(struct keymap **km_sorted, int num_keymaps)
327 char tmp_name[] = "/tmp/_kbd_lang.XXXX";
330 fd = mkstemp(tmp_name);
332 fprintf(stderr, "Could not open temporary file \"%s\"\n",
336 asprintf(&dialog, "/usr/bin/dialog --clear --title \"Keyboard Menu\" "
337 "--menu \"%s\" -1 -1 10", menu);
339 /* start right font, assume that current font is equal
340 * to default font in /etc/rc.conf
342 * $font is the font which require the language $lang; e.g.
343 * russian *need* a koi8 font
344 * $font_current is the current font from /etc/rc.conf
346 if (font && strcmp(font, font_current))
349 /* Build up the command */
351 for (i=0; i<num_keymaps; i++) {
353 * Each 'font' is passed as ' "font" ""', so allow the
356 size += strlen(km_sorted[i]->desc) + 6;
359 /* Allow the space for '2> tmpfilename' redirection */
360 size += strlen(tmp_name) + 3;
362 cmd = (char *) malloc(strlen(dialog) + size + 1);
365 for (i=0; i<num_keymaps; i++) {
367 strcat(cmd, km_sorted[i]->desc);
369 strcat(cmd, " \"\"");
373 strcat(cmd, tmp_name);
375 /* Show the dialog.. */
378 fp = fopen(tmp_name, "r");
381 if (fgets(choice, 64, fp) != NULL) {
382 /* Find key for desc */
383 for (i=0; i<num_keymaps; i++) {
384 if (!strcmp(choice, km_sorted[i]->desc)) {
385 if (!strcmp(program, "kbdmap"))
386 do_kbdcontrol(km_sorted[i]);
388 do_vidfont(km_sorted[i]);
393 if (font != NULL && strcmp(font, font_current))
394 /* Cancelled, restore old font */
395 vidcontrol(font_current);
399 fprintf(stderr, "Failed to open temporary file");
409 * Search for 'token' in comma delimited array 'buffer'.
410 * Return true for found, false for not found.
413 find_token(const char *buffer, const char *token)
415 char *buffer_tmp, *buffer_copy, *inputstring;
419 buffer_copy = strdup(buffer);
420 buffer_tmp = buffer_copy;
421 inputstring = buffer_copy;
426 while ((*ap = strsep(&inputstring, ",")) != NULL) {
427 if (strcmp(buffer_tmp, token) == 0) {
439 * Compare function for qsort
442 compare_keymap(const void *a, const void *b)
445 /* We've been passed pointers to pointers, so: */
446 const struct keymap *km1 = *((const struct keymap * const *) a);
447 const struct keymap *km2 = *((const struct keymap * const *) b);
449 return strcmp(km1->desc, km2->desc);
453 * Compare function for qsort
456 compare_lang(const void *a, const void *b)
458 const char *l1 = *((const char * const *) a);
459 const char *l2 = *((const char * const *) b);
461 return strcmp(l1, l2);
465 * Change '8x8' to '8x08' so qsort will put it before eg. '8x14'
468 kludge_desc(struct keymap **km_sorted, int num_keymaps)
472 for (i=0; i<num_keymaps; i++) {
474 char *km = km_sorted[i]->desc;
475 if ((p = strstr(km, "8x8")) != NULL) {
482 /* Make enough space for the extra '0' */
484 km = realloc(km, len + 2);
486 for (j=len; j!=offset+1; j--)
491 km_sorted[i]->desc = km;
497 * Reverse 'kludge_desc()' - change '8x08' back to '8x8'
500 unkludge_desc(struct keymap **km_sorted, int num_keymaps)
504 for (i=0; i<num_keymaps; i++) {
506 char *km = km_sorted[i]->desc;
507 if ((p = strstr(km, "8x08")) != NULL) {
512 km = realloc(km, p - km - 1);
513 km_sorted[i]->desc = km;
519 * Return 0 if file exists and is readable, else -1
522 check_file(const char *keym)
526 if (access(keym, R_OK) == -1) {
528 asprintf(&fn, "%s/%s", dir, keym);
529 if (access(fn, R_OK) == -1) {
531 fprintf(stderr, "%s not found!\n", fn);
537 fprintf(stderr, "No read permission for %s!\n", keym);
545 * Read options from the relevent configuration file, then
553 int mark, num_keymaps, items, i;
554 char buffer[256], filename[PATH_MAX];
555 char keym[64], lng[64], desc[64];
556 char dialect[64], lang_abk[64];
558 struct keymap **km_sorted;
560 StringList *lang_list;
564 lang_list = sl_init();
566 sprintf(filename, "%s/INDEX.%s", dir, extract_name(dir));
568 /* en_US.ISO8859-1 -> en_..\.ISO8859-1 */
569 strlcpy(dialect, lang, sizeof(dialect));
570 if (strlen(dialect) >= 6 && dialect[2] == '-') {
576 /* en_US.ISO8859-1 -> en */
577 strlcpy(lang_abk, lang, sizeof(lang_abk));
578 if (strlen(lang_abk) >= 3 && lang_abk[2] == '-')
581 fprintf(stderr, "lang_default = %s\n", lang_default);
582 fprintf(stderr, "dialect = %s\n", dialect);
583 fprintf(stderr, "lang_abk = %s\n", lang_abk);
585 fp = fopen(filename, "r");
588 while (fgets(buffer, sizeof(buffer), fp)) {
599 /* Parse input, removing newline */
600 matches = sscanf(p, "%64[^:]:%64[^:]:%64[^:\n]",
603 if (strcmp(keym, "FONT")
604 && strcmp(keym, "MENU")) {
605 /* Check file exists & is readable */
606 if (check_file(keym) == -1)
613 * Take note of supported languages, which
614 * might be in a comma-delimited list
616 char *tmp = strdup(lng);
619 for (delim = tmp; ; ) {
621 if (ch == ',' || ch == '\0') {
623 if (!sl_find(lang_list, tmp))
624 sl_add(lang_list, tmp);
631 /* Set empty language to default language */
638 /* 4) Your choice if it exists
639 * 3) Long match eg. en_GB.ISO8859-1 is equal to
641 * 2) short match 'de'
642 * 1) default langlist 'en'
645 * Language may be a comma separated list
646 * A higher match overwrites a lower
647 * A later entry overwrites a previous if it exists
648 * twice in the database
651 /* Check for favoured language */
652 km = get_keymap(keym);
653 mark = (km) ? km->mark : 0;
655 if (find_token(lg, lang))
656 add_keymap(desc, 4, keym);
657 else if (mark <= 3 && find_token(lg, dialect))
658 add_keymap(desc, 3, keym);
659 else if (mark <= 2 && find_token(lg, lang_abk))
660 add_keymap(desc, 2, keym);
661 else if (mark <= 1 && find_token(lg, lang_default))
662 add_keymap(desc, 1, keym);
664 add_keymap(desc, 0, keym);
669 printf("Could not open file\n");
672 qsort(lang_list->sl_str, lang_list->sl_cur, sizeof(char*),
674 printf("Currently supported languages: ");
675 for (i=0; i< (int) lang_list->sl_cur; i++)
676 printf("%s ", lang_list->sl_str[i]);
681 km = get_keymap("MENU");
683 /* Take note of menu title */
684 menu = strdup(km->desc);
685 km = get_keymap("FONT");
687 /* Take note of language font */
688 font = strdup(km->desc);
690 /* Remove unwanted items from list */
691 remove_keymap("MENU");
692 remove_keymap("FONT");
694 /* Look for keymaps not in database */
697 while ((dp = readdir(dirp)) != NULL) {
698 const char *ext = get_extension(dp->d_name);
700 if ((!strcmp(ext, ".fnt") ||
701 !strcmp(ext, ".kbd")) &&
702 !get_keymap(dp->d_name)) {
705 /* Remove any .fnt or .kbd extension */
706 q = strdup(dp->d_name);
707 *(get_extension(q)) = '\0';
708 add_keymap(q, 0, dp->d_name);
713 "'%s' not in database\n",
720 fprintf(stderr, "Could not open directory '%s'\n", dir);
722 /* Sort items in keymap */
723 num_keymaps = get_num_keymaps();
725 km_sorted = (struct keymap **)
726 malloc(num_keymaps*sizeof(struct keymap *));
728 /* Make array of pointers to items in hash */
730 SLIST_FOREACH(km, &head, entries)
731 km_sorted[items++] = km;
733 /* Change '8x8' to '8x08' so sort works as we might expect... */
734 kludge_desc(km_sorted, num_keymaps);
736 qsort(km_sorted, num_keymaps, sizeof(struct keymap *), compare_keymap);
738 /* ...change back again */
739 unkludge_desc(km_sorted, num_keymaps);
742 for (i=0; i<num_keymaps; i++)
743 printf("%s\n", km_sorted[i]->desc);
747 show_dialog(km_sorted, num_keymaps);
753 * Display usage information and exit
759 fprintf(stderr, "usage: %s\t[-K] [-V] [-d|-default] [-h|-help] "
760 "[-l|-lang language]\n\t\t[-p|-print] [-r|-restore] [-s|-show] "
761 "[-v|-verbose]\n", program);
766 parse_args(int argc, char **argv)
770 for (i=1; i<argc; i++) {
771 if (argv[i][0] != '-')
773 else if (!strcmp(argv[i], "-help") || !strcmp(argv[i], "-h"))
775 else if (!strcmp(argv[i], "-verbose") || !strcmp(argv[i], "-v"))
777 else if (!strcmp(argv[i], "-lang") || !strcmp(argv[i], "-l"))
782 else if (!strcmp(argv[i], "-default") || !strcmp(argv[i], "-d"))
784 else if (!strcmp(argv[i], "-show") || !strcmp(argv[i], "-s"))
786 else if (!strcmp(argv[i], "-print") || !strcmp(argv[i], "-p"))
788 else if (!strcmp(argv[i], "-restore") ||
789 !strcmp(argv[i], "-r")) {
790 vidcontrol(font_current);
792 } else if (!strcmp(argv[i], "-K"))
794 else if (!strcmp(argv[i], "-V"))
802 * A front-end for the 'vidfont' and 'kbdmap' programs.
805 main(int argc, char **argv)
808 x11 = system("kbdcontrol -d >/dev/null");
811 fprintf(stderr, "You are not on a virtual console - "
812 "expect certain strange side-effects\n");
820 program = extract_name(argv[0]);
822 font_current = get_font();
823 if (font_current == NULL)
824 font_current = font_default;
826 if (strcmp(program, "kbdmap"))
831 /* Parse command line arguments */
832 parse_args(argc, argv);
834 /* Read and display options */