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