chiark / gitweb /
@@@ tty mess
[mLib] / ui / example / progress-test.c
1 #include <locale.h>
2 #include <time.h>
3
4 #include <unistd.h>
5
6 #include "tty.h"
7 #include "ttyprogress.h"
8
9 static unsigned pos;
10 static const char *left, *right;
11
12 static void render_bar(struct ttyprogress_item *item,
13                        struct ttyprogress_render *render)
14 {
15   ttyprogress_putleft(render, " %u%%", pos/3);
16   if (left) ttyprogress_putleft(render, " %s", left);
17   ttyprogress_putright(render, " %u ", pos);
18   if (right) ttyprogress_putright(render, "%s ", right);
19   ttyprogress_showbar(render, pos/300.0);
20 }
21
22 static void render_sub(struct ttyprogress_item *item,
23                        struct ttyprogress_render *render)
24 {
25   unsigned subpos = pos%30;
26
27   ttyprogress_putleft(render, " %u%%", (10*subpos + 1)/3);
28   ttyprogress_putright(render, " %u ", subpos);
29   ttyprogress_showbar(render, subpos/30.0);
30 }
31
32 int main(int argc, char *argv[])
33 {
34   struct tty *tty;
35   struct ttyprogress progress;
36   struct ttyprogress_item
37     bar = TTYPROGRESS_ITEM_INIT,
38     sub = TTYPROGRESS_ITEM_INIT;
39
40   setlocale(LC_ALL, "");
41
42   if (argc >= 2) left = argv[1];
43   if (argc >= 3) right = argv[2];
44
45   tty = tty_open(stdout, TTF_BORROW, 0);
46   if (ttyprogress_init(&progress, tty))
47     fprintf(stderr, "terminal insufficiently capable\n");
48
49   bar.render = render_bar; ttyprogress_additem(&progress, &bar);
50   for (pos = 0; pos <= 300; pos++) {
51     if (pos%30)
52       ;
53     else if (pos%60)
54       { sub.render = render_sub; ttyprogress_additem(&progress, &sub); }
55     else
56       ttyprogress_removeitem(&progress, &sub);
57     ttyprogress_update(&progress);
58     usleep(100000);
59   }
60   ttyprogress_removeitem(&progress, &bar);
61   ttyprogress_update(&progress);
62
63   ttyprogress_clear(&progress);
64   tty_close(tty);
65
66   return (0);
67 }