b3c8f2d9d033c20c1357f901962c1492e55ef7c3
[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
31     signal(SIGCHLD, sigchld);
32
33     madtty_initialize();
34     getmaxyx(stdscr, screen_h, screen_w);
35
36     /* create a window with a frame */
37     term_win = newwin(screen_h - 2, screen_w - 2, 1, 1);
38     rt = madtty_create(screen_h - 2, screen_w - 2);
39     {
40         const char *path = getenv("SHELL") ?: "/bin/sh";
41         const char *args[] = { path, "--login", NULL};
42
43         madtty_forkpty(rt, path, args);
44     }
45
46     /* keep reading keypresses from the user and passing them to the terminal;
47      * also, redraw the terminal to the window at each iteration */
48     while (!getout) {
49         fd_set rfds;
50         struct timeval tv = { 0 , 1000 }, t;
51         int ch;
52
53         FD_ZERO(&rfds);
54         FD_SET(rt->pty, &rfds);
55
56         if (select(rt->pty + 1, &rfds, NULL, NULL, &tv) > 0) {
57             if (madtty_process(rt))
58                 break;
59         }
60
61         while ((ch = getch()) != ERR) {
62             madtty_keypress(rt, ch); /* pass the keypress for handling */
63         }
64
65         gettimeofday(&t, NULL);
66         if (timercmp(&t, &next, >=)) {
67             madtty_draw(rt, term_win, 0, 0);
68             wrefresh(term_win);
69             gettimeofday(&next, NULL);
70             next.tv_usec += 1000 * 1000 / 50;
71             if (next.tv_usec > 1000 * 1000) {
72                 next.tv_usec -= 1000 * 1000;
73                 next.tv_sec++;
74             }
75         }
76     }
77
78     endwin();
79     return 0;
80 }