]> git.tdb.fi Git - libs/gltk.git/blob - source/entry.cpp
6daa8ef1b1083c1361522d64bc3e845df228c2ad
[libs/gltk.git] / source / entry.cpp
1 #include <SDL/SDL_keysym.h>
2 #include <msp/gl/matrix.h>
3 #include <msp/gl/transform.h>
4 #include "entry.h"
5 #include "part.h"
6 #include "style.h"
7
8 using namespace std;
9
10 namespace Msp {
11 namespace GLtk {
12
13 Entry::Entry(const Resources &r, const string &t):
14         Widget(r),
15         text(t),
16         edit_pos(0),
17         active(false)
18 {
19 }
20
21 void Entry::set_text(const string &t)
22 {
23         text=t;
24         if(edit_pos>text.size())
25                 edit_pos=text.size();
26 }
27
28 void Entry::key_press(unsigned key, unsigned, wchar_t ch)
29 {
30         if(key==SDLK_LEFT)
31         {
32                 if(edit_pos>0)
33                         --edit_pos;
34         }
35         else if(key==SDLK_RIGHT)
36         {
37                 if(edit_pos<text.size())
38                         ++edit_pos;
39         }
40         else if(key==SDLK_BACKSPACE)
41         {
42                 if(edit_pos>0)
43                         text.erase(--edit_pos, 1);
44         }
45         else
46         {
47                 text+=ch;
48         }
49 }
50
51 void Entry::focus_in()
52 {
53         active=true;
54 }
55
56 void Entry::focus_out()
57 {
58         active=false;
59 }
60
61 void Entry::render_part(const Part &part) const
62 {
63         if(part.get_name()=="text")
64         {
65                 const GL::Font *const font=style->get_font();
66
67                 const float font_size=font->get_default_size();
68                 unsigned text_w=static_cast<unsigned>(font->get_string_width(text)*font_size);
69
70                 GL::push_matrix();
71
72                 part.get_alignment().apply(geom, text_w, static_cast<unsigned>(font->get_ascent()*font_size));
73                 GL::scale_uniform(font_size);
74
75                 const Color &color=style->get_font_color();
76                 glColor3f(color.r, color.g, color.b);
77                 if(active)
78                 {
79                         font->draw_string(text.substr(0, edit_pos));
80                         glBegin(GL_LINES);
81                         glVertex2f(0, 0);
82                         glVertex2f(0, 1);
83                         glEnd();
84                         font->draw_string(text.substr(edit_pos));
85                 }
86                 else
87                         font->draw_string(text);
88                 glColor3f(1, 1, 1);
89
90                 GL::pop_matrix();
91                 render_text(part, text);
92         }
93         else
94                 Widget::render_part(part);
95 }
96
97 } // namespace GLtk
98 } // namespace Msp