dbb47e4690644720f2e002173841a7bfa1108dd6
[apps/madtty.git] / demo / boxshell.c
1 /* Just a simple example program that creates a terminal in a frame
2  * and lets the user interact with it.
3  *
4  * To compile:
5  *    gcc -o boxshell boxshell.c $(pkg-config madtty --cflags --libs)
6  */
7
8 #include <ncurses.h>
9 #include <stdio.h>
10 #include <signal.h>
11 #include <string.h>
12 #include <sys/time.h>
13 #include <time.h>
14
15 #include <madtty/madtty.h>
16
17 static unsigned char getout = 0;
18 static int screen_w, screen_h;
19 static WINDOW *term_win;
20
21 void sigchld(int signo __attribute__((unused)))
22 {
23     getout = 1;
24 }
25
26 int main(void)
27 {
28     struct timeval next = { 0, 0 };
29     madtty_t *rt;
30     int pos = 0;
31     char buf[BUFSIZ];
32
33     signal(SIGCHLD, sigchld);
34
35     madtty_initialize();
36     getmaxyx(stdscr, screen_h, screen_w);
37
38     /* create a window with a frame */
39     term_win = newwin(screen_h - 2, screen_w - 2, 1, 1);
40     rt = madtty_create(screen_h - 2, screen_w - 2);
41     {
42         const char *path = getenv("SHELL") ?: "/bin/sh";
43         const char *args[] = { path, "--login", NULL};
44
45         madtty_forkpty(rt, path, args);
46     }
47
48     /* keep reading keypresses from the user and passing them to the terminal;
49      * also, redraw the terminal to the window at each iteration */
50     pos = 0;
51     while (!getout) {
52         fd_set rfds;
53         struct timeval tv = { 0 , 1000 }, t;
54         int ch;
55
56         FD_ZERO(&rfds);
57         FD_SET(rt->pty, &rfds);
58
59         if (select(rt->pty + 1, &rfds, NULL, NULL, &tv) > 0) {
60             if (madtty_process(rt))
61                 break;
62         }
63
64         while ((ch = getch()) != ERR) {
65             madtty_keypress(rt, ch); /* pass the keypress for handling */
66         }
67
68         gettimeofday(&t, NULL);
69         if (timercmp(&t, &next, >=)) {
70             madtty_draw(rt, term_win, 0, 0);
71             wrefresh(term_win);
72             gettimeofday(&next, NULL);
73             next.tv_usec += 1000 * 1000 / 50;
74             if (next.tv_usec > 1000 * 1000) {
75                 next.tv_usec -= 1000 * 1000;
76                 next.tv_sec++;
77             }
78         }
79     }
80
81     endwin();
82     return 0;
83 }