#include <sys/cdefs.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <termios.h>
#include <unistd.h>
static const char query[] =
"\0337"
"\033[r"
"\033[999;999H"
"\033[6n"
"\0338";
static void
usage(void)
{
fprintf(stderr, "usage: resizewin [-z]\n");
exit(1);
}
int
main(int argc, char **argv)
{
struct termios old, new;
struct winsize w;
struct timeval then, now;
char data[20];
int ch, cnt, error, fd, ret, zflag;
error = 0;
zflag = 0;
while ((ch = getopt(argc, argv, "z")) != -1) {
switch (ch) {
case 'z':
zflag = 1;
break;
case '?':
default:
usage();
}
}
argc -= optind;
if (argc != 0)
usage();
if ((fd = open("/dev/tty", O_RDWR | O_NONBLOCK)) == -1)
exit(1);
if (zflag) {
if (ioctl(fd, TIOCGWINSZ, &w) == -1)
exit(1);
if (w.ws_row != 0 && w.ws_col != 0)
exit(0);
}
if (tcgetattr(fd, &old) == -1)
exit(1);
new = old;
new.c_cflag |= (CLOCAL | CREAD);
new.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
if (tcsetattr(fd, TCSAFLUSH, &new) == -1)
exit(1);
if (write(fd, query, sizeof(query) - 1) != sizeof(query) - 1) {
error = 1;
goto out;
}
bzero(data, sizeof(data));
gettimeofday(&then, NULL);
cnt = 0;
while (1) {
ret = read(fd, data + cnt, 1);
if (ret == -1) {
if (errno == EAGAIN) {
gettimeofday(&now, NULL);
timersub(&now, &then, &now);
if (now.tv_sec >= 2) {
warnx("timeout reading from terminal");
error = 1;
goto out;
}
usleep(20000);
continue;
}
error = 1;
goto out;
}
if (data[cnt] == 'R')
break;
cnt++;
if (cnt == sizeof(data) - 2) {
warnx("response too long");
error = 1;
goto out;
}
}
if (sscanf(data, "\033[%hu;%huR", &w.ws_row, &w.ws_col) != 2) {
error = 1;
warnx("unable to parse response");
goto out;
}
if (ioctl(fd, TIOCSWINSZ, &w) == -1)
error = 1;
out:
tcsetattr(fd, TCSANOW, &old);
close(fd);
exit(error);
}