#include <sys/ioctl.h>
#include <sys/queue.h>
#include <sys/time.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <term.h>
#include <termios.h>
#include <unistd.h>
#include "def.h"
#define NOBUF 512
int ttstarted;
char obuf[NOBUF];
size_t nobuf;
struct termios oldtty;
struct termios newtty;
int nrow;
int ncol;
void
ttopen(void)
{
if (!isatty(STDIN_FILENO) || !isatty(STDOUT_FILENO))
panic("standard input and output must be a terminal");
if (ttraw() == FALSE)
panic("aborting due to terminal initialize failure");
}
int
ttraw(void)
{
if (tcgetattr(0, &oldtty) == -1) {
dobeep();
ewprintf("ttopen can't get terminal attributes");
return (FALSE);
}
(void)memcpy(&newtty, &oldtty, sizeof(newtty));
newtty.c_cc[VMIN] = 1;
newtty.c_cc[VTIME] = 0;
newtty.c_iflag |= IGNBRK;
newtty.c_iflag &= ~(BRKINT | PARMRK | INLCR | IGNCR | ICRNL | IXON);
newtty.c_oflag &= ~OPOST;
newtty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
if (tcsetattr(0, TCSASOFT | TCSADRAIN, &newtty) == -1) {
dobeep();
ewprintf("ttopen can't tcsetattr");
return (FALSE);
}
ttstarted = 1;
return (TRUE);
}
void
ttclose(void)
{
if (ttstarted) {
if (ttcooked() == FALSE)
panic("");
ttstarted = 0;
}
}
int
ttcooked(void)
{
ttflush();
if (tcsetattr(0, TCSASOFT | TCSADRAIN, &oldtty) == -1) {
dobeep();
ewprintf("ttclose can't tcsetattr");
return (FALSE);
}
return (TRUE);
}
int
ttputc(int c)
{
if (nobuf >= NOBUF)
ttflush();
obuf[nobuf++] = c;
return (c);
}
void
ttflush(void)
{
ssize_t written;
char *buf = obuf;
if (nobuf == 0 || batch == 1)
return;
while ((written = write(fileno(stdout), buf, nobuf)) != nobuf) {
if (written == -1) {
if (errno == EINTR)
continue;
panic("ttflush write failed");
}
buf += written;
nobuf -= written;
}
nobuf = 0;
}
int
ttgetc(void)
{
char c;
ssize_t ret;
do {
ret = read(STDIN_FILENO, &c, 1);
if (ret == -1 && errno == EINTR) {
if (winch_flag) {
redraw(0, 0);
winch_flag = 0;
}
} else if (ret == -1 && errno == EIO)
panic("lost stdin");
else if (ret == 1)
break;
} while (1);
return ((int) c) & 0xFF;
}
int
charswaiting(void)
{
int x;
return ((ioctl(0, FIONREAD, &x) == -1) ? 0 : x);
}
void
panic(char *s)
{
static int panicking = 0;
if (panicking)
return;
else
panicking = 1;
ttclose();
(void) fputs("panic: ", stderr);
(void) fputs(s, stderr);
(void) fputc('\n', stderr);
exit(1);
}
int
ttwait(int msec)
{
struct pollfd pfd[1];
pfd[0].fd = 0;
pfd[0].events = POLLIN;
if ((poll(pfd, 1, msec)) == 0)
return (TRUE);
return (FALSE);
}