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
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
30 #include <sys/types.h>
31 #include <sys/queue.h>
40 #include <stringlist.h>
46 static const char *lang_default = DEFAULT_LANG;
47 static const char *font;
48 static const char *lang;
49 static const char *program;
50 static const char *keymapdir = DEFAULT_KEYMAP_DIR;
51 static const char *fontdir = DEFAULT_FONT_DIR;
52 static const char *sysconfig = DEFAULT_SYSCONFIG;
53 static const char *font_default = DEFAULT_FONT;
54 static const char *font_current;
55 static const char *dir;
56 static const char *menu = "";
68 SLIST_ENTRY(keymap) entries;
70 static SLIST_HEAD(slisthead, keymap) head = SLIST_HEAD_INITIALIZER(head);
74 * Get keymap entry for 'key', or NULL of not found
76 static struct keymap *
77 get_keymap(const char *key)
81 SLIST_FOREACH(km, &head, entries)
82 if (!strcmp(km->keym, key))
89 * Count the number of keymaps we found
97 SLIST_FOREACH(km, &head, entries)
104 * Remove any keymap with given keym
107 remove_keymap(const char *keym)
111 SLIST_FOREACH(km, &head, entries) {
112 if (!strcmp(keym, km->keym)) {
113 SLIST_REMOVE(&head, km, keymap, entries);
121 * Add to hash with 'key'
124 add_keymap(const char *desc, int mark, const char *keym)
126 struct keymap *km, *km_new;
128 /* Is there already an entry with this key? */
129 SLIST_FOREACH(km, &head, entries) {
130 if (!strcmp(km->keym, keym)) {
131 /* Reuse this entry */
133 km->desc = strdup(desc);
139 km_new = (struct keymap *) malloc (sizeof(struct keymap));
140 km_new->desc = strdup(desc);
141 km_new->keym = strdup(keym);
144 /* Add to keymap list */
145 SLIST_INSERT_HEAD(&head, km_new, entries);
149 * Figure out the default language to use.
156 if ((locale = getenv("LC_ALL")) == NULL &&
157 (locale = getenv("LC_CTYPE")) == NULL &&
158 (locale = getenv("LANG")) == NULL)
159 locale = lang_default;
161 /* Check for alias */
162 if (!strcmp(locale, "C"))
163 locale = DEFAULT_LANG;
169 * Extract filename part
172 extract_name(const char *name)
176 p = strrchr(name, '/');
177 if (p != NULL && p[1] != '\0')
184 * Return file extension or NULL
187 get_extension(const char *name)
191 p = strrchr(name, '.');
193 if (p != NULL && p[1] != '\0')
200 * Read font from /etc/rc.conf else return default.
201 * Freeing the memory is the caller's responsibility.
206 char line[256], buf[20];
209 FILE *fp = fopen(sysconfig, "r");
211 while (fgets(line, sizeof(line), fp)) {
217 matches = sscanf(line,
218 " font%dx%d = \"%20[-.0-9a-zA-Z_]",
221 if (strcmp(buf, "NO")) {
224 fnt = (char *) malloc(strlen(buf) + 1);
231 fprintf(stderr, "Could not open %s for reading\n", sysconfig);
237 * Set a font using 'vidcontrol'
240 vidcontrol(const char *fnt)
246 /* syscons test failed */
252 /* Extract font size */
253 p = strrchr(tmp, '-');
254 if (p && p[1] != '\0') {
256 /* Remove any '.fnt' extension */
257 if ((q = strstr(p, ".fnt")))
261 * Check font size is valid, with no trailing characters
262 * ('&ch' should not be matched)
264 if (sscanf(p, "%dx%d%c", &i, &i, &ch) != 2)
265 fprintf(stderr, "Which font size? %s\n", fnt);
268 asprintf(&cmd, "vidcontrol -f %s %s", p, fnt);
270 fprintf(stderr, "%s\n", cmd);
275 fprintf(stderr, "Which font size? %s\n", fnt);
281 * Execute 'kbdcontrol' with the appropriate arguments
284 do_kbdcontrol(struct keymap *km)
287 asprintf(&kbd_cmd, "kbdcontrol -l %s/%s", dir, km->keym);
292 fprintf(stderr, "keymap=\"%s\"\n", km->keym);
297 * Call 'vidcontrol' with the appropriate arguments
300 do_vidfont(struct keymap *km)
302 char *vid_cmd, *tmp, *p, *q;
304 asprintf(&vid_cmd, "%s/%s", dir, km->keym);
308 tmp = strdup(km->keym);
309 p = strrchr(tmp, '-');
310 if (p && p[1]!='\0') {
312 q = get_extension(p);
315 printf("font%s=%s\n", p, km->keym);
322 * Display dialog from 'keymaps[]'
325 show_dialog(struct keymap **km_sorted, int num_keymaps)
329 char tmp_name[] = "/tmp/_kbd_lang.XXXX";
332 fd = mkstemp(tmp_name);
334 fprintf(stderr, "Could not open temporary file \"%s\"\n",
338 asprintf(&dialog, "/usr/bin/dialog --clear --title \"Keyboard Menu\" "
339 "--menu \"%s\" 0 0 0", menu);
341 /* start right font, assume that current font is equal
342 * to default font in /etc/rc.conf
344 * $font is the font which require the language $lang; e.g.
345 * russian *need* a koi8 font
346 * $font_current is the current font from /etc/rc.conf
348 if (font && strcmp(font, font_current))
351 /* Build up the command */
353 for (i=0; i<num_keymaps; i++) {
355 * Each 'font' is passed as ' "font" ""', so allow the
358 size += strlen(km_sorted[i]->desc) + 6;
361 /* Allow the space for '2> tmpfilename' redirection */
362 size += strlen(tmp_name) + 3;
364 cmd = (char *) malloc(strlen(dialog) + size + 1);
367 for (i=0; i<num_keymaps; i++) {
369 strcat(cmd, km_sorted[i]->desc);
371 strcat(cmd, " \"\"");
375 strcat(cmd, tmp_name);
377 /* Show the dialog.. */
380 fp = fopen(tmp_name, "r");
383 if (fgets(choice, sizeof(choice), fp) != NULL) {
384 /* Find key for desc */
385 for (i=0; i<num_keymaps; i++) {
386 if (!strcmp(choice, km_sorted[i]->desc)) {
387 if (!strcmp(program, "kbdmap"))
388 do_kbdcontrol(km_sorted[i]);
390 do_vidfont(km_sorted[i]);
395 if (font != NULL && strcmp(font, font_current))
396 /* Cancelled, restore old font */
397 vidcontrol(font_current);
401 fprintf(stderr, "Failed to open temporary file");
411 * Search for 'token' in comma delimited array 'buffer'.
412 * Return true for found, false for not found.
415 find_token(const char *buffer, const char *token)
417 char *buffer_tmp, *buffer_copy, *inputstring;
421 buffer_copy = strdup(buffer);
422 buffer_tmp = buffer_copy;
423 inputstring = buffer_copy;
428 while ((*ap = strsep(&inputstring, ",")) != NULL) {
429 if (strcmp(buffer_tmp, token) == 0) {
441 * Compare function for qsort
444 compare_keymap(const void *a, const void *b)
447 /* We've been passed pointers to pointers, so: */
448 const struct keymap *km1 = *((const struct keymap * const *) a);
449 const struct keymap *km2 = *((const struct keymap * const *) b);
451 return strcmp(km1->desc, km2->desc);
455 * Compare function for qsort
458 compare_lang(const void *a, const void *b)
460 const char *l1 = *((const char * const *) a);
461 const char *l2 = *((const char * const *) b);
463 return strcmp(l1, l2);
467 * Change '8x8' to '8x08' so qsort will put it before eg. '8x14'
470 kludge_desc(struct keymap **km_sorted, int num_keymaps)
474 for (i=0; i<num_keymaps; i++) {
476 char *km = km_sorted[i]->desc;
477 if ((p = strstr(km, "8x8")) != NULL) {
484 /* Make enough space for the extra '0' */
486 km = realloc(km, len + 2);
488 for (j=len; j!=offset+1; j--)
493 km_sorted[i]->desc = km;
499 * Reverse 'kludge_desc()' - change '8x08' back to '8x8'
502 unkludge_desc(struct keymap **km_sorted, int num_keymaps)
506 for (i=0; i<num_keymaps; i++) {
508 char *km = km_sorted[i]->desc;
509 if ((p = strstr(km, "8x08")) != NULL) {
514 km = realloc(km, p - km - 1);
515 km_sorted[i]->desc = km;
521 * Return 0 if file exists and is readable, else -1
524 check_file(const char *keym)
528 if (access(keym, R_OK) == -1) {
530 asprintf(&fn, "%s/%s", dir, keym);
531 if (access(fn, R_OK) == -1) {
533 fprintf(stderr, "%s not found!\n", fn);
539 fprintf(stderr, "No read permission for %s!\n", keym);
547 * Read options from the relevent configuration file, then
555 int mark, num_keymaps, items, i;
556 char buffer[256], filename[PATH_MAX];
557 char keym[64], lng[64], desc[64];
558 char dialect[64], lang_abk[64];
560 struct keymap **km_sorted;
562 StringList *lang_list;
566 lang_list = sl_init();
568 sprintf(filename, "%s/INDEX.%s", dir, extract_name(dir));
570 /* en_US.ISO8859-1 -> en_..\.ISO8859-1 */
571 strlcpy(dialect, lang, sizeof(dialect));
572 if (strlen(dialect) >= 6 && dialect[2] == '_') {
578 /* en_US.ISO8859-1 -> en */
579 strlcpy(lang_abk, lang, sizeof(lang_abk));
580 if (strlen(lang_abk) >= 3 && lang_abk[2] == '_')
583 fprintf(stderr, "lang_default = %s\n", lang_default);
584 fprintf(stderr, "dialect = %s\n", dialect);
585 fprintf(stderr, "lang_abk = %s\n", lang_abk);
587 fp = fopen(filename, "r");
590 while (fgets(buffer, sizeof(buffer), fp)) {
601 /* Parse input, removing newline */
602 matches = sscanf(p, "%64[^:]:%64[^:]:%64[^:\n]",
605 if (strcmp(keym, "FONT")
606 && strcmp(keym, "MENU")) {
607 /* Check file exists & is readable */
608 if (check_file(keym) == -1)
615 * Take note of supported languages, which
616 * might be in a comma-delimited list
618 char *tmp = strdup(lng);
621 for (delim = tmp; ; ) {
623 if (ch == ',' || ch == '\0') {
625 if (!sl_find(lang_list, tmp))
626 sl_add(lang_list, tmp);
633 /* Set empty language to default language */
640 /* 4) Your choice if it exists
641 * 3) Long match eg. en_GB.ISO8859-1 is equal to
643 * 2) short match 'de'
644 * 1) default langlist 'en'
647 * Language may be a comma separated list
648 * A higher match overwrites a lower
649 * A later entry overwrites a previous if it exists
650 * twice in the database
653 /* Check for favoured language */
654 km = get_keymap(keym);
655 mark = (km) ? km->mark : 0;
657 if (find_token(lg, lang))
658 add_keymap(desc, 4, keym);
659 else if (mark <= 3 && find_token(lg, dialect))
660 add_keymap(desc, 3, keym);
661 else if (mark <= 2 && find_token(lg, lang_abk))
662 add_keymap(desc, 2, keym);
663 else if (mark <= 1 && find_token(lg, lang_default))
664 add_keymap(desc, 1, keym);
666 add_keymap(desc, 0, keym);
671 printf("Could not open file\n");
674 qsort(lang_list->sl_str, lang_list->sl_cur, sizeof(char*),
676 printf("Currently supported languages: ");
677 for (i=0; i< (int) lang_list->sl_cur; i++)
678 printf("%s ", lang_list->sl_str[i]);
683 km = get_keymap("MENU");
685 /* Take note of menu title */
686 menu = strdup(km->desc);
687 km = get_keymap("FONT");
689 /* Take note of language font */
690 font = strdup(km->desc);
692 /* Remove unwanted items from list */
693 remove_keymap("MENU");
694 remove_keymap("FONT");
696 /* Look for keymaps not in database */
699 while ((dp = readdir(dirp)) != NULL) {
700 const char *ext = get_extension(dp->d_name);
702 if ((!strcmp(ext, ".fnt") ||
703 !strcmp(ext, ".kbd")) &&
704 !get_keymap(dp->d_name)) {
707 /* Remove any .fnt or .kbd extension */
708 q = strdup(dp->d_name);
709 *(get_extension(q)) = '\0';
710 add_keymap(q, 0, dp->d_name);
715 "'%s' not in database\n",
722 fprintf(stderr, "Could not open directory '%s'\n", dir);
724 /* Sort items in keymap */
725 num_keymaps = get_num_keymaps();
727 km_sorted = (struct keymap **)
728 malloc(num_keymaps*sizeof(struct keymap *));
730 /* Make array of pointers to items in hash */
732 SLIST_FOREACH(km, &head, entries)
733 km_sorted[items++] = km;
735 /* Change '8x8' to '8x08' so sort works as we might expect... */
736 kludge_desc(km_sorted, num_keymaps);
738 qsort(km_sorted, num_keymaps, sizeof(struct keymap *), compare_keymap);
740 /* ...change back again */
741 unkludge_desc(km_sorted, num_keymaps);
744 for (i=0; i<num_keymaps; i++)
745 printf("%s\n", km_sorted[i]->desc);
749 show_dialog(km_sorted, num_keymaps);
755 * Display usage information and exit
761 fprintf(stderr, "usage: %s\t[-K] [-V] [-d|-default] [-h|-help] "
762 "[-l|-lang language]\n\t\t[-p|-print] [-r|-restore] [-s|-show] "
763 "[-v|-verbose]\n", program);
768 parse_args(int argc, char **argv)
772 for (i=1; i<argc; i++) {
773 if (argv[i][0] != '-')
775 else if (!strcmp(argv[i], "-help") || !strcmp(argv[i], "-h"))
777 else if (!strcmp(argv[i], "-verbose") || !strcmp(argv[i], "-v"))
779 else if (!strcmp(argv[i], "-lang") || !strcmp(argv[i], "-l"))
784 else if (!strcmp(argv[i], "-default") || !strcmp(argv[i], "-d"))
786 else if (!strcmp(argv[i], "-show") || !strcmp(argv[i], "-s"))
788 else if (!strcmp(argv[i], "-print") || !strcmp(argv[i], "-p"))
790 else if (!strcmp(argv[i], "-restore") ||
791 !strcmp(argv[i], "-r")) {
792 vidcontrol(font_current);
794 } else if (!strcmp(argv[i], "-K"))
796 else if (!strcmp(argv[i], "-V"))
804 * A front-end for the 'vidfont' and 'kbdmap' programs.
807 main(int argc, char **argv)
810 x11 = system("kbdcontrol -d >/dev/null");
813 fprintf(stderr, "You are not on a virtual console - "
814 "expect certain strange side-effects\n");
822 program = extract_name(argv[0]);
824 font_current = get_font();
825 if (font_current == NULL)
826 font_current = font_default;
828 if (strcmp(program, "kbdmap"))
833 /* Parse command line arguments */
834 parse_args(argc, argv);
836 /* Read and display options */