2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2002 Jonathan Belson <jon@witchspace.com>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
32 #include <sys/types.h>
33 #include <sys/queue.h>
34 #include <sys/sysctl.h>
43 #include <stringlist.h>
49 static const char *lang_default = DEFAULT_LANG;
50 static const char *font;
51 static const char *lang;
52 static const char *program;
53 static const char *keymapdir = DEFAULT_VT_KEYMAP_DIR;
54 static const char *fontdir = DEFAULT_VT_FONT_DIR;
55 static const char *font_default = DEFAULT_VT_FONT;
56 static const char *sysconfig = DEFAULT_SYSCONFIG;
57 static const char *font_current;
58 static const char *dir;
59 static const char *menu = "";
72 SLIST_ENTRY(keymap) entries;
74 static SLIST_HEAD(slisthead, keymap) head = SLIST_HEAD_INITIALIZER(head);
78 * Get keymap entry for 'key', or NULL of not found
80 static struct keymap *
81 get_keymap(const char *key)
85 SLIST_FOREACH(km, &head, entries)
86 if (!strcmp(km->keym, key))
93 * Count the number of keymaps we found
101 SLIST_FOREACH(km, &head, entries)
108 * Remove any keymap with given keym
111 remove_keymap(const char *keym)
115 SLIST_FOREACH(km, &head, entries) {
116 if (!strcmp(keym, km->keym)) {
117 SLIST_REMOVE(&head, km, keymap, entries);
125 * Add to hash with 'key'
128 add_keymap(const char *desc, int mark, const char *keym)
130 struct keymap *km, *km_new;
132 /* Is there already an entry with this key? */
133 SLIST_FOREACH(km, &head, entries) {
134 if (!strcmp(km->keym, keym)) {
135 /* Reuse this entry */
137 km->desc = strdup(desc);
143 km_new = (struct keymap *) malloc (sizeof(struct keymap));
144 km_new->desc = strdup(desc);
145 km_new->keym = strdup(keym);
148 /* Add to keymap list */
149 SLIST_INSERT_HEAD(&head, km_new, entries);
153 * Return 0 if syscons is in use (to select legacy defaults).
162 if (sysctlbyname("kern.vty", &term, &len, NULL, 0) != 0 ||
163 strcmp(term, "vt") != 0)
169 * Figure out the default language to use.
176 if ((locale = getenv("LC_ALL")) == NULL &&
177 (locale = getenv("LC_CTYPE")) == NULL &&
178 (locale = getenv("LANG")) == NULL)
179 locale = lang_default;
181 /* Check for alias */
182 if (!strcmp(locale, "C"))
183 locale = DEFAULT_LANG;
189 * Extract filename part
192 extract_name(const char *name)
196 p = strrchr(name, '/');
197 if (p != NULL && p[1] != '\0')
204 * Return file extension or NULL
207 get_extension(const char *name)
211 p = strrchr(name, '.');
213 if (p != NULL && p[1] != '\0')
220 * Read font from /etc/rc.conf else return default.
221 * Freeing the memory is the caller's responsibility.
226 char line[256], buf[20];
229 FILE *fp = fopen(sysconfig, "r");
231 while (fgets(line, sizeof(line), fp)) {
237 matches = sscanf(line,
238 " font%dx%d = \"%20[-.0-9a-zA-Z_]",
241 if (strcmp(buf, "NO")) {
250 fprintf(stderr, "Could not open %s for reading\n", sysconfig);
256 * Set a font using 'vidcontrol'
259 vidcontrol(const char *fnt)
261 char *tmp, *p, *q, *cmd;
265 /* syscons test failed */
270 asprintf(&cmd, "vidcontrol -f %s", fnt);
278 /* Extract font size */
279 p = strrchr(tmp, '-');
280 if (p && p[1] != '\0') {
282 /* Remove any '.fnt' extension */
283 if ((q = strstr(p, ".fnt")))
287 * Check font size is valid, with no trailing characters
288 * ('&ch' should not be matched)
290 if (sscanf(p, "%dx%d%c", &i, &i, &ch) != 2)
291 fprintf(stderr, "Which font size? %s\n", fnt);
293 asprintf(&cmd, "vidcontrol -f %s %s", p, fnt);
295 fprintf(stderr, "%s\n", cmd);
300 fprintf(stderr, "Which font size? %s\n", fnt);
306 * Execute 'kbdcontrol' with the appropriate arguments
309 do_kbdcontrol(struct keymap *km)
312 asprintf(&kbd_cmd, "kbdcontrol -l %s/%s", dir, km->keym);
317 fprintf(stderr, "keymap=\"%s\"\n", km->keym);
322 * Call 'vidcontrol' with the appropriate arguments
325 do_vidfont(struct keymap *km)
327 char *vid_cmd, *tmp, *p, *q;
329 asprintf(&vid_cmd, "%s/%s", dir, km->keym);
333 tmp = strdup(km->keym);
334 p = strrchr(tmp, '-');
335 if (p && p[1]!='\0') {
337 q = get_extension(p);
340 printf("font%s=%s\n", p, km->keym);
347 * Display dialog from 'keymaps[]'
350 show_dialog(struct keymap **km_sorted, int num_keymaps)
354 char tmp_name[] = "/tmp/_kbd_lang.XXXX";
357 fd = mkstemp(tmp_name);
359 fprintf(stderr, "Could not open temporary file \"%s\"\n",
363 asprintf(&dialog, "/usr/bin/dialog --clear --title \"Keyboard Menu\" "
364 "--menu \"%s\" 0 0 0", menu);
366 /* start right font, assume that current font is equal
367 * to default font in /etc/rc.conf
369 * $font is the font which require the language $lang; e.g.
370 * russian *need* a koi8 font
371 * $font_current is the current font from /etc/rc.conf
373 if (font && strcmp(font, font_current))
376 /* Build up the command */
378 for (i=0; i<num_keymaps; i++) {
380 * Each 'font' is passed as ' "font" ""', so allow the
383 size += strlen(km_sorted[i]->desc) + 6;
386 /* Allow the space for '2> tmpfilename' redirection */
387 size += strlen(tmp_name) + 3;
389 cmd = (char *) malloc(strlen(dialog) + size + 1);
392 for (i=0; i<num_keymaps; i++) {
394 strcat(cmd, km_sorted[i]->desc);
396 strcat(cmd, " \"\"");
400 strcat(cmd, tmp_name);
402 /* Show the dialog.. */
405 fp = fopen(tmp_name, "r");
408 if (fgets(choice, sizeof(choice), fp) != NULL) {
409 /* Find key for desc */
410 for (i=0; i<num_keymaps; i++) {
411 if (!strcmp(choice, km_sorted[i]->desc)) {
412 if (!strcmp(program, "kbdmap"))
413 do_kbdcontrol(km_sorted[i]);
415 do_vidfont(km_sorted[i]);
420 if (font != NULL && strcmp(font, font_current))
421 /* Cancelled, restore old font */
422 vidcontrol(font_current);
426 fprintf(stderr, "Failed to open temporary file");
436 * Search for 'token' in comma delimited array 'buffer'.
437 * Return true for found, false for not found.
440 find_token(const char *buffer, const char *token)
442 char *buffer_tmp, *buffer_copy, *inputstring;
446 buffer_copy = strdup(buffer);
447 buffer_tmp = buffer_copy;
448 inputstring = buffer_copy;
453 while ((*ap = strsep(&inputstring, ",")) != NULL) {
454 if (strcmp(buffer_tmp, token) == 0) {
466 * Compare function for qsort
469 compare_keymap(const void *a, const void *b)
472 /* We've been passed pointers to pointers, so: */
473 const struct keymap *km1 = *((const struct keymap * const *) a);
474 const struct keymap *km2 = *((const struct keymap * const *) b);
476 return strcmp(km1->desc, km2->desc);
480 * Compare function for qsort
483 compare_lang(const void *a, const void *b)
485 const char *l1 = *((const char * const *) a);
486 const char *l2 = *((const char * const *) b);
488 return strcmp(l1, l2);
492 * Change '8x8' to '8x08' so qsort will put it before eg. '8x14'
495 kludge_desc(struct keymap **km_sorted, int num_keymaps)
499 for (i=0; i<num_keymaps; i++) {
501 char *km = km_sorted[i]->desc;
502 if ((p = strstr(km, "8x8")) != NULL) {
509 /* Make enough space for the extra '0' */
511 km = realloc(km, len + 2);
513 for (j=len; j!=offset+1; j--)
518 km_sorted[i]->desc = km;
524 * Reverse 'kludge_desc()' - change '8x08' back to '8x8'
527 unkludge_desc(struct keymap **km_sorted, int num_keymaps)
531 for (i=0; i<num_keymaps; i++) {
533 char *km = km_sorted[i]->desc;
534 if ((p = strstr(km, "8x08")) != NULL) {
539 km = realloc(km, p - km - 1);
540 km_sorted[i]->desc = km;
546 * Return 0 if file exists and is readable, else -1
549 check_file(const char *keym)
553 if (access(keym, R_OK) == -1) {
555 asprintf(&fn, "%s/%s", dir, keym);
556 if (access(fn, R_OK) == -1) {
558 fprintf(stderr, "%s not found!\n", fn);
564 fprintf(stderr, "No read permission for %s!\n", keym);
572 * Read options from the relevant configuration file, then
580 int mark, num_keymaps, items, i;
581 char buffer[256], filename[PATH_MAX];
582 char keym[64], lng[64], desc[256];
583 char dialect[64], lang_abk[64];
585 struct keymap **km_sorted;
587 StringList *lang_list;
591 lang_list = sl_init();
593 sprintf(filename, "%s/INDEX.%s", dir, extract_name(dir));
595 /* en_US.ISO8859-1 -> en_..\.ISO8859-1 */
596 strlcpy(dialect, lang, sizeof(dialect));
597 if (strlen(dialect) >= 6 && dialect[2] == '_') {
603 /* en_US.ISO8859-1 -> en */
604 strlcpy(lang_abk, lang, sizeof(lang_abk));
605 if (strlen(lang_abk) >= 3 && lang_abk[2] == '_')
608 fprintf(stderr, "lang_default = %s\n", lang_default);
609 fprintf(stderr, "dialect = %s\n", dialect);
610 fprintf(stderr, "lang_abk = %s\n", lang_abk);
612 fp = fopen(filename, "r");
615 while (fgets(buffer, sizeof(buffer), fp)) {
626 /* Parse input, removing newline */
627 matches = sscanf(p, "%64[^:]:%64[^:]:%256[^:\n]",
630 if (strcmp(keym, "FONT")
631 && strcmp(keym, "MENU")) {
632 /* Check file exists & is readable */
633 if (check_file(keym) == -1)
640 * Take note of supported languages, which
641 * might be in a comma-delimited list
643 char *tmp = strdup(lng);
646 for (delim = tmp; ; ) {
648 if (ch == ',' || ch == '\0') {
650 if (!sl_find(lang_list, tmp))
651 sl_add(lang_list, tmp);
658 /* Set empty language to default language */
665 /* 4) Your choice if it exists
666 * 3) Long match eg. en_GB.ISO8859-1 is equal to
668 * 2) short match 'de'
669 * 1) default langlist 'en'
672 * Language may be a comma separated list
673 * A higher match overwrites a lower
674 * A later entry overwrites a previous if it exists
675 * twice in the database
678 /* Check for favoured language */
679 km = get_keymap(keym);
680 mark = (km) ? km->mark : 0;
682 if (find_token(lg, lang))
683 add_keymap(desc, 4, keym);
684 else if (mark <= 3 && find_token(lg, dialect))
685 add_keymap(desc, 3, keym);
686 else if (mark <= 2 && find_token(lg, lang_abk))
687 add_keymap(desc, 2, keym);
688 else if (mark <= 1 && find_token(lg, lang_default))
689 add_keymap(desc, 1, keym);
691 add_keymap(desc, 0, keym);
696 fprintf(stderr, "Could not open %s for reading\n", filename);
699 qsort(lang_list->sl_str, lang_list->sl_cur, sizeof(char*),
701 printf("Currently supported languages: ");
702 for (i=0; i< (int) lang_list->sl_cur; i++)
703 printf("%s ", lang_list->sl_str[i]);
708 km = get_keymap("MENU");
710 /* Take note of menu title */
711 menu = strdup(km->desc);
712 km = get_keymap("FONT");
714 /* Take note of language font */
715 font = strdup(km->desc);
717 /* Remove unwanted items from list */
718 remove_keymap("MENU");
719 remove_keymap("FONT");
721 /* Look for keymaps not in database */
724 while ((dp = readdir(dirp)) != NULL) {
725 const char *ext = get_extension(dp->d_name);
727 if ((!strcmp(ext, ".fnt") ||
728 !strcmp(ext, ".kbd")) &&
729 !get_keymap(dp->d_name)) {
732 /* Remove any .fnt or .kbd extension */
733 q = strdup(dp->d_name);
734 *(get_extension(q)) = '\0';
735 add_keymap(q, 0, dp->d_name);
740 "'%s' not in database\n",
747 fprintf(stderr, "Could not open directory '%s'\n", dir);
749 /* Sort items in keymap */
750 num_keymaps = get_num_keymaps();
752 km_sorted = (struct keymap **)
753 malloc(num_keymaps*sizeof(struct keymap *));
755 /* Make array of pointers to items in hash */
757 SLIST_FOREACH(km, &head, entries)
758 km_sorted[items++] = km;
760 /* Change '8x8' to '8x08' so sort works as we might expect... */
761 kludge_desc(km_sorted, num_keymaps);
763 qsort(km_sorted, num_keymaps, sizeof(struct keymap *), compare_keymap);
765 /* ...change back again */
766 unkludge_desc(km_sorted, num_keymaps);
769 for (i=0; i<num_keymaps; i++)
770 printf("%s\n", km_sorted[i]->desc);
774 show_dialog(km_sorted, num_keymaps);
780 * Display usage information and exit
786 fprintf(stderr, "usage: %s\t[-K] [-V] [-d|-default] [-h|-help] "
787 "[-l|-lang language]\n\t\t[-p|-print] [-r|-restore] [-s|-show] "
788 "[-v|-verbose]\n", program);
793 parse_args(int argc, char **argv)
797 for (i=1; i<argc; i++) {
798 if (argv[i][0] != '-')
800 else if (!strcmp(argv[i], "-help") || !strcmp(argv[i], "-h"))
802 else if (!strcmp(argv[i], "-verbose") || !strcmp(argv[i], "-v"))
804 else if (!strcmp(argv[i], "-lang") || !strcmp(argv[i], "-l"))
809 else if (!strcmp(argv[i], "-default") || !strcmp(argv[i], "-d"))
811 else if (!strcmp(argv[i], "-show") || !strcmp(argv[i], "-s"))
813 else if (!strcmp(argv[i], "-print") || !strcmp(argv[i], "-p"))
815 else if (!strcmp(argv[i], "-restore") ||
816 !strcmp(argv[i], "-r")) {
817 vidcontrol(font_current);
819 } else if (!strcmp(argv[i], "-K"))
821 else if (!strcmp(argv[i], "-V"))
829 * A front-end for the 'vidfont' and 'kbdmap' programs.
832 main(int argc, char **argv)
835 x11 = system("kbdcontrol -d >/dev/null");
838 fprintf(stderr, "You are not on a virtual console - "
839 "expect certain strange side-effects\n");
843 using_vt = check_vt();
845 keymapdir = DEFAULT_SC_KEYMAP_DIR;
846 fontdir = DEFAULT_SC_FONT_DIR;
847 font_default = DEFAULT_SC_FONT;
854 program = extract_name(argv[0]);
856 font_current = get_font();
857 if (font_current == NULL)
858 font_current = font_default;
860 if (strcmp(program, "kbdmap"))
865 /* Parse command line arguments */
866 parse_args(argc, argv);
868 /* Read and display options */