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