Collapse termio/termios/sgtty terminal interface down to Posix termios.
[mmh] / uip / termsbr.c
1 /*
2 ** termsbr.c -- termcap support
3 **
4 ** This code is Copyright (c) 2002, by the authors of nmh.  See the
5 ** COPYRIGHT file in the root directory of the nmh distribution for
6 ** complete copyright information.
7 */
8
9 #include <h/mh.h>
10
11 #include <termios.h>
12
13 #ifdef HAVE_TERMCAP_H
14 # include <termcap.h>
15 #endif
16
17 /* <sys/ioctl.h> is need anyway for ioctl()
18 #ifdef GWINSZ_IN_SYS_IOCTL
19 */
20 # include <sys/ioctl.h>
21 /*
22 #endif
23 */
24
25 #ifdef WINSIZE_IN_PTEM
26 # include <sys/stream.h>
27 # include <sys/ptem.h>
28 #endif
29
30 #if BUFSIZ<2048
31 # define TXTSIZ 2048
32 #else
33 # define TXTSIZ BUFSIZ
34 #endif
35
36 /*
37 ** These variables are sometimes defined in,
38 ** and needed by the termcap library.
39 */
40 #ifdef HAVE_OSPEED
41 # ifdef MUST_DEFINE_OSPEED
42 extern short ospeed;
43 extern char PC;
44 # endif
45 #else
46 short ospeed;
47 char PC;
48 #endif
49
50 static long speedcode;
51
52 static int initCO = 0;
53
54 static int CO = 80;      /* number of colums */
55
56 static char termcap[TXTSIZ];
57
58
59 static void
60 read_termcap(void)
61 {
62         char *bp, *cp;
63         char *term;
64
65 #ifndef TGETENT_ACCEPTS_NULL
66         char termbuf[TXTSIZ];
67 #endif
68
69         struct termios tio;
70         static int inited = 0;
71
72         if (inited++)
73                 return;
74
75         if (!(term = getenv("TERM")))
76                 return;
77
78 /*
79 ** If possible, we let tgetent allocate its own termcap buffer
80 */
81 #ifdef TGETENT_ACCEPTS_NULL
82         if (tgetent(NULL, term) != TGETENT_SUCCESS)
83                 return;
84 #else
85         if (tgetent(termbuf, term) != TGETENT_SUCCESS)
86                 return;
87 #endif
88
89         speedcode = cfgetospeed(&tio);
90
91         if (!initCO && (CO = tgetnum("co")) <= 0)
92                 CO = 80;
93
94         cp = termcap;
95         if ((bp = tgetstr("pc", &cp)))
96                 PC = *bp;
97 }
98
99
100 int
101 sc_width(void)
102 {
103 #ifdef TIOCGWINSZ
104         struct winsize win;
105         int width;
106
107         if (ioctl(fileno(stderr), TIOCGWINSZ, &win) != NOTOK
108                         && (width = win.ws_col) > 0) {
109                 CO = width;
110                 initCO++;
111         } else
112 #endif /* TIOCGWINSZ */
113                 read_termcap();
114
115         return CO;
116 }