1 | #include "Textbox.h"
|
---|
2 |
|
---|
3 | #include <iostream>
|
---|
4 |
|
---|
5 | using namespace std;
|
---|
6 |
|
---|
7 | Textbox::Textbox(int x, int y, int width, int height, ALLEGRO_FONT *font) :
|
---|
8 | GuiComponent(x, y, width, height, font)
|
---|
9 | {
|
---|
10 | str = "";
|
---|
11 | selected = false;
|
---|
12 | }
|
---|
13 |
|
---|
14 | Textbox::~Textbox(void)
|
---|
15 | {
|
---|
16 | }
|
---|
17 |
|
---|
18 | const string& Textbox::getStr() const
|
---|
19 | {
|
---|
20 | return str;
|
---|
21 | }
|
---|
22 |
|
---|
23 | void Textbox::clear(void)
|
---|
24 | {
|
---|
25 | str.clear();
|
---|
26 | }
|
---|
27 |
|
---|
28 | void Textbox::draw(ALLEGRO_DISPLAY *display)
|
---|
29 | {
|
---|
30 | al_set_target_bitmap(bitmap);
|
---|
31 | al_clear_to_color(al_map_rgb(0, 0, 0));
|
---|
32 |
|
---|
33 | int textWidth = al_get_text_width(font, str.c_str());
|
---|
34 | int fontHeight = al_get_font_line_height(font);
|
---|
35 |
|
---|
36 | int textPos = 1;
|
---|
37 | if(textWidth > this->width)
|
---|
38 | textPos = this->width-textWidth-3;
|
---|
39 |
|
---|
40 | al_draw_text(font, al_map_rgb(0, 255, 0), textPos, (this->height-fontHeight)/2, ALLEGRO_ALIGN_LEFT, str.c_str());
|
---|
41 | al_draw_rectangle(1, 1, this->width, this->height, al_map_rgb(0, 255, 0), 1);
|
---|
42 |
|
---|
43 | al_set_target_bitmap(al_get_backbuffer(display));
|
---|
44 | al_draw_bitmap(bitmap, x, y, 0);
|
---|
45 | }
|
---|
46 |
|
---|
47 | bool Textbox::handleEvent(ALLEGRO_EVENT& e)
|
---|
48 | {
|
---|
49 | ALLEGRO_KEYBOARD_STATE keys;
|
---|
50 | al_get_keyboard_state(&keys);
|
---|
51 |
|
---|
52 | if (e.type == ALLEGRO_EVENT_MOUSE_BUTTON_UP) {
|
---|
53 | if (e.mouse.button == 1) {
|
---|
54 | if (this->x < e.mouse.x && e.mouse.x < (this->x+this->width)
|
---|
55 | && this->y < e.mouse.y && e.mouse.y < (this->y+this->height))
|
---|
56 | {
|
---|
57 | selected = true;
|
---|
58 | return true;
|
---|
59 | }else
|
---|
60 | selected = false;
|
---|
61 | }
|
---|
62 |
|
---|
63 | return false;
|
---|
64 | }
|
---|
65 |
|
---|
66 | if (!selected)
|
---|
67 | return false;
|
---|
68 |
|
---|
69 | if (e.type == ALLEGRO_EVENT_KEY_DOWN) {
|
---|
70 | char newChar = 0;
|
---|
71 |
|
---|
72 | if (ALLEGRO_KEY_A <= e.keyboard.keycode && e.keyboard.keycode <= ALLEGRO_KEY_Z) {
|
---|
73 | newChar = 'a'+e.keyboard.keycode-ALLEGRO_KEY_A;
|
---|
74 | if (al_key_down(&keys, ALLEGRO_KEY_LSHIFT) || al_key_down(&keys, ALLEGRO_KEY_RSHIFT))
|
---|
75 | newChar -= 32;
|
---|
76 | }
|
---|
77 | else if (ALLEGRO_KEY_0 <= e.keyboard.keycode && e.keyboard.keycode <= ALLEGRO_KEY_9)
|
---|
78 | newChar = '0'+e.keyboard.keycode-ALLEGRO_KEY_0;
|
---|
79 | else if (e.keyboard.keycode = ALLEGRO_KEY_BACKSPACE && str.size() > 0)
|
---|
80 | str = str.substr(0, str.size()-1);
|
---|
81 |
|
---|
82 | if (newChar != 0) {
|
---|
83 | str.append(1, newChar);
|
---|
84 | return true;
|
---|
85 | }
|
---|
86 | }
|
---|
87 |
|
---|
88 | return false;
|
---|
89 | }
|
---|