xref: /freebsd/usr.sbin/vidcontrol/vidcontrol.c (revision 5608fd23c27fa1e8ee595d7b678cbfd35d657fbe)
1 /*-
2  * Copyright (c) 1994-1996 Søren Schmidt
3  * All rights reserved.
4  *
5  * Portions of this software are based in part on the work of
6  * Sascha Wildner <saw@online.de> contributed to The DragonFly Project
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer,
13  *    in this position and unchanged.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. The name of the author may not be used to endorse or promote products
18  *    derived from this software without specific prior written permission
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  *
31  * $DragonFly: src/usr.sbin/vidcontrol/vidcontrol.c,v 1.10 2005/03/02 06:08:29 joerg Exp $
32  */
33 
34 #ifndef lint
35 static const char rcsid[] =
36   "$FreeBSD$";
37 #endif /* not lint */
38 
39 #include <ctype.h>
40 #include <err.h>
41 #include <limits.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <unistd.h>
46 #include <sys/fbio.h>
47 #include <sys/consio.h>
48 #include <sys/endian.h>
49 #include <sys/errno.h>
50 #include <sys/param.h>
51 #include <sys/types.h>
52 #include <sys/stat.h>
53 #include <sys/sysctl.h>
54 #include "path.h"
55 #include "decode.h"
56 
57 
58 #define	DATASIZE(x)	((x).w * (x).h * 256 / 8)
59 
60 /* Screen dump modes */
61 #define DUMP_FMT_RAW	1
62 #define DUMP_FMT_TXT	2
63 /* Screen dump options */
64 #define DUMP_FBF	0
65 #define DUMP_ALL	1
66 /* Screen dump file format revision */
67 #define DUMP_FMT_REV	1
68 
69 static const char *legal_colors[16] = {
70 	"black", "blue", "green", "cyan",
71 	"red", "magenta", "brown", "white",
72 	"grey", "lightblue", "lightgreen", "lightcyan",
73 	"lightred", "lightmagenta", "yellow", "lightwhite"
74 };
75 
76 static struct {
77 	int			active_vty;
78 	vid_info_t		console_info;
79 	unsigned char		screen_map[256];
80 	int			video_mode_number;
81 	struct video_info	video_mode_info;
82 } cur_info;
83 
84 struct vt4font_header {
85 	uint8_t		magic[8];
86 	uint8_t		width;
87 	uint8_t		height;
88 	uint16_t	pad;
89 	uint32_t	glyph_count;
90 	uint32_t	map_count[4];
91 } __packed;
92 
93 static int	hex = 0;
94 static int	vesa_cols;
95 static int	vesa_rows;
96 static int	font_height;
97 static int	colors_changed;
98 static int	video_mode_changed;
99 static int	normal_fore_color, normal_back_color;
100 static int	revers_fore_color, revers_back_color;
101 static int	vt4_mode = 0;
102 static struct	vid_info info;
103 static struct	video_info new_mode_info;
104 
105 
106 /*
107  * Initialize revert data.
108  *
109  * NOTE: the following parameters are not yet saved/restored:
110  *
111  *   screen saver timeout
112  *   cursor type
113  *   mouse character and mouse show/hide state
114  *   vty switching on/off state
115  *   history buffer size
116  *   history contents
117  *   font maps
118  */
119 
120 static void
121 init(void)
122 {
123 	if (ioctl(0, VT_GETACTIVE, &cur_info.active_vty) == -1)
124 		errc(1, errno, "getting active vty");
125 
126 	cur_info.console_info.size = sizeof(cur_info.console_info);
127 
128 	if (ioctl(0, CONS_GETINFO, &cur_info.console_info) == -1)
129 		errc(1, errno, "getting console information");
130 
131 	/* vt(4) use unicode, so no screen mapping required. */
132 	if (vt4_mode == 0 &&
133 	    ioctl(0, GIO_SCRNMAP, &cur_info.screen_map) == -1)
134 		errc(1, errno, "getting screen map");
135 
136 	if (ioctl(0, CONS_GET, &cur_info.video_mode_number) == -1)
137 		errc(1, errno, "getting video mode number");
138 
139 	cur_info.video_mode_info.vi_mode = cur_info.video_mode_number;
140 
141 	if (ioctl(0, CONS_MODEINFO, &cur_info.video_mode_info) == -1)
142 		errc(1, errno, "getting video mode parameters");
143 
144 	normal_fore_color = cur_info.console_info.mv_norm.fore;
145 	normal_back_color = cur_info.console_info.mv_norm.back;
146 	revers_fore_color = cur_info.console_info.mv_rev.fore;
147 	revers_back_color = cur_info.console_info.mv_rev.back;
148 }
149 
150 
151 /*
152  * If something goes wrong along the way we call revert() to go back to the
153  * console state we came from (which is assumed to be working).
154  *
155  * NOTE: please also read the comments of init().
156  */
157 
158 static void
159 revert(void)
160 {
161 	int size[3];
162 
163 	ioctl(0, VT_ACTIVATE, cur_info.active_vty);
164 
165 	fprintf(stderr, "\033[=%dA", cur_info.console_info.mv_ovscan);
166 	fprintf(stderr, "\033[=%dF", cur_info.console_info.mv_norm.fore);
167 	fprintf(stderr, "\033[=%dG", cur_info.console_info.mv_norm.back);
168 	fprintf(stderr, "\033[=%dH", cur_info.console_info.mv_rev.fore);
169 	fprintf(stderr, "\033[=%dI", cur_info.console_info.mv_rev.back);
170 
171 	if (vt4_mode == 0)
172 		ioctl(0, PIO_SCRNMAP, &cur_info.screen_map);
173 
174 	if (cur_info.video_mode_number >= M_VESA_BASE)
175 		ioctl(0, _IO('V', cur_info.video_mode_number - M_VESA_BASE),
176 		      NULL);
177 	else
178 		ioctl(0, _IO('S', cur_info.video_mode_number), NULL);
179 
180 	if (cur_info.video_mode_info.vi_flags & V_INFO_GRAPHICS) {
181 		size[0] = cur_info.video_mode_info.vi_width / 8;
182 		size[1] = cur_info.video_mode_info.vi_height /
183 			  cur_info.console_info.font_size;
184 		size[2] = cur_info.console_info.font_size;
185 
186 		ioctl(0, KDRASTER, size);
187 	}
188 }
189 
190 
191 /*
192  * Print a short usage string describing all options, then exit.
193  */
194 
195 static void
196 usage(void)
197 {
198 	if (vt4_mode)
199 		fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n",
200 "usage: vidcontrol [-CHPpx] [-b color] [-c appearance] [-f [size] file]",
201 "                  [-g geometry] [-h size] [-i adapter | mode]",
202 "                  [-M char] [-m on | off] [-r foreground background]",
203 "                  [-S on | off] [-s number] [-T xterm | cons25] [-t N | off]",
204 "                  [mode] [foreground [background]] [show]");
205 	else
206 		fprintf(stderr, "%s\n%s\n%s\n%s\n%s\n",
207 "usage: vidcontrol [-CdHLPpx] [-b color] [-c appearance] [-f [size] file]",
208 "                  [-g geometry] [-h size] [-i adapter | mode] [-l screen_map]",
209 "                  [-M char] [-m on | off] [-r foreground background]",
210 "                  [-S on | off] [-s number] [-T xterm | cons25] [-t N | off]",
211 "                  [mode] [foreground [background]] [show]");
212 	exit(1);
213 }
214 
215 /* Detect presence of vt(4). */
216 static int
217 is_vt4(void)
218 {
219 	char vty_name[4] = "";
220 	size_t len = sizeof(vty_name);
221 
222 	if (sysctlbyname("kern.vty", vty_name, &len, NULL, 0) != 0)
223 		return (0);
224 	return (strcmp(vty_name, "vt") == 0);
225 }
226 
227 /*
228  * Retrieve the next argument from the command line (for options that require
229  * more than one argument).
230  */
231 
232 static char *
233 nextarg(int ac, char **av, int *indp, int oc, int strict)
234 {
235 	if (*indp < ac)
236 		return(av[(*indp)++]);
237 
238 	if (strict != 0) {
239 		revert();
240 		errx(1, "option requires two arguments -- %c", oc);
241 	}
242 
243 	return(NULL);
244 }
245 
246 
247 /*
248  * Guess which file to open. Try to open each combination of a specified set
249  * of file name components.
250  */
251 
252 static FILE *
253 openguess(const char *a[], const char *b[], const char *c[], const char *d[], char **name)
254 {
255 	FILE *f;
256 	int i, j, k, l;
257 
258 	for (i = 0; a[i] != NULL; i++) {
259 		for (j = 0; b[j] != NULL; j++) {
260 			for (k = 0; c[k] != NULL; k++) {
261 				for (l = 0; d[l] != NULL; l++) {
262 					asprintf(name, "%s%s%s%s",
263 						 a[i], b[j], c[k], d[l]);
264 
265 					f = fopen(*name, "r");
266 
267 					if (f != NULL)
268 						return (f);
269 
270 					free(*name);
271 				}
272 			}
273 		}
274 	}
275 	return (NULL);
276 }
277 
278 
279 /*
280  * Load a screenmap from a file and set it.
281  */
282 
283 static void
284 load_scrnmap(const char *filename)
285 {
286 	FILE *fd;
287 	int size;
288 	char *name;
289 	scrmap_t scrnmap;
290 	const char *a[] = {"", SCRNMAP_PATH, NULL};
291 	const char *b[] = {filename, NULL};
292 	const char *c[] = {"", ".scm", NULL};
293 	const char *d[] = {"", NULL};
294 
295 	fd = openguess(a, b, c, d, &name);
296 
297 	if (fd == NULL) {
298 		revert();
299 		errx(1, "screenmap file not found");
300 	}
301 
302 	size = sizeof(scrnmap);
303 
304 	if (decode(fd, (char *)&scrnmap, size) != size) {
305 		rewind(fd);
306 
307 		if (fread(&scrnmap, 1, size, fd) != (size_t)size) {
308 			warnx("bad screenmap file");
309 			fclose(fd);
310 			revert();
311 			errx(1, "bad screenmap file");
312 		}
313 	}
314 
315 	if (ioctl(0, PIO_SCRNMAP, &scrnmap) == -1) {
316 		revert();
317 		errc(1, errno, "loading screenmap");
318 	}
319 
320 	fclose(fd);
321 }
322 
323 
324 /*
325  * Set the default screenmap.
326  */
327 
328 static void
329 load_default_scrnmap(void)
330 {
331 	scrmap_t scrnmap;
332 	int i;
333 
334 	for (i=0; i<256; i++)
335 		*((char*)&scrnmap + i) = i;
336 
337 	if (ioctl(0, PIO_SCRNMAP, &scrnmap) == -1) {
338 		revert();
339 		errc(1, errno, "loading default screenmap");
340 	}
341 }
342 
343 
344 /*
345  * Print the current screenmap to stdout.
346  */
347 
348 static void
349 print_scrnmap(void)
350 {
351 	unsigned char map[256];
352 	size_t i;
353 
354 	if (ioctl(0, GIO_SCRNMAP, &map) == -1) {
355 		revert();
356 		errc(1, errno, "getting screenmap");
357 	}
358 	for (i=0; i<sizeof(map); i++) {
359 		if (i != 0 && i % 16 == 0)
360 			fprintf(stdout, "\n");
361 
362 		if (hex != 0)
363 			fprintf(stdout, " %02x", map[i]);
364 		else
365 			fprintf(stdout, " %03d", map[i]);
366 	}
367 	fprintf(stdout, "\n");
368 
369 }
370 
371 
372 /*
373  * Determine a file's size.
374  */
375 
376 static int
377 fsize(FILE *file)
378 {
379 	struct stat sb;
380 
381 	if (fstat(fileno(file), &sb) == 0)
382 		return sb.st_size;
383 	else
384 		return -1;
385 }
386 
387 static vfnt_map_t *
388 load_vt4mappingtable(unsigned int nmappings, FILE *f)
389 {
390 	vfnt_map_t *t;
391 	unsigned int i;
392 
393 	if (nmappings == 0)
394 		return (NULL);
395 
396 	t = malloc(sizeof *t * nmappings);
397 
398 	if (fread(t, sizeof *t * nmappings, 1, f) != 1) {
399 		perror("mappings");
400 		exit(1);
401 	}
402 
403 	for (i = 0; i < nmappings; i++) {
404 		t[i].src = be32toh(t[i].src);
405 		t[i].dst = be16toh(t[i].dst);
406 		t[i].len = be16toh(t[i].len);
407 	}
408 
409 	return (t);
410 }
411 
412 static int
413 load_vt4font(FILE *f)
414 {
415 	struct vt4font_header fh;
416 	static vfnt_t vfnt;
417 	size_t glyphsize;
418 	unsigned int i;
419 
420 	if (fread(&fh, sizeof fh, 1, f) != 1) {
421 		perror("file_header");
422 		return (1);
423 	}
424 
425 	if (memcmp(fh.magic, "VFNT0002", 8) != 0) {
426 		fprintf(stderr, "Bad magic\n");
427 		return (1);
428 	}
429 
430 	for (i = 0; i < VFNT_MAPS; i++)
431 		vfnt.map_count[i] = be32toh(fh.map_count[i]);
432 	vfnt.glyph_count = be32toh(fh.glyph_count);
433 	vfnt.width = fh.width;
434 	vfnt.height = fh.height;
435 
436 	glyphsize = howmany(vfnt.width, 8) * vfnt.height * vfnt.glyph_count;
437 	vfnt.glyphs = malloc(glyphsize);
438 
439 	if (fread(vfnt.glyphs, glyphsize, 1, f) != 1) {
440 		perror("glyphs");
441 		return (1);
442 	}
443 
444 	for (i = 0; i < VFNT_MAPS; i++)
445 		vfnt.map[i] = load_vt4mappingtable(vfnt.map_count[i], f);
446 
447 	if (ioctl(STDIN_FILENO, PIO_VFONT, &vfnt) == -1) {
448 		perror("PIO_VFONT");
449 		return (1);
450 	}
451 	return (0);
452 }
453 
454 /*
455  * Load a font from file and set it.
456  */
457 
458 static void
459 load_font(const char *type, const char *filename)
460 {
461 	FILE	*fd;
462 	int	h, i, size, w;
463 	unsigned long io = 0;	/* silence stupid gcc(1) in the Wall mode */
464 	char	*name, *fontmap, size_sufx[6];
465 	const char	*a[] = {"", FONT_PATH, NULL};
466 	const char	*vt4a[] = {"", VT_FONT_PATH, NULL};
467 	const char	*b[] = {filename, NULL};
468 	const char	*c[] = {"", size_sufx, NULL};
469 	const char	*d[] = {"", ".fnt", NULL};
470 	vid_info_t _info;
471 
472 	struct sizeinfo {
473 		int w;
474 		int h;
475 		unsigned long io;
476 	} sizes[] = {{8, 16, PIO_FONT8x16},
477 		     {8, 14, PIO_FONT8x14},
478 		     {8,  8,  PIO_FONT8x8},
479 		     {0,  0,            0}};
480 
481 	if (vt4_mode) {
482 		size_sufx[0] = '\0';
483 	} else {
484 		_info.size = sizeof(_info);
485 		if (ioctl(0, CONS_GETINFO, &_info) == -1) {
486 			revert();
487 			warn("failed to obtain current video mode parameters");
488 			return;
489 		}
490 
491 		snprintf(size_sufx, sizeof(size_sufx), "-8x%d", _info.font_size);
492 	}
493 	fd = openguess((vt4_mode == 0) ? a : vt4a, b, c, d, &name);
494 
495 	if (fd == NULL) {
496 		revert();
497 		errx(1, "%s: can't load font file", filename);
498 	}
499 
500 	if (vt4_mode) {
501 		if(load_vt4font(fd))
502 			warn("failed to load font \"%s\"", filename);
503 		fclose(fd);
504 		return;
505 	}
506 
507 	if (type != NULL) {
508 		size = 0;
509 		if (sscanf(type, "%dx%d", &w, &h) == 2) {
510 			for (i = 0; sizes[i].w != 0; i++) {
511 				if (sizes[i].w == w && sizes[i].h == h) {
512 					size = DATASIZE(sizes[i]);
513 					io = sizes[i].io;
514 					font_height = sizes[i].h;
515 				}
516 			}
517 		}
518 		if (size == 0) {
519 			fclose(fd);
520 			revert();
521 			errx(1, "%s: bad font size specification", type);
522 		}
523 	} else {
524 		/* Apply heuristics */
525 
526 		int j;
527 		int dsize[2];
528 
529 		size = DATASIZE(sizes[0]);
530 		fontmap = (char*) malloc(size);
531 		dsize[0] = decode(fd, fontmap, size);
532 		dsize[1] = fsize(fd);
533 		free(fontmap);
534 
535 		size = 0;
536 		for (j = 0; j < 2; j++) {
537 			for (i = 0; sizes[i].w != 0; i++) {
538 				if (DATASIZE(sizes[i]) == dsize[j]) {
539 					size = dsize[j];
540 					io = sizes[i].io;
541 					font_height = sizes[i].h;
542 					j = 2;	/* XXX */
543 					break;
544 				}
545 			}
546 		}
547 
548 		if (size == 0) {
549 			fclose(fd);
550 			revert();
551 			errx(1, "%s: can't guess font size", filename);
552 		}
553 
554 		rewind(fd);
555 	}
556 
557 	fontmap = (char*) malloc(size);
558 
559 	if (decode(fd, fontmap, size) != size) {
560 		rewind(fd);
561 		if (fsize(fd) != size ||
562 		    fread(fontmap, 1, size, fd) != (size_t)size) {
563 			warnx("%s: bad font file", filename);
564 			fclose(fd);
565 			free(fontmap);
566 			revert();
567 			errx(1, "%s: bad font file", filename);
568 		}
569 	}
570 
571 	if (ioctl(0, io, fontmap) == -1) {
572 		revert();
573 		errc(1, errno, "loading font");
574 	}
575 
576 	fclose(fd);
577 	free(fontmap);
578 }
579 
580 
581 /*
582  * Set the timeout for the screensaver.
583  */
584 
585 static void
586 set_screensaver_timeout(char *arg)
587 {
588 	int nsec;
589 
590 	if (!strcmp(arg, "off")) {
591 		nsec = 0;
592 	} else {
593 		nsec = atoi(arg);
594 
595 		if ((*arg == '\0') || (nsec < 1)) {
596 			revert();
597 			errx(1, "argument must be a positive number");
598 		}
599 	}
600 
601 	if (ioctl(0, CONS_BLANKTIME, &nsec) == -1) {
602 		revert();
603 		errc(1, errno, "setting screensaver period");
604 	}
605 }
606 
607 
608 /*
609  * Set the cursor's shape/type.
610  */
611 
612 static void
613 set_cursor_type(char *appearance)
614 {
615 	int type;
616 
617 	if (!strcmp(appearance, "normal"))
618 		type = 0;
619 	else if (!strcmp(appearance, "blink"))
620 		type = 1;
621 	else if (!strcmp(appearance, "destructive"))
622 		type = 3;
623 	else {
624 		revert();
625 		errx(1, "argument to -c must be normal, blink or destructive");
626 	}
627 
628 	if (ioctl(0, CONS_CURSORTYPE, &type) == -1) {
629 		revert();
630 		errc(1, errno, "setting cursor type");
631 	}
632 }
633 
634 
635 /*
636  * Set the video mode.
637  */
638 
639 static int
640 video_mode(int argc, char **argv, int *mode_index)
641 {
642 	static struct {
643 		const char *name;
644 		unsigned long mode;
645 		unsigned long mode_num;
646 	} modes[] = {
647 		{ "80x25",        SW_TEXT_80x25,   M_TEXT_80x25 },
648 		{ "80x30",        SW_TEXT_80x30,   M_TEXT_80x30 },
649 		{ "80x43",        SW_TEXT_80x43,   M_TEXT_80x43 },
650 		{ "80x50",        SW_TEXT_80x50,   M_TEXT_80x50 },
651 		{ "80x60",        SW_TEXT_80x60,   M_TEXT_80x60 },
652 		{ "132x25",       SW_TEXT_132x25,  M_TEXT_132x25 },
653 		{ "132x30",       SW_TEXT_132x30,  M_TEXT_132x30 },
654 		{ "132x43",       SW_TEXT_132x43,  M_TEXT_132x43 },
655 		{ "132x50",       SW_TEXT_132x50,  M_TEXT_132x50 },
656 		{ "132x60",       SW_TEXT_132x60,  M_TEXT_132x60 },
657 		{ "VGA_40x25",    SW_VGA_C40x25,   M_VGA_C40x25 },
658 		{ "VGA_80x25",    SW_VGA_C80x25,   M_VGA_C80x25 },
659 		{ "VGA_80x30",    SW_VGA_C80x30,   M_VGA_C80x30 },
660 		{ "VGA_80x50",    SW_VGA_C80x50,   M_VGA_C80x50 },
661 		{ "VGA_80x60",    SW_VGA_C80x60,   M_VGA_C80x60 },
662 #ifdef SW_VGA_C90x25
663 		{ "VGA_90x25",    SW_VGA_C90x25,   M_VGA_C90x25 },
664 		{ "VGA_90x30",    SW_VGA_C90x30,   M_VGA_C90x30 },
665 		{ "VGA_90x43",    SW_VGA_C90x43,   M_VGA_C90x43 },
666 		{ "VGA_90x50",    SW_VGA_C90x50,   M_VGA_C90x50 },
667 		{ "VGA_90x60",    SW_VGA_C90x60,   M_VGA_C90x60 },
668 #endif
669 		{ "VGA_320x200",	SW_VGA_CG320,	M_CG320 },
670 		{ "EGA_80x25",		SW_ENH_C80x25,	M_ENH_C80x25 },
671 		{ "EGA_80x43",		SW_ENH_C80x43,	M_ENH_C80x43 },
672 		{ "VESA_132x25",	SW_VESA_C132x25,M_VESA_C132x25 },
673 		{ "VESA_132x43",	SW_VESA_C132x43,M_VESA_C132x43 },
674 		{ "VESA_132x50",	SW_VESA_C132x50,M_VESA_C132x50 },
675 		{ "VESA_132x60",	SW_VESA_C132x60,M_VESA_C132x60 },
676 		{ "VESA_800x600",	SW_VESA_800x600,M_VESA_800x600 },
677 		{ NULL, 0, 0 },
678 	};
679 
680 	int new_mode_num = 0;
681 	unsigned long mode = 0;
682 	int cur_mode;
683 	int ioerr;
684 	int size[3];
685 	int i;
686 
687 	if (ioctl(0, CONS_GET, &cur_mode) < 0)
688 		err(1, "cannot get the current video mode");
689 
690 	/*
691 	 * Parse the video mode argument...
692 	 */
693 
694 	if (*mode_index < argc) {
695 		if (!strncmp(argv[*mode_index], "MODE_", 5)) {
696 			if (!isdigit(argv[*mode_index][5]))
697 				errx(1, "invalid video mode number");
698 
699 			new_mode_num = atoi(&argv[*mode_index][5]);
700 		} else {
701 			for (i = 0; modes[i].name != NULL; ++i) {
702 				if (!strcmp(argv[*mode_index], modes[i].name)) {
703 					mode = modes[i].mode;
704 					new_mode_num = modes[i].mode_num;
705 					break;
706 				}
707 			}
708 
709 			if (modes[i].name == NULL)
710 				return EXIT_FAILURE;
711 			if (ioctl(0, mode, NULL) < 0) {
712 				warn("cannot set videomode");
713 				return EXIT_FAILURE;
714 			}
715 		}
716 
717 		/*
718 		 * Collect enough information about the new video mode...
719 		 */
720 
721 		new_mode_info.vi_mode = new_mode_num;
722 
723 		if (ioctl(0, CONS_MODEINFO, &new_mode_info) == -1) {
724 			revert();
725 			errc(1, errno, "obtaining new video mode parameters");
726 		}
727 
728 		if (mode == 0) {
729 			if (new_mode_num >= M_VESA_BASE)
730 				mode = _IO('V', new_mode_num - M_VESA_BASE);
731 			else
732 				mode = _IO('S', new_mode_num);
733 		}
734 
735 		/*
736 		 * Try setting the new mode.
737 		 */
738 
739 		if (ioctl(0, mode, NULL) == -1) {
740 			revert();
741 			errc(1, errno, "setting video mode");
742 		}
743 
744 		/*
745 		 * For raster modes it's not enough to just set the mode.
746 		 * We also need to explicitly set the raster mode.
747 		 */
748 
749 		if (new_mode_info.vi_flags & V_INFO_GRAPHICS) {
750 			/* font size */
751 
752 			if (font_height == 0)
753 				font_height = cur_info.console_info.font_size;
754 
755 			size[2] = font_height;
756 
757 			/* adjust columns */
758 
759 			if ((vesa_cols * 8 > new_mode_info.vi_width) ||
760 			    (vesa_cols <= 0)) {
761 				size[0] = new_mode_info.vi_width / 8;
762 			} else {
763 				size[0] = vesa_cols;
764 			}
765 
766 			/* adjust rows */
767 
768 			if ((vesa_rows * font_height > new_mode_info.vi_height) ||
769 			    (vesa_rows <= 0)) {
770 				size[1] = new_mode_info.vi_height /
771 					  font_height;
772 			} else {
773 				size[1] = vesa_rows;
774 			}
775 
776 			/* set raster mode */
777 
778 			if (ioctl(0, KDRASTER, size)) {
779 				ioerr = errno;
780 				if (cur_mode >= M_VESA_BASE)
781 					ioctl(0,
782 					    _IO('V', cur_mode - M_VESA_BASE),
783 					    NULL);
784 				else
785 					ioctl(0, _IO('S', cur_mode), NULL);
786 				revert();
787 				warnc(ioerr, "cannot activate raster display");
788 				return EXIT_FAILURE;
789 			}
790 		}
791 
792 		video_mode_changed = 1;
793 
794 		(*mode_index)++;
795 	}
796 	return EXIT_SUCCESS;
797 }
798 
799 
800 /*
801  * Return the number for a specified color name.
802  */
803 
804 static int
805 get_color_number(char *color)
806 {
807 	int i;
808 
809 	for (i=0; i<16; i++) {
810 		if (!strcmp(color, legal_colors[i]))
811 			return i;
812 	}
813 	return -1;
814 }
815 
816 
817 /*
818  * Get normal text and background colors.
819  */
820 
821 static void
822 get_normal_colors(int argc, char **argv, int *_index)
823 {
824 	int color;
825 
826 	if (*_index < argc && (color = get_color_number(argv[*_index])) != -1) {
827 		(*_index)++;
828 		fprintf(stderr, "\033[=%dF", color);
829 		normal_fore_color=color;
830 		colors_changed = 1;
831 		if (*_index < argc
832 		    && (color = get_color_number(argv[*_index])) != -1
833 		    && color < 8) {
834 			(*_index)++;
835 			fprintf(stderr, "\033[=%dG", color);
836 			normal_back_color=color;
837 		}
838 	}
839 }
840 
841 
842 /*
843  * Get reverse text and background colors.
844  */
845 
846 static void
847 get_reverse_colors(int argc, char **argv, int *_index)
848 {
849 	int color;
850 
851 	if ((color = get_color_number(argv[*(_index)-1])) != -1) {
852 		fprintf(stderr, "\033[=%dH", color);
853 		revers_fore_color=color;
854 		colors_changed = 1;
855 		if (*_index < argc
856 		    && (color = get_color_number(argv[*_index])) != -1
857 		    && color < 8) {
858 			(*_index)++;
859 			fprintf(stderr, "\033[=%dI", color);
860 			revers_back_color=color;
861 		}
862 	}
863 }
864 
865 
866 /*
867  * Set normal and reverse foreground and background colors.
868  */
869 
870 static void
871 set_colors(void)
872 {
873 	fprintf(stderr, "\033[=%dF", normal_fore_color);
874 	fprintf(stderr, "\033[=%dG", normal_back_color);
875 	fprintf(stderr, "\033[=%dH", revers_fore_color);
876 	fprintf(stderr, "\033[=%dI", revers_back_color);
877 }
878 
879 
880 /*
881  * Switch to virtual terminal #arg.
882  */
883 
884 static void
885 set_console(char *arg)
886 {
887 	int n;
888 
889 	if(!arg || strspn(arg,"0123456789") != strlen(arg)) {
890 		revert();
891 		errx(1, "bad console number");
892 	}
893 
894 	n = atoi(arg);
895 
896 	if (n < 1 || n > 16) {
897 		revert();
898 		errx(1, "console number out of range");
899 	} else if (ioctl(0, VT_ACTIVATE, n) == -1) {
900 		revert();
901 		errc(1, errno, "switching vty");
902 	}
903 }
904 
905 
906 /*
907  * Sets the border color.
908  */
909 
910 static void
911 set_border_color(char *arg)
912 {
913 	int color;
914 
915 	if ((color = get_color_number(arg)) != -1) {
916 		fprintf(stderr, "\033[=%dA", color);
917 	}
918 	else
919 		usage();
920 }
921 
922 static void
923 set_mouse_char(char *arg)
924 {
925 	struct mouse_info mouse;
926 	long l;
927 
928 	l = strtol(arg, NULL, 0);
929 
930 	if ((l < 0) || (l > UCHAR_MAX - 3)) {
931 		revert();
932 		warnx("argument to -M must be 0 through %d", UCHAR_MAX - 3);
933 		return;
934 	}
935 
936 	mouse.operation = MOUSE_MOUSECHAR;
937 	mouse.u.mouse_char = (int)l;
938 
939 	if (ioctl(0, CONS_MOUSECTL, &mouse) == -1) {
940 		revert();
941 		errc(1, errno, "setting mouse character");
942 	}
943 }
944 
945 
946 /*
947  * Show/hide the mouse.
948  */
949 
950 static void
951 set_mouse(char *arg)
952 {
953 	struct mouse_info mouse;
954 
955 	if (!strcmp(arg, "on")) {
956 		mouse.operation = MOUSE_SHOW;
957 	} else if (!strcmp(arg, "off")) {
958 		mouse.operation = MOUSE_HIDE;
959 	} else {
960 		revert();
961 		errx(1, "argument to -m must be either on or off");
962 	}
963 
964 	if (ioctl(0, CONS_MOUSECTL, &mouse) == -1) {
965 		revert();
966 		errc(1, errno, "%sing the mouse",
967 		     mouse.operation == MOUSE_SHOW ? "show" : "hid");
968 	}
969 }
970 
971 
972 static void
973 set_lockswitch(char *arg)
974 {
975 	int data;
976 
977 	if (!strcmp(arg, "off")) {
978 		data = 0x01;
979 	} else if (!strcmp(arg, "on")) {
980 		data = 0x02;
981 	} else {
982 		revert();
983 		errx(1, "argument to -S must be either on or off");
984 	}
985 
986 	if (ioctl(0, VT_LOCKSWITCH, &data) == -1) {
987 		revert();
988 		errc(1, errno, "turning %s vty switching",
989 		     data == 0x01 ? "off" : "on");
990 	}
991 }
992 
993 
994 /*
995  * Return the adapter name for a specified type.
996  */
997 
998 static const char
999 *adapter_name(int type)
1000 {
1001     static struct {
1002 	int type;
1003 	const char *name;
1004     } names[] = {
1005 	{ KD_MONO,	"MDA" },
1006 	{ KD_HERCULES,	"Hercules" },
1007 	{ KD_CGA,	"CGA" },
1008 	{ KD_EGA,	"EGA" },
1009 	{ KD_VGA,	"VGA" },
1010 	{ KD_PC98,	"PC-98xx" },
1011 	{ KD_TGA,	"TGA" },
1012 	{ -1,		"Unknown" },
1013     };
1014 
1015     int i;
1016 
1017     for (i = 0; names[i].type != -1; ++i)
1018 	if (names[i].type == type)
1019 	    break;
1020     return names[i].name;
1021 }
1022 
1023 
1024 /*
1025  * Show graphics adapter information.
1026  */
1027 
1028 static void
1029 show_adapter_info(void)
1030 {
1031 	struct video_adapter_info ad;
1032 
1033 	ad.va_index = 0;
1034 
1035 	if (ioctl(0, CONS_ADPINFO, &ad) == -1) {
1036 		revert();
1037 		errc(1, errno, "obtaining adapter information");
1038 	}
1039 
1040 	printf("fb%d:\n", ad.va_index);
1041 	printf("    %.*s%d, type:%s%s (%d), flags:0x%x\n",
1042 	       (int)sizeof(ad.va_name), ad.va_name, ad.va_unit,
1043 	       (ad.va_flags & V_ADP_VESA) ? "VESA " : "",
1044 	       adapter_name(ad.va_type), ad.va_type, ad.va_flags);
1045 	printf("    initial mode:%d, current mode:%d, BIOS mode:%d\n",
1046 	       ad.va_initial_mode, ad.va_mode, ad.va_initial_bios_mode);
1047 	printf("    frame buffer window:0x%zx, buffer size:0x%zx\n",
1048 	       ad.va_window, ad.va_buffer_size);
1049 	printf("    window size:0x%zx, origin:0x%x\n",
1050 	       ad.va_window_size, ad.va_window_orig);
1051 	printf("    display start address (%d, %d), scan line width:%d\n",
1052 	       ad.va_disp_start.x, ad.va_disp_start.y, ad.va_line_width);
1053 	printf("    reserved:0x%zx\n", ad.va_unused0);
1054 }
1055 
1056 
1057 /*
1058  * Show video mode information.
1059  */
1060 
1061 static void
1062 show_mode_info(void)
1063 {
1064 	char buf[80];
1065 	struct video_info _info;
1066 	int c;
1067 	int mm;
1068 	int mode;
1069 
1070 	printf("    mode#     flags   type    size       "
1071 	       "font      window      linear buffer\n");
1072 	printf("---------------------------------------"
1073 	       "---------------------------------------\n");
1074 
1075 	for (mode = 0; mode <= M_VESA_MODE_MAX; ++mode) {
1076 		_info.vi_mode = mode;
1077 		if (ioctl(0, CONS_MODEINFO, &_info))
1078 			continue;
1079 		if (_info.vi_mode != mode)
1080 			continue;
1081 
1082 		printf("%3d (0x%03x)", mode, mode);
1083     		printf(" 0x%08x", _info.vi_flags);
1084 		if (_info.vi_flags & V_INFO_GRAPHICS) {
1085 			c = 'G';
1086 
1087 			if (_info.vi_mem_model == V_INFO_MM_PLANAR)
1088 				snprintf(buf, sizeof(buf), "%dx%dx%d %d",
1089 				    _info.vi_width, _info.vi_height,
1090 				    _info.vi_depth, _info.vi_planes);
1091 			else {
1092 				switch (_info.vi_mem_model) {
1093 				case V_INFO_MM_PACKED:
1094 					mm = 'P';
1095 					break;
1096 				case V_INFO_MM_DIRECT:
1097 					mm = 'D';
1098 					break;
1099 				case V_INFO_MM_CGA:
1100 					mm = 'C';
1101 					break;
1102 				case V_INFO_MM_HGC:
1103 					mm = 'H';
1104 					break;
1105 				case V_INFO_MM_VGAX:
1106 					mm = 'V';
1107 					break;
1108 				default:
1109 					mm = ' ';
1110 					break;
1111 				}
1112 				snprintf(buf, sizeof(buf), "%dx%dx%d %c",
1113 				    _info.vi_width, _info.vi_height,
1114 				    _info.vi_depth, mm);
1115 			}
1116 		} else {
1117 			c = 'T';
1118 
1119 			snprintf(buf, sizeof(buf), "%dx%d",
1120 				 _info.vi_width, _info.vi_height);
1121 		}
1122 
1123 		printf(" %c %-15s", c, buf);
1124 		snprintf(buf, sizeof(buf), "%dx%d",
1125 			 _info.vi_cwidth, _info.vi_cheight);
1126 		printf(" %-5s", buf);
1127     		printf(" 0x%05zx %2dk %2dk",
1128 		       _info.vi_window, (int)_info.vi_window_size/1024,
1129 		       (int)_info.vi_window_gran/1024);
1130     		printf(" 0x%08zx %dk\n",
1131 		       _info.vi_buffer, (int)_info.vi_buffer_size/1024);
1132 	}
1133 }
1134 
1135 
1136 static void
1137 show_info(char *arg)
1138 {
1139 	if (!strcmp(arg, "adapter")) {
1140 		show_adapter_info();
1141 	} else if (!strcmp(arg, "mode")) {
1142 		show_mode_info();
1143 	} else {
1144 		revert();
1145 		errx(1, "argument to -i must be either adapter or mode");
1146 	}
1147 }
1148 
1149 
1150 static void
1151 test_frame(void)
1152 {
1153 	int i, cur_mode, fore;
1154 
1155 	fore = 15;
1156 
1157 	if (ioctl(0, CONS_GET, &cur_mode) < 0)
1158 		err(1, "must be on a virtual console");
1159 	switch (cur_mode) {
1160 	case M_PC98_80x25:
1161 	case M_PC98_80x30:
1162 		fore = 7;
1163 		break;
1164 	}
1165 
1166 	fprintf(stdout, "\033[=0G\n\n");
1167 	for (i=0; i<8; i++) {
1168 		fprintf(stdout, "\033[=%dF\033[=0G        %2d \033[=%dF%-16s"
1169 				"\033[=%dF\033[=0G        %2d \033[=%dF%-16s        "
1170 				"\033[=%dF %2d \033[=%dGBACKGROUND\033[=0G\n",
1171 			fore, i, i, legal_colors[i],
1172 			fore, i+8, i+8, legal_colors[i+8],
1173 			fore, i, i);
1174 	}
1175 	fprintf(stdout, "\033[=%dF\033[=%dG\033[=%dH\033[=%dI\n",
1176 		info.mv_norm.fore, info.mv_norm.back,
1177 		info.mv_rev.fore, info.mv_rev.back);
1178 }
1179 
1180 
1181 /*
1182  * Snapshot the video memory of that terminal, using the CONS_SCRSHOT
1183  * ioctl, and writes the results to stdout either in the special
1184  * binary format (see manual page for details), or in the plain
1185  * text format.
1186  */
1187 
1188 static void
1189 dump_screen(int mode, int opt)
1190 {
1191 	scrshot_t shot;
1192 	vid_info_t _info;
1193 
1194 	_info.size = sizeof(_info);
1195 
1196 	if (ioctl(0, CONS_GETINFO, &_info) == -1) {
1197 		revert();
1198 		errc(1, errno, "obtaining current video mode parameters");
1199 		return;
1200 	}
1201 
1202 	shot.x = shot.y = 0;
1203 	shot.xsize = _info.mv_csz;
1204 	shot.ysize = _info.mv_rsz;
1205 	if (opt == DUMP_ALL)
1206 		shot.ysize += _info.mv_hsz;
1207 
1208 	shot.buf = alloca(shot.xsize * shot.ysize * sizeof(u_int16_t));
1209 	if (shot.buf == NULL) {
1210 		revert();
1211 		errx(1, "failed to allocate memory for dump");
1212 	}
1213 
1214 	if (ioctl(0, CONS_SCRSHOT, &shot) == -1) {
1215 		revert();
1216 		errc(1, errno, "dumping screen");
1217 	}
1218 
1219 	if (mode == DUMP_FMT_RAW) {
1220 		printf("SCRSHOT_%c%c%c%c", DUMP_FMT_REV, 2,
1221 		       shot.xsize, shot.ysize);
1222 
1223 		fflush(stdout);
1224 
1225 		write(STDOUT_FILENO, shot.buf,
1226 		      shot.xsize * shot.ysize * sizeof(u_int16_t));
1227 	} else {
1228 		char *line;
1229 		int x, y;
1230 		u_int16_t ch;
1231 
1232 		line = alloca(shot.xsize + 1);
1233 
1234 		if (line == NULL) {
1235 			revert();
1236 			errx(1, "failed to allocate memory for line buffer");
1237 		}
1238 
1239 		for (y = 0; y < shot.ysize; y++) {
1240 			for (x = 0; x < shot.xsize; x++) {
1241 				ch = shot.buf[x + (y * shot.xsize)];
1242 				ch &= 0xff;
1243 
1244 				if (isprint(ch) == 0)
1245 					ch = ' ';
1246 
1247 				line[x] = (char)ch;
1248 			}
1249 
1250 			/* Trim trailing spaces */
1251 
1252 			do {
1253 				line[x--] = '\0';
1254 			} while (line[x] == ' ' && x != 0);
1255 
1256 			puts(line);
1257 		}
1258 
1259 		fflush(stdout);
1260 	}
1261 }
1262 
1263 
1264 /*
1265  * Set the console history buffer size.
1266  */
1267 
1268 static void
1269 set_history(char *opt)
1270 {
1271 	int size;
1272 
1273 	size = atoi(opt);
1274 
1275 	if ((*opt == '\0') || size < 0) {
1276 		revert();
1277 		errx(1, "argument must be a positive number");
1278 	}
1279 
1280 	if (ioctl(0, CONS_HISTORY, &size) == -1) {
1281 		revert();
1282 		errc(1, errno, "setting history buffer size");
1283 	}
1284 }
1285 
1286 
1287 /*
1288  * Clear the console history buffer.
1289  */
1290 
1291 static void
1292 clear_history(void)
1293 {
1294 	if (ioctl(0, CONS_CLRHIST) == -1) {
1295 		revert();
1296 		errc(1, errno, "clearing history buffer");
1297 	}
1298 }
1299 
1300 static void
1301 set_terminal_mode(char *arg)
1302 {
1303 
1304 	if (strcmp(arg, "xterm") == 0)
1305 		fprintf(stderr, "\033[=T");
1306 	else if (strcmp(arg, "cons25") == 0)
1307 		fprintf(stderr, "\033[=1T");
1308 }
1309 
1310 
1311 int
1312 main(int argc, char **argv)
1313 {
1314 	char    *font, *type, *termmode;
1315 	const char *opts;
1316 	int	dumpmod, dumpopt, opt;
1317 	int	reterr;
1318 
1319 	vt4_mode = is_vt4();
1320 
1321 	init();
1322 
1323 	info.size = sizeof(info);
1324 
1325 	if (ioctl(0, CONS_GETINFO, &info) == -1)
1326 		err(1, "must be on a virtual console");
1327 	dumpmod = 0;
1328 	dumpopt = DUMP_FBF;
1329 	termmode = NULL;
1330 	if (vt4_mode)
1331 		opts = "b:Cc:f:g:h:Hi:M:m:pPr:S:s:T:t:x";
1332 	else
1333 		opts = "b:Cc:df:g:h:Hi:l:LM:m:pPr:S:s:T:t:x";
1334 
1335 	while ((opt = getopt(argc, argv, opts)) != -1)
1336 		switch(opt) {
1337 		case 'b':
1338 			set_border_color(optarg);
1339 			break;
1340 		case 'C':
1341 			clear_history();
1342 			break;
1343 		case 'c':
1344 			set_cursor_type(optarg);
1345 			break;
1346 		case 'd':
1347 			if (vt4_mode)
1348 				break;
1349 			print_scrnmap();
1350 			break;
1351 		case 'f':
1352 			type = optarg;
1353 			font = nextarg(argc, argv, &optind, 'f', 0);
1354 
1355 			if (font == NULL) {
1356 				type = NULL;
1357 				font = optarg;
1358 			}
1359 
1360 			load_font(type, font);
1361 			break;
1362 		case 'g':
1363 			if (sscanf(optarg, "%dx%d",
1364 			    &vesa_cols, &vesa_rows) != 2) {
1365 				revert();
1366 				warnx("incorrect geometry: %s", optarg);
1367 				usage();
1368 			}
1369                 	break;
1370 		case 'h':
1371 			set_history(optarg);
1372 			break;
1373 		case 'H':
1374 			dumpopt = DUMP_ALL;
1375 			break;
1376 		case 'i':
1377 			show_info(optarg);
1378 			break;
1379 		case 'l':
1380 			if (vt4_mode)
1381 				break;
1382 			load_scrnmap(optarg);
1383 			break;
1384 		case 'L':
1385 			if (vt4_mode)
1386 				break;
1387 			load_default_scrnmap();
1388 			break;
1389 		case 'M':
1390 			set_mouse_char(optarg);
1391 			break;
1392 		case 'm':
1393 			set_mouse(optarg);
1394 			break;
1395 		case 'p':
1396 			dumpmod = DUMP_FMT_RAW;
1397 			break;
1398 		case 'P':
1399 			dumpmod = DUMP_FMT_TXT;
1400 			break;
1401 		case 'r':
1402 			get_reverse_colors(argc, argv, &optind);
1403 			break;
1404 		case 'S':
1405 			set_lockswitch(optarg);
1406 			break;
1407 		case 's':
1408 			set_console(optarg);
1409 			break;
1410 		case 'T':
1411 			if (strcmp(optarg, "xterm") != 0 &&
1412 			    strcmp(optarg, "cons25") != 0)
1413 				usage();
1414 			termmode = optarg;
1415 			break;
1416 		case 't':
1417 			set_screensaver_timeout(optarg);
1418 			break;
1419 		case 'x':
1420 			hex = 1;
1421 			break;
1422 		default:
1423 			usage();
1424 		}
1425 
1426 	if (dumpmod != 0)
1427 		dump_screen(dumpmod, dumpopt);
1428 	reterr = video_mode(argc, argv, &optind);
1429 	get_normal_colors(argc, argv, &optind);
1430 
1431 	if (optind < argc && !strcmp(argv[optind], "show")) {
1432 		test_frame();
1433 		optind++;
1434 	}
1435 
1436 	video_mode(argc, argv, &optind);
1437 	if (termmode != NULL)
1438 		set_terminal_mode(termmode);
1439 
1440 	get_normal_colors(argc, argv, &optind);
1441 
1442 	if (colors_changed || video_mode_changed) {
1443 		if (!(new_mode_info.vi_flags & V_INFO_GRAPHICS)) {
1444 			if ((normal_back_color < 8) && (revers_back_color < 8)) {
1445 				set_colors();
1446 			} else {
1447 				revert();
1448 				errx(1, "bg color for text modes must be < 8");
1449 			}
1450 		} else {
1451 			set_colors();
1452 		}
1453 	}
1454 
1455 	if ((optind != argc) || (argc == 1))
1456 		usage();
1457 	return reterr;
1458 }
1459 
1460