Support resizing
[apps/madtty.git] / demo / boxshell.c
index 00a11a0..fa7d2ee 100644 (file)
@@ -7,6 +7,7 @@
 
 #include <ncurses.h>
 
+#include <fcntl.h>
 #include <signal.h>
 #include <stdio.h>
 #include <string.h>
@@ -17,7 +18,7 @@
 
 #include <madtty/madtty.h>
 
-static unsigned char getout = 0;
+static int getout = 0, sigwinch = 0;
 static int screen_w, screen_h;
 static WINDOW *term_win;
 
@@ -28,6 +29,7 @@ void handler(int signo)
         getout = 1;
         break;
       case SIGWINCH:
+        sigwinch = 1;
         break;
     }
 }
@@ -45,7 +47,7 @@ int main(void)
 
     /* create a window with a frame */
     term_win = newwin(screen_h - 2, screen_w - 2, 1, 1);
-    rt = madtty_create(screen_h - 2, screen_w - 2);
+    rt = madtty_create(screen_h - 2, screen_w -2);
     {
         const char *path = getenv("SHELL") ?: "/bin/sh";
         const char *args[] = { path, "--login", NULL};
@@ -71,19 +73,32 @@ int main(void)
             }
         }
 
-        while ((ch = getch()) != ERR) {
-#if 0
-            if (ch == KEY_F(1)) {
-                struct winsize ws = {
-                    .ws_row = --rt->rows,
-                    .ws_col = --rt->cols,
-                };
-
-                erase();
-                ioctl(rt->pty, TIOCSWINSZ, &ws);
-                wresize(term_win, rt->rows, rt->cols);
+        if (sigwinch) {
+            int fd, cols = -1, rows = -1;
+            struct winsize w;
+
+            if ((fd = open("/dev/tty", O_RDONLY)) != -1) {
+                if (ioctl(fd, TIOCGWINSZ, &w) != -1) {
+                    rows = w.ws_row;
+                    cols = w.ws_col;
+                }
+                close(fd);
+            }
+            if (rows <= 0) {
+                rows = atoi(getenv("LINES") ?: "24");
+            }
+            if (cols <= 0) {
+                cols = atoi(getenv("COLUMNS") ?: "80");
             }
-#endif
+
+            resizeterm(rows, cols);
+            madtty_resize(rt, rows - 2, cols - 2);
+            wresize(term_win, rows - 2, cols - 2);
+            sigwinch = 0;
+            erase();
+        }
+
+        while ((ch = getch()) != ERR) {
             madtty_keypress(rt, ch); /* pass the keypress for handling */
             dirty = 1;
         }