termcap.c revision 199250
1/*
2 * Copyright (c) 1994, Paul Richards.
3 *
4 * All rights reserved.
5 *
6 * This software may be used, modified, copied, distributed, and sold, in both
7 * source and binary form provided that the above copyright and these terms
8 * are retained, verbatim, as the first lines of this file.  Under no
9 * circumstances is the author responsible for the proper functioning of this
10 * software, nor does the author assume any responsibility for damages
11 * incurred with its use.
12 *
13 * $FreeBSD: head/usr.sbin/sade/termcap.c 199250 2009-11-13 11:28:54Z ed $
14 */
15
16#include "sade.h"
17#include <stdarg.h>
18#include <fcntl.h>
19#include <sys/errno.h>
20#include <sys/ioctl.h>
21#include <sys/consio.h>
22
23#define VTY_STATUS_LINE    24
24#define TTY_STATUS_LINE    23
25
26static void
27prompt_term(char **termp)
28{
29	char str[80];
30
31	printf("\nPlease set your TERM variable before running this program.\n");
32	printf("Defaulting to an ANSI compatible terminal - please press RETURN\n");
33	fgets(str, sizeof(str), stdin);	/* Just to make it interactive */
34	*termp = (char *)"ansi";
35}
36
37int
38set_termcap(void)
39{
40    char           *term;
41    int		   stat;
42    struct winsize ws;
43
44    term = getenv("TERM");
45    stat = ioctl(STDERR_FILENO, GIO_COLOR, &ColorDisplay);
46
47	if (isDebug())
48	    DebugFD = open("sade.debug", O_WRONLY|O_CREAT|O_TRUNC, 0644);
49	else
50	    DebugFD = -1;
51	if (DebugFD < 0)
52	    DebugFD = open("/dev/null", O_RDWR, 0);
53
54    if (!OnVTY || (stat < 0)) {
55	if (!term) {
56	    char *term;
57
58	    prompt_term(&term);
59	    if (setenv("TERM", term, 1) < 0)
60		return -1;
61	}
62	if (DebugFD < 0)
63	    DebugFD = open("/dev/null", O_RDWR, 0);
64    }
65    else {
66	int i, on;
67
68	if (getpid() == 1) {
69	    DebugFD = open("/dev/ttyv1", O_WRONLY);
70	    if (DebugFD != -1) {
71		on = 1;
72		i = ioctl(DebugFD, TIOCCONS, (char *)&on);
73		msgDebug("ioctl(%d, TIOCCONS, NULL) = %d (%s)\n",
74			 DebugFD, i, !i ? "success" : strerror(errno));
75	    }
76	}
77
78#ifdef PC98
79	if (!term) {
80	    if (setenv("TERM", "cons25w", 1) < 0)
81		return -1;
82	}
83#else
84	if (ColorDisplay) {
85	    if (!term) {
86		if (setenv("TERM", "xterm", 1) < 0)
87		    return -1;
88	    }
89	}
90	else {
91	    if (!term) {
92		if (setenv("TERM", "vt100", 1) < 0)
93		    return -1;
94	    }
95	}
96#endif
97    }
98    if (ioctl(0, TIOCGWINSZ, &ws) == -1) {
99	msgDebug("Unable to get terminal size - errno %d\n", errno);
100	ws.ws_row = 0;
101    }
102    StatusLine = ws.ws_row ? ws.ws_row - 1: (OnVTY ? VTY_STATUS_LINE : TTY_STATUS_LINE);
103    return 0;
104}
105