imtk

view src/slider.c @ 14:df2bc9406561

added gradients
author John Tsiombikas <nuclear@siggraph.org>
date Tue, 19 Apr 2011 03:01:46 +0300
parents 10604ff95527
children c7a7ddbe7714
line source
1 #include <stdio.h>
2 #include <string.h>
3 #include <assert.h>
4 #include "imtk.h"
5 #include "state.h"
6 #include "draw.h"
8 #define SLIDER_SIZE 100
9 #define THUMB_WIDTH 10
10 #define THUMB_HEIGHT 20
12 static void draw_slider(int id, float pos, float min, float max, int x, int y, int over);
14 float imtk_slider(int id, float pos, float min, float max, int x, int y)
15 {
16 int mousex, mousey, thumb_x, thumb_y, over = 0;
17 float range = max - min;
19 assert(id >= 0);
21 imtk_get_mouse(&mousex, &mousey);
23 pos = (pos - min) / range;
24 if(pos < 0.0) pos = 0.0;
25 if(pos > 1.0) pos = 1.0;
27 thumb_x = x + SLIDER_SIZE * pos - THUMB_WIDTH / 2;
28 thumb_y = y - THUMB_HEIGHT / 2;
30 if(imtk_hit_test(thumb_x, thumb_y, THUMB_WIDTH, THUMB_HEIGHT)) {
31 imtk_set_hot(id);
32 over = 1;
33 }
35 if(imtk_button_state(IMTK_LEFT_BUTTON)) {
36 if(over && imtk_is_hot(id)) {
37 if(!imtk_is_active(id)) {
38 imtk_set_prev_mouse(mousex, mousey);
39 }
40 imtk_set_active(id);
41 }
42 } else {
43 if(imtk_is_active(id)) {
44 imtk_set_active(-1);
45 }
46 }
48 if(imtk_is_active(id)) {
49 int prevx;
50 float dx;
52 imtk_get_prev_mouse(&prevx, 0);
54 dx = (float)(mousex - prevx) / (float)SLIDER_SIZE;
55 pos += dx;
56 imtk_set_prev_mouse(mousex, mousey);
58 if(pos < 0.0) pos = 0.0;
59 if(pos > 1.0) pos = 1.0;
60 }
62 draw_slider(id, pos, min, max, x, y, over);
63 return pos * range + min;
64 }
67 static void draw_slider(int id, float pos, float min, float max, int x, int y, int over)
68 {
69 float range = max - min;
70 int thumb_x, thumb_y;
71 char buf[32];
72 float tcol[4], bcol[4];
73 unsigned int attr = 0;
75 thumb_x = x + SLIDER_SIZE * pos - THUMB_WIDTH / 2;
76 thumb_y = y - THUMB_HEIGHT / 2;
78 memcpy(tcol, imtk_get_color(IMTK_BOTTOM_COLOR), sizeof tcol);
79 memcpy(bcol, imtk_get_color(IMTK_TOP_COLOR), sizeof bcol);
81 /* draw trough */
82 imtk_draw_rect(x, y - 2, SLIDER_SIZE, 5, tcol, bcol);
83 imtk_draw_frame(x, y - 2, SLIDER_SIZE, 5, FRAME_INSET);
85 if(over) {
86 attr |= IMTK_FOCUS_BIT;
87 }
88 if(imtk_is_active(id)) {
89 attr |= IMTK_PRESS_BIT;
90 }
91 memcpy(tcol, imtk_get_color(IMTK_TOP_COLOR | attr), sizeof tcol);
92 memcpy(bcol, imtk_get_color(IMTK_BOTTOM_COLOR | attr), sizeof bcol);
94 /* draw handle */
95 imtk_draw_rect(thumb_x, thumb_y, THUMB_WIDTH, THUMB_HEIGHT, tcol, bcol);
96 imtk_draw_frame(thumb_x, thumb_y, THUMB_WIDTH, THUMB_HEIGHT, FRAME_OUTSET);
98 /* draw display */
99 sprintf(buf, "%.3f", pos * range + min);
100 glColor4fv(imtk_get_color(IMTK_TEXT_COLOR));
101 imtk_draw_string(x + SLIDER_SIZE + THUMB_WIDTH / 2 + 2, y + 4, buf);
102 }