xref: /freebsd/contrib/dialog/ttysize.c (revision fe75646a0234a261c0013bf1840fdac4acaf0cec)
1 /*
2  *  $Id: ttysize.c,v 1.2 2019/07/25 00:07:15 tom Exp $
3  *
4  *  ttysize.c -- obtain terminal-size for dialog
5  *
6  *  Copyright 2018,2019	Thomas E. Dickey
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU Lesser General Public License, version 2.1
10  *  as published by the Free Software Foundation.
11  *
12  *  This program is distributed in the hope that it will be useful, but
13  *  WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  *  Lesser General Public License for more details.
16  *
17  *  You should have received a copy of the GNU Lesser General Public
18  *  License along with this program; if not, write to
19  *	Free Software Foundation, Inc.
20  *	51 Franklin St., Fifth Floor
21  *	Boston, MA 02110, USA.
22  *
23  *  An earlier version of this program lists as authors
24  *	Savio Lam (lam836@cs.cuhk.hk)
25  */
26 
27 #include <dialog.h>
28 
29 /*
30  * This is based on work I did for ncurses in 1997, and improved/extended for
31  * other terminal-based programs.  The comments are from my original version -TD
32  */
33 
34 #ifdef HAVE_TERMIOS_H
35 #include <termios.h>
36 #endif
37 
38 #ifdef HAVE_SYS_IOCTL_H
39 # include <sys/ioctl.h>
40 #endif
41 
42 #ifdef NEED_PTEM_H
43  /* On SCO, they neglected to define struct winsize in termios.h -- it's only
44   * in termio.h and ptem.h (the former conflicts with other definitions).
45   */
46 # include <sys/stream.h>
47 # include <sys/ptem.h>
48 #endif
49 
50 /*
51  * SCO defines TIOCGSIZE and the corresponding struct.  Other systems (SunOS,
52  * Solaris, IRIX) define TIOCGWINSZ and struct winsize.
53  */
54 #if defined(TIOCGSIZE)
55 # define IOCTL_WINSIZE TIOCGSIZE
56 # define STRUCT_WINSIZE struct ttysize
57 # define WINSIZE_ROWS(n) (int)n.ts_lines
58 # define WINSIZE_COLS(n) (int)n.ts_cols
59 #elif defined(TIOCGWINSZ)
60 # define IOCTL_WINSIZE TIOCGWINSZ
61 # define STRUCT_WINSIZE struct winsize
62 # define WINSIZE_ROWS(n) (int)n.ws_row
63 # define WINSIZE_COLS(n) (int)n.ws_col
64 #else
65 # undef HAVE_SIZECHANGE
66 #endif
67 
68 int
69 dlg_ttysize(int fd, int *high, int *wide)
70 {
71     int rc = -1;
72 #ifdef HAVE_SIZECHANGE
73     if (isatty(fd)) {
74 	STRUCT_WINSIZE size;
75 
76 	if (ioctl(fd, IOCTL_WINSIZE, &size) >= 0) {
77 	    *high = WINSIZE_ROWS(size);
78 	    *wide = WINSIZE_COLS(size);
79 	    rc = 0;
80 	}
81     }
82 #else
83     *high = 24;
84     *wide = 80;
85 #endif /* HAVE_SIZECHANGE */
86     return rc;
87 }
88