9d491df8b2ea4abcf5f7ec366c8829e9956760f1
[oftp] / src / tui_list.c
1 #include <stdlib.h>
2 #include <string.h>
3 #include <assert.h>
4 #include "darray.h"
5 #include "tui.h"
6 #include "tuipriv.h"
7 #include "tgfx.h"
8
9 static void free_list(struct tui_widget *w, void *cls);
10 static void draw_list(struct tui_widget *w, void *cls);
11
12 struct tui_widget *tui_list(const char *title, int x, int y, int width, int height, tui_callback cbfunc, void *cbdata)
13 {
14         struct tui_list *w;
15
16         if(!(w = calloc(1, sizeof *w))) {
17                 return 0;
18         }
19         w->type = TUI_LIST;
20         w->title = strdup(title);
21         w->x = x;
22         w->y = y;
23         w->width = width;
24         w->height = height;
25
26         w->entries = darr_alloc(0, sizeof *w->entries);
27
28         if(cbfunc) {
29                 tui_set_callback((struct tui_widget*)w, TUI_ONMODIFY, cbfunc, cbdata);
30         }
31         tui_set_callback((struct tui_widget*)w, TUI_FREE, free_list, 0);
32         tui_set_callback((struct tui_widget*)w, TUI_DRAW, draw_list, 0);
33         return (struct tui_widget*)w;
34 }
35
36 static void free_list(struct tui_widget *w, void *cls)
37 {
38         darr_free(((struct tui_list*)w)->entries);
39 }
40
41
42 void tui_clear_list(struct tui_widget *w)
43 {
44         struct tui_list *wl = (struct tui_list*)w;
45         assert(wl->type == TUI_LIST);
46         darr_clear(wl->entries);
47 }
48
49 void tui_add_list_item(struct tui_widget *w, const char *text)
50 {
51         struct tui_list *wl = (struct tui_list*)w;
52         assert(wl->type == TUI_LIST);
53         darr_push(wl->entries, &text);
54 }
55
56 static void draw_list(struct tui_widget *w, void *cls)
57 {
58         int i, x, y, num;
59         struct tui_list *wl = (struct tui_list*)w;
60
61         tui_wtoscr(w, 0, 0, &x, &y);    
62
63         tg_bgcolor(1);
64         tg_rect(wl->title, x, y, wl->width, wl->height, TGFX_FRAME);
65
66         num = darr_size(wl->entries);
67         if(num > wl->height - 2) {
68                 num = wl->height - 2;
69         }
70
71         x++;
72         for(i=0; i<num; i++) {
73                 tg_text(x, ++y, "%s", wl->entries[i]);
74         }
75 }