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>
37 #include <bsddialog.h>
44 #include <stringlist.h>
50 static const char *lang_default = DEFAULT_LANG;
51 static const char *font;
52 static const char *lang;
53 static const char *program;
54 static const char *keymapdir = DEFAULT_VT_KEYMAP_DIR;
55 static const char *fontdir = DEFAULT_VT_FONT_DIR;
56 static const char *font_default = DEFAULT_VT_FONT;
57 static const char *sysconfig = DEFAULT_SYSCONFIG;
58 static const char *font_current;
59 static const char *dir;
60 static const char *menu = "";
61 static const char *title = "Keyboard Menu";
74 SLIST_ENTRY(keymap) entries;
76 static SLIST_HEAD(slisthead, keymap) head = SLIST_HEAD_INITIALIZER(head);
80 * Get keymap entry for 'key', or NULL of not found
82 static struct keymap *
83 get_keymap(const char *key)
87 SLIST_FOREACH(km, &head, entries)
88 if (!strcmp(km->keym, key))
95 * Count the number of keymaps we found
103 SLIST_FOREACH(km, &head, entries)
110 * Remove any keymap with given keym
113 remove_keymap(const char *keym)
117 SLIST_FOREACH(km, &head, entries) {
118 if (!strcmp(keym, km->keym)) {
119 SLIST_REMOVE(&head, km, keymap, entries);
127 * Add to hash with 'key'
130 add_keymap(const char *desc, int mark, const char *keym)
132 struct keymap *km, *km_new;
134 /* Is there already an entry with this key? */
135 SLIST_FOREACH(km, &head, entries) {
136 if (!strcmp(km->keym, keym)) {
137 /* Reuse this entry */
139 km->desc = strdup(desc);
145 km_new = (struct keymap *) malloc (sizeof(struct keymap));
146 km_new->desc = strdup(desc);
147 km_new->keym = strdup(keym);
150 /* Add to keymap list */
151 SLIST_INSERT_HEAD(&head, km_new, entries);
155 * Return 0 if syscons is in use (to select legacy defaults).
164 if (sysctlbyname("kern.vty", &term, &len, NULL, 0) != 0 ||
165 strcmp(term, "vt") != 0)
171 * Figure out the default language to use.
178 if ((locale = getenv("LC_ALL")) == NULL &&
179 (locale = getenv("LC_CTYPE")) == NULL &&
180 (locale = getenv("LANG")) == NULL)
181 locale = lang_default;
183 /* Check for alias */
184 if (!strcmp(locale, "C"))
185 locale = DEFAULT_LANG;
191 * Extract filename part
194 extract_name(const char *name)
198 p = strrchr(name, '/');
199 if (p != NULL && p[1] != '\0')
206 * Return file extension or NULL
209 get_extension(const char *name)
213 p = strrchr(name, '.');
215 if (p != NULL && p[1] != '\0')
222 * Read font from /etc/rc.conf else return default.
223 * Freeing the memory is the caller's responsibility.
228 char line[256], buf[21];
231 FILE *fp = fopen(sysconfig, "r");
233 while (fgets(line, sizeof(line), fp)) {
239 matches = sscanf(line,
240 " font%dx%d = \"%20[-.0-9a-zA-Z_]",
243 if (strcmp(buf, "NO")) {
252 fprintf(stderr, "Could not open %s for reading\n", sysconfig);
258 * Set a font using 'vidcontrol'
261 vidcontrol(const char *fnt)
263 char *tmp, *p, *q, *cmd;
267 /* syscons test failed */
272 asprintf(&cmd, "vidcontrol -f %s", fnt);
280 /* Extract font size */
281 p = strrchr(tmp, '-');
282 if (p && p[1] != '\0') {
284 /* Remove any '.fnt' extension */
285 if ((q = strstr(p, ".fnt")))
289 * Check font size is valid, with no trailing characters
290 * ('&ch' should not be matched)
292 if (sscanf(p, "%dx%d%c", &i, &i, &ch) != 2)
293 fprintf(stderr, "Which font size? %s\n", fnt);
295 asprintf(&cmd, "vidcontrol -f %s %s", p, fnt);
297 fprintf(stderr, "%s\n", cmd);
302 fprintf(stderr, "Which font size? %s\n", fnt);
308 * Execute 'kbdcontrol' with the appropriate arguments
311 do_kbdcontrol(struct keymap *km)
314 asprintf(&kbd_cmd, "kbdcontrol -l %s/%s", dir, km->keym);
319 fprintf(stderr, "keymap=\"%s\"\n", km->keym);
324 * Call 'vidcontrol' with the appropriate arguments
327 do_vidfont(struct keymap *km)
329 char *vid_cmd, *tmp, *p, *q;
331 asprintf(&vid_cmd, "%s/%s", dir, km->keym);
335 tmp = strdup(km->keym);
336 p = strrchr(tmp, '-');
337 if (p && p[1]!='\0') {
339 q = get_extension(p);
342 printf("font%s=%s\n", p, km->keym);
349 * Display dialog from 'keymaps[]'
352 show_dialog(struct keymap **km_sorted, int num_keymaps)
354 struct bsddialog_conf conf;
355 struct bsddialog_menuitem *listitems;
358 if (bsddialog_init() == BSDDIALOG_ERROR) {
359 fprintf(stderr, "Error bsddialog: %s\n", bsddialog_geterror());
362 conf.title = __DECONST(char *, title);
364 listitems = calloc(num_keymaps + 1, sizeof(struct bsddialog_menuitem));
365 if (listitems == NULL) {
366 fprintf(stderr, "Failed to allocate memory in show_dialog");
371 /* start right font, assume that current font is equal
372 * to default font in /etc/rc.conf
374 * $font is the font which require the language $lang; e.g.
375 * russian *need* a koi8 font
376 * $font_current is the current font from /etc/rc.conf
378 if (font && strcmp(font, font_current))
381 /* Build up the menu */
382 for (i=0; i<num_keymaps; i++) {
383 listitems[i].prefix = "";
384 listitems[i].depth = 0;
385 listitems[i].bottomdesc = "";
386 listitems[i].on = false;
387 listitems[i].name = km_sorted[i]->desc;
388 listitems[i].desc = "";
390 bsddialog_initconf(&conf);
393 conf.key.enable_esc = true;
394 result = bsddialog_menu(&conf, menu, 0, 0, 0, num_keymaps, listitems,
396 if (result == BSDDIALOG_ERROR)
397 fprintf(stderr, "Error bsddialog: %s\n", bsddialog_geterror());
402 for (i = 0; i < num_keymaps; i++) {
403 if (listitems[i].on) {
405 if (!strcmp(program, "kdbmap"))
406 do_kbdcontrol(km_sorted[i]);
408 do_vidfont(km_sorted[i]);
415 if (font != NULL && strcmp(font, font_current))
416 /* Cancelled, restore old font */
417 vidcontrol(font_current);
423 * Search for 'token' in comma delimited array 'buffer'.
424 * Return true for found, false for not found.
427 find_token(const char *buffer, const char *token)
429 char *buffer_tmp, *buffer_copy, *inputstring;
433 buffer_copy = strdup(buffer);
434 buffer_tmp = buffer_copy;
435 inputstring = buffer_copy;
440 while ((*ap = strsep(&inputstring, ",")) != NULL) {
441 if (strcmp(buffer_tmp, token) == 0) {
453 * Compare function for qsort
456 compare_keymap(const void *a, const void *b)
459 /* We've been passed pointers to pointers, so: */
460 const struct keymap *km1 = *((const struct keymap * const *) a);
461 const struct keymap *km2 = *((const struct keymap * const *) b);
463 return strcmp(km1->desc, km2->desc);
467 * Compare function for qsort
470 compare_lang(const void *a, const void *b)
472 const char *l1 = *((const char * const *) a);
473 const char *l2 = *((const char * const *) b);
475 return strcmp(l1, l2);
479 * Change '8x8' to '8x08' so qsort will put it before eg. '8x14'
482 kludge_desc(struct keymap **km_sorted, int num_keymaps)
486 for (i=0; i<num_keymaps; i++) {
488 char *km = km_sorted[i]->desc;
489 if ((p = strstr(km, "8x8")) != NULL) {
496 /* Make enough space for the extra '0' */
498 km = realloc(km, len + 2);
500 for (j=len; j!=offset+1; j--)
505 km_sorted[i]->desc = km;
511 * Reverse 'kludge_desc()' - change '8x08' back to '8x8'
514 unkludge_desc(struct keymap **km_sorted, int num_keymaps)
518 for (i=0; i<num_keymaps; i++) {
520 char *km = km_sorted[i]->desc;
521 if ((p = strstr(km, "8x08")) != NULL) {
526 km = realloc(km, p - km - 1);
527 km_sorted[i]->desc = km;
533 * Return 0 if file exists and is readable, else -1
536 check_file(const char *keym)
540 if (access(keym, R_OK) == -1) {
542 asprintf(&fn, "%s/%s", dir, keym);
543 if (access(fn, R_OK) == -1) {
545 fprintf(stderr, "%s not found!\n", fn);
551 fprintf(stderr, "No read permission for %s!\n", keym);
559 * Read options from the relevant configuration file, then
567 int mark, num_keymaps, items, i;
568 char buffer[256], filename[PATH_MAX];
569 char keym[65], lng[65], desc[257];
570 char dialect[64], lang_abk[64];
572 struct keymap **km_sorted;
574 StringList *lang_list;
578 lang_list = sl_init();
580 sprintf(filename, "%s/INDEX.%s", dir, extract_name(dir));
582 /* en_US.ISO8859-1 -> en_..\.ISO8859-1 */
583 strlcpy(dialect, lang, sizeof(dialect));
584 if (strlen(dialect) >= 6 && dialect[2] == '_') {
590 /* en_US.ISO8859-1 -> en */
591 strlcpy(lang_abk, lang, sizeof(lang_abk));
592 if (strlen(lang_abk) >= 3 && lang_abk[2] == '_')
595 fprintf(stderr, "lang_default = %s\n", lang_default);
596 fprintf(stderr, "dialect = %s\n", dialect);
597 fprintf(stderr, "lang_abk = %s\n", lang_abk);
599 fp = fopen(filename, "r");
602 while (fgets(buffer, sizeof(buffer), fp)) {
613 /* Parse input, removing newline */
614 matches = sscanf(p, "%64[^:]:%64[^:]:%256[^:\n]",
617 if (strcmp(keym, "FONT") != 0 &&
618 strcmp(keym, "MENU") != 0 &&
619 strcmp(keym, "TITLE") != 0) {
620 /* Check file exists & is readable */
621 if (check_file(keym) == -1)
628 * Take note of supported languages, which
629 * might be in a comma-delimited list
631 char *tmp = strdup(lng);
634 for (delim = tmp; ; ) {
636 if (ch == ',' || ch == '\0') {
638 if (!sl_find(lang_list, tmp))
639 sl_add(lang_list, tmp);
646 /* Set empty language to default language */
653 /* 4) Your choice if it exists
654 * 3) Long match eg. en_GB.ISO8859-1 is equal to
656 * 2) short match 'de'
657 * 1) default langlist 'en'
660 * Language may be a comma separated list
661 * A higher match overwrites a lower
662 * A later entry overwrites a previous if it exists
663 * twice in the database
666 /* Check for favoured language */
667 km = get_keymap(keym);
668 mark = (km) ? km->mark : 0;
670 if (find_token(lg, lang))
671 add_keymap(desc, 4, keym);
672 else if (mark <= 3 && find_token(lg, dialect))
673 add_keymap(desc, 3, keym);
674 else if (mark <= 2 && find_token(lg, lang_abk))
675 add_keymap(desc, 2, keym);
676 else if (mark <= 1 && find_token(lg, lang_default))
677 add_keymap(desc, 1, keym);
679 add_keymap(desc, 0, keym);
684 fprintf(stderr, "Could not open %s for reading\n", filename);
687 qsort(lang_list->sl_str, lang_list->sl_cur, sizeof(char*),
689 printf("Currently supported languages: ");
690 for (i=0; i< (int) lang_list->sl_cur; i++)
691 printf("%s ", lang_list->sl_str[i]);
696 km = get_keymap("TITLE");
698 /* Take note of dialog title */
699 title = strdup(km->desc);
700 km = get_keymap("MENU");
702 /* Take note of menu title */
703 menu = strdup(km->desc);
704 km = get_keymap("FONT");
706 /* Take note of language font */
707 font = strdup(km->desc);
709 /* Remove unwanted items from list */
710 remove_keymap("FONT");
711 remove_keymap("MENU");
712 remove_keymap("TITLE");
714 /* Look for keymaps not in database */
717 while ((dp = readdir(dirp)) != NULL) {
718 const char *ext = get_extension(dp->d_name);
720 if ((!strcmp(ext, ".fnt") ||
721 !strcmp(ext, ".kbd")) &&
722 !get_keymap(dp->d_name)) {
725 /* Remove any .fnt or .kbd extension */
726 q = strdup(dp->d_name);
727 *(get_extension(q)) = '\0';
728 add_keymap(q, 0, dp->d_name);
733 "'%s' not in database\n",
740 fprintf(stderr, "Could not open directory '%s'\n", dir);
742 /* Sort items in keymap */
743 num_keymaps = get_num_keymaps();
745 km_sorted = (struct keymap **)
746 malloc(num_keymaps*sizeof(struct keymap *));
748 /* Make array of pointers to items in hash */
750 SLIST_FOREACH(km, &head, entries)
751 km_sorted[items++] = km;
753 /* Change '8x8' to '8x08' so sort works as we might expect... */
754 kludge_desc(km_sorted, num_keymaps);
756 qsort(km_sorted, num_keymaps, sizeof(struct keymap *), compare_keymap);
758 /* ...change back again */
759 unkludge_desc(km_sorted, num_keymaps);
762 for (i=0; i<num_keymaps; i++)
763 printf("%s\n", km_sorted[i]->desc);
767 show_dialog(km_sorted, num_keymaps);
773 * Display usage information and exit
779 fprintf(stderr, "usage: %s\t[-K] [-V] [-d|-default] [-h|-help] "
780 "[-l|-lang language]\n\t\t[-p|-print] [-r|-restore] [-s|-show] "
781 "[-v|-verbose]\n", program);
786 parse_args(int argc, char **argv)
790 for (i=1; i<argc; i++) {
791 if (argv[i][0] != '-')
793 else if (!strcmp(argv[i], "-help") || !strcmp(argv[i], "-h"))
795 else if (!strcmp(argv[i], "-verbose") || !strcmp(argv[i], "-v"))
797 else if (!strcmp(argv[i], "-lang") || !strcmp(argv[i], "-l"))
802 else if (!strcmp(argv[i], "-default") || !strcmp(argv[i], "-d"))
804 else if (!strcmp(argv[i], "-show") || !strcmp(argv[i], "-s"))
806 else if (!strcmp(argv[i], "-print") || !strcmp(argv[i], "-p"))
808 else if (!strcmp(argv[i], "-restore") ||
809 !strcmp(argv[i], "-r")) {
810 vidcontrol(font_current);
812 } else if (!strcmp(argv[i], "-K"))
814 else if (!strcmp(argv[i], "-V"))
822 * A front-end for the 'vidfont' and 'kbdmap' programs.
825 main(int argc, char **argv)
828 x11 = system("kbdcontrol -d >/dev/null");
831 fprintf(stderr, "You are not on a virtual console - "
832 "expect certain strange side-effects\n");
836 using_vt = check_vt();
838 keymapdir = DEFAULT_SC_KEYMAP_DIR;
839 fontdir = DEFAULT_SC_FONT_DIR;
840 font_default = DEFAULT_SC_FONT;
847 program = extract_name(argv[0]);
849 font_current = get_font();
850 if (font_current == NULL)
851 font_current = font_default;
853 if (strcmp(program, "kbdmap"))
858 /* Parse command line arguments */
859 parse_args(argc, argv);
861 /* Read and display options */