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