- added libdrawtext
[demo_prior] / src / imtk / button.c
1 #include <string.h>
2 #include <assert.h>
3 #include "imtk.h"
4 #include "state.h"
5 #include "draw.h"
6
7 static void calc_button_size(const char *label, int *wret, int *hret);
8 static void draw_button(int id, const char *label, int x, int y, int over);
9
10 int imtk_button(int id, const char *label, int x, int y)
11 {
12         int w, h, res = 0;
13         int over = 0;
14
15         assert(id >= 0);
16
17         if(x == IMTK_AUTO || y == IMTK_AUTO) {
18                 imtk_layout_get_pos(&x, &y);
19         }
20
21         calc_button_size(label, &w, &h);
22
23         if(imtk_hit_test(x, y, w, h)) {
24                 imtk_set_hot(id);
25                 over = 1;
26         }
27
28         if(imtk_button_state(IMTK_LEFT_BUTTON)) {
29                 if(over) {
30                         imtk_set_active(id);
31                 }
32         } else { /* mouse button up */
33                 if(imtk_is_active(id)) {
34                         imtk_set_active(-1);
35                         if(imtk_is_hot(id) && over) {
36                                 res = 1;
37                         }
38                 }
39         }
40
41         draw_button(id, label, x, y, over);
42         imtk_layout_advance(w, h);
43         return res;
44 }
45
46 static void draw_button(int id, const char *label, int x, int y, int over)
47 {
48         float tcol[4], bcol[4];
49         int width, height, active = imtk_is_active(id);
50         unsigned int attr = 0;
51
52         if(over) attr |= IMTK_FOCUS_BIT;
53         if(active) attr |= IMTK_PRESS_BIT;
54
55         calc_button_size(label, &width, &height);
56
57         memcpy(tcol, imtk_get_color(IMTK_TOP_COLOR | attr), sizeof tcol);
58         memcpy(bcol, imtk_get_color(IMTK_BOTTOM_COLOR | attr), sizeof bcol);
59
60         imtk_draw_rect(x, y, width, height, tcol, bcol);
61         imtk_draw_frame(x, y, width, height, active ? FRAME_INSET : FRAME_OUTSET);
62
63         glColor4fv(imtk_get_color(IMTK_TEXT_COLOR));
64         imtk_draw_string(x + 20, y + 15, label);
65 }
66
67 static void calc_button_size(const char *label, int *wret, int *hret)
68 {
69         int strsz = imtk_string_size(label);
70         if(wret) *wret = strsz + 40;
71         if(hret) *hret = 20;
72 }