]> git.tdb.fi Git - libs/gltk.git/blob - source/entry.cpp
Add Text class with multiline support
[libs/gltk.git] / source / entry.cpp
1 /* $Id$
2
3 This file is part of libmspgltk
4 Copyright © 2007  Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #include <msp/gl/matrix.h>
9 #include <msp/gl/texture.h>
10 #include <msp/gl/transform.h>
11 #include <msp/input/keys.h>
12 #include "entry.h"
13 #include "graphic.h"
14 #include "part.h"
15 #include "style.h"
16
17 using namespace std;
18
19 namespace Msp {
20 namespace GLtk {
21
22 Entry::Entry(const Resources &r, const string &t):
23         Widget(r),
24         text(style),
25         edit_pos(0)
26 {
27         update_style();
28         set_text(t);
29 }
30
31 void Entry::set_text(const string &t)
32 {
33         text=t;
34         edit_pos=text.size();
35 }
36
37 void Entry::key_press(unsigned key, unsigned, wchar_t ch)
38 {
39         if(key==Input::KEY_LEFT)
40         {
41                 if(edit_pos>0)
42                         --edit_pos;
43         }
44         else if(key==Input::KEY_RIGHT)
45         {
46                 if(edit_pos<text.size())
47                         ++edit_pos;
48         }
49         else if(key==Input::KEY_BACKSPACE)
50         {
51                 if(edit_pos>0)
52                         text.erase(--edit_pos, 1);
53         }
54         else if(key==Input::KEY_ENTER)
55                 signal_enter.emit();
56         else if(ch>=' ')
57         {
58                 text.insert(edit_pos, Codecs::encode<Codecs::Utf8>(Codecs::ustring(1, ch)));
59                 ++edit_pos;
60         }
61 }
62
63 void Entry::render_special(const Part &part) const
64 {
65         if(part.get_name()=="text")
66                 text.render(part, geom);
67         else if(part.get_name()=="cursor")
68         {
69                 if(!part.get_graphic(state))
70                         return;
71
72                 const GL::Font *const font=style->get_font();
73                 const float font_size=font->get_default_size();
74
75                 Geometry rgeom=part.get_geometry();
76                 rgeom.x=static_cast<unsigned>(font->get_string_width(text.get().substr(0, edit_pos))*font_size);
77                 rgeom.w=static_cast<unsigned>(font->get_string_width(text.get())*font_size);
78                 part.get_alignment().apply(rgeom, geom, part.get_margin());
79
80                 GL::push_matrix();
81                 GL::translate(rgeom.x, rgeom.y, 0);
82                 part.get_graphic(state)->render(part.get_geometry().w, rgeom.h);
83                 GL::pop_matrix();
84         }
85 }
86
87
88 Entry::Loader::Loader(Entry &ent):
89         Widget::Loader(ent)
90 { }
91
92 } // namespace GLtk
93 } // namespace Msp