xref: /netbsd-src/external/mit/libuv/dist/docs/code/tty-gravity/main.c (revision 0e552da7216834a96e91ad098e59272b41087480)
1*0e552da7Schristos #include <stdio.h>
2*0e552da7Schristos #include <string.h>
3*0e552da7Schristos #include <unistd.h>
4*0e552da7Schristos #include <uv.h>
5*0e552da7Schristos 
6*0e552da7Schristos uv_loop_t *loop;
7*0e552da7Schristos uv_tty_t tty;
8*0e552da7Schristos uv_timer_t tick;
9*0e552da7Schristos uv_write_t write_req;
10*0e552da7Schristos int width, height;
11*0e552da7Schristos int pos = 0;
12*0e552da7Schristos char *message = "  Hello TTY  ";
13*0e552da7Schristos 
update(uv_timer_t * req)14*0e552da7Schristos void update(uv_timer_t *req) {
15*0e552da7Schristos     char data[500];
16*0e552da7Schristos 
17*0e552da7Schristos     uv_buf_t buf;
18*0e552da7Schristos     buf.base = data;
19*0e552da7Schristos     buf.len = sprintf(data, "\033[2J\033[H\033[%dB\033[%luC\033[42;37m%s",
20*0e552da7Schristos                             pos,
21*0e552da7Schristos                             (unsigned long) (width-strlen(message))/2,
22*0e552da7Schristos                             message);
23*0e552da7Schristos     uv_write(&write_req, (uv_stream_t*) &tty, &buf, 1, NULL);
24*0e552da7Schristos 
25*0e552da7Schristos     pos++;
26*0e552da7Schristos     if (pos > height) {
27*0e552da7Schristos         uv_tty_reset_mode();
28*0e552da7Schristos         uv_timer_stop(&tick);
29*0e552da7Schristos     }
30*0e552da7Schristos }
31*0e552da7Schristos 
main()32*0e552da7Schristos int main() {
33*0e552da7Schristos     loop = uv_default_loop();
34*0e552da7Schristos 
35*0e552da7Schristos     uv_tty_init(loop, &tty, STDOUT_FILENO, 0);
36*0e552da7Schristos     uv_tty_set_mode(&tty, 0);
37*0e552da7Schristos 
38*0e552da7Schristos     if (uv_tty_get_winsize(&tty, &width, &height)) {
39*0e552da7Schristos         fprintf(stderr, "Could not get TTY information\n");
40*0e552da7Schristos         uv_tty_reset_mode();
41*0e552da7Schristos         return 1;
42*0e552da7Schristos     }
43*0e552da7Schristos 
44*0e552da7Schristos     fprintf(stderr, "Width %d, height %d\n", width, height);
45*0e552da7Schristos     uv_timer_init(loop, &tick);
46*0e552da7Schristos     uv_timer_start(&tick, update, 200, 200);
47*0e552da7Schristos     return uv_run(loop, UV_RUN_DEFAULT);
48*0e552da7Schristos }
49