summaryrefslogtreecommitdiff
path: root/src/gui/button.cpp
blob: 2b57772b7c6ad836f4dbe9e63676a4c6fb2375f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include "base.h"

void gui_button_draw_fn( void* ptr ) {
  GUI_BUTTON* btn = (GUI_BUTTON*)ptr;

  I32 x = gui_relx( btn );
  I32 y = gui_rely( btn );

  CLR col = gui_is_fg_window( btn )? ui_clr.border : ui_clr.border_inactive;
  gui_draw_frect( x, y, btn->w, btn->h, col );
  gui_draw_frect( x+1, y+1, btn->w-2, btn->h-2, ui_clr.bg_sec );

  I32 middle = x + btn->w/2;
  I32 middle_y = y + btn->h/2 - 7;

  gui_draw_str( middle, middle_y, ALIGN_C, FNT_JPN12, ui_clr.txt, btn->name );
}

void gui_button_input_fn( void* ptr ) {
  GUI_BUTTON* btn = (GUI_BUTTON*)ptr;

  I32 x = gui_relx( btn );
  I32 y = gui_rely( btn );

  U8 m1 = gui_mbutton_down( 0 );
  I32 mx, my;
  gui_cursor_pos( &mx, &my );

  U8 inbounds = mx >= x && mx <= x + btn->w && my >= y && my <= y + btn->h;

  if( !m1 ) {
    // button could be destroyed by callback
    U8 was_held = btn->held;
    btn->held = 0;
    if( inbounds && was_held )
      btn->cb( btn );

    return;
  }

  if( inbounds ) {
    btn->held = 1;
  }
}

GUI_BUTTON* gui_button( I32 x, I32 y, I32 w, I32 h, const char* title, GUI_CALLBACK cb ) {
  if( !gui_check_target() ) return 0;

  GUI_BUTTON* btn = new GUI_BUTTON;
  btn->x = x;
  btn->y = y;
  btn->xbound = btn->w = w;
  btn->ybound = btn->h = h;
  btn->cb = cb;
  btn->draw_fn = gui_button_draw_fn;
  btn->input_fn = gui_button_input_fn;

  btn->parent = _gui.cur_view;
  strcpy( btn->name, title );

  btn->extra = 0;
  btn->held = 0;

  gui_get_view()->children.push( btn );
  return btn;
}