1 /* Just a simple example program that creates a terminal in a frame
2 * and lets the user interact with it.
5 * gcc -o boxshell boxshell.c $(pkg-config madtty --cflags --libs)
14 #include <sys/ioctl.h>
19 #include <madtty/madtty.h>
21 static int getout = 0, sigwinch = 0;
22 static int screen_w, screen_h;
23 static WINDOW *term_win;
24 static struct timeval const slice = { 0, 1000 * 1000 / 100 };
26 void handler(int signo)
38 static struct timeval timeval_add(struct timeval a, struct timeval b)
40 int usec = a.tv_usec + b.tv_usec;
42 while (usec > 1000 * 1000) {
50 static int is_expired(struct timeval now, struct timeval expiry)
52 return now.tv_sec > expiry.tv_sec
53 || (now.tv_sec == expiry.tv_sec && now.tv_usec > expiry.tv_usec);
62 signal(SIGCHLD, handler);
63 signal(SIGWINCH, handler);
66 getmaxyx(stdscr, screen_h, screen_w);
68 /* create a window with a frame */
69 term_win = newwin(screen_h - 2, screen_w - 2, 1, 1);
70 rt = madtty_create(screen_h - 2, screen_w -2);
72 const char *path = getenv("SHELL") ?: "/bin/sh";
73 const char *args[] = { path, "--login", NULL};
75 madtty_forkpty(rt, path, args, &pty);
78 /* keep reading keypresses from the user and passing them to the terminal;
79 * also, redraw the terminal to the window at each iteration */
80 gettimeofday(&next, NULL);
82 struct timeval tv = { 0, 1000 * 1000 / 100 };
90 if (select(pty + 1, &rfds, NULL, NULL, &tv) > 0) {
91 if (FD_ISSET(pty, &rfds)) {
98 int fd, cols = -1, rows = -1;
101 if ((fd = open("/dev/tty", O_RDONLY)) != -1) {
102 if (ioctl(fd, TIOCGWINSZ, &w) != -1) {
109 rows = atoi(getenv("LINES") ?: "24");
112 cols = atoi(getenv("COLUMNS") ?: "80");
115 resizeterm(rows, cols);
116 madtty_resize(rt, rows - 2, cols - 2);
117 wresize(term_win, rows - 2, cols - 2);
122 while ((ch = getch()) != ERR) {
123 madtty_keypress(rt, ch); /* pass the keypress for handling */
127 gettimeofday(&tv, NULL);
128 if (dirty && is_expired(tv, next)) {
129 madtty_draw(rt, term_win, 0, 0);
132 next = timeval_add(tv, slice);