1 module unde.guitk.lib;
2 
3 import derelict.sdl2.sdl;
4 import derelict.sdl2.ttf;
5 import derelict.sdl2.image;
6 
7 import unde.global_state;
8 
9 interface UIEntry
10 {
11     @property SDL_Rect rect();
12     void on_draw(GlobalState gs);
13     void process_event(GlobalState gs, SDL_Event event);
14     @property UIPage page();
15     @property ref bool focus();
16     void on_set_focus(GlobalState gs);
17     void on_unset_focus(GlobalState gs);
18     void set_keybar(GlobalState gs);
19 
20     final void unset_focus(GlobalState gs)
21     {
22         on_unset_focus(gs);
23         focus = false;
24         page.focused = null;
25     }
26 
27     final void set_focus(GlobalState gs)
28     {
29         if (page.focused)
30             page.focused.unset_focus(gs);
31         focus = true;
32         page.focused = this;
33         on_set_focus(gs);
34     }
35 }
36 
37 class UIPage
38 {
39     bool show;
40     private UIEntry[] entries;
41     UIEntry focused;
42 
43     void on_draw(GlobalState gs)
44     {
45         foreach (entry; entries)
46         {
47             entry.on_draw(gs);
48         }
49     }
50 
51     void add_entry(GlobalState gs, UIEntry entry)
52     {
53         entries ~= entry;
54         if (!focused) entry.set_focus(gs);
55     }
56 
57     void process_event(GlobalState gs, SDL_Event event)
58     {
59         foreach (entry; entries)
60         {
61             switch(event.type)
62             {
63                 case SDL_MOUSEMOTION:
64                     goto case;
65                 case SDL_MOUSEBUTTONDOWN:
66                     goto case;
67                 case SDL_MOUSEBUTTONUP:
68                     goto case;
69                 case SDL_MOUSEWHEEL:
70                     if (gs.mouse_screen_x > entry.rect.x &&
71                             gs.mouse_screen_x < entry.rect.x + entry.rect.w &&
72                             gs.mouse_screen_y > entry.rect.y &&
73                             gs.mouse_screen_y < entry.rect.y + entry.rect.h)
74                         entry.process_event(gs, event);
75                     break;
76                 case SDL_TEXTINPUT:
77                     if (entry.focus)
78                     {
79                         entry.process_event(gs, event);
80                     }
81                     break;
82                 default:
83                     entry.process_event(gs, event);
84             }
85         }
86     }
87 
88     void set_keybar(GlobalState gs)
89     {
90         if (focused)
91             focused.set_keybar(gs);
92     }
93 }
94