]> git.tdb.fi Git - libs/gltk.git/blob - source/widget.cpp
Adapt to DataFile changes
[libs/gltk.git] / source / widget.cpp
1 #include <msp/gl/matrix.h>
2 #include <msp/gl/transform.h>
3 #include "resources.h"
4 #include "widget.h"
5
6 #include <iostream>
7 using namespace std;
8
9 namespace Msp {
10 namespace GLtk {
11
12 void Widget::set_position(int x, int y)
13 {
14         geom.x=x;
15         geom.y=y;
16 }
17
18 void Widget::set_size(unsigned w, unsigned h)
19 {
20         geom.w=w;
21         geom.h=h;
22 }
23
24 void Widget::set_geometry(const Geometry &g)
25 {
26         geom=g;
27 }
28
29 void Widget::set_style(const string &s)
30 {
31         style_name=s;
32         update_style();
33 }
34
35 void Widget::render() const
36 {
37         if(!style)
38                 throw InvalidState("Attempt to render a widget without a style");
39
40         GL::push_matrix();
41         GL::translate(geom.x, geom.y, 0);
42         for(PartSeq::const_iterator i=style->get_parts().begin(); i!=style->get_parts().end(); ++i)
43                 render_part(*i);
44         GL::pop_matrix();
45 }
46
47 Widget::Widget(const Resources &r):
48         res(r),
49         style(0),
50         state(NORMAL)
51 { }
52
53 void Widget::update_style()
54 {
55         string sname=get_class();
56         if(!style_name.empty())
57         {
58                 sname+='-';
59                 sname+=style_name;
60         }
61         style=res.get<Style>(sname);
62 }
63
64 void Widget::render_part(const Part &part) const
65 {
66         render_graphic(part);
67 }
68
69 void Widget::render_graphic(const Part &part) const
70 {
71         GL::push_matrix();
72         part.render(geom, state);
73         GL::pop_matrix();
74 }
75
76 void Widget::render_text(const Part &part, const string &text) const
77 {
78         const GL::Font *const font=style->get_font();
79
80         const float font_size=font->get_default_size();
81         unsigned text_w=static_cast<unsigned>(font->get_string_width(text)*font_size);
82
83         GL::push_matrix();
84
85         part.get_alignment().apply(geom, text_w, static_cast<unsigned>(font->get_ascent()*font_size));
86         GL::scale_uniform(font_size);
87
88         const GL::Color &color=style->get_font_color();
89         glColor3f(color.r, color.g, color.b);
90         font->draw_string(text);
91         glColor3f(1, 1, 1);
92
93         GL::pop_matrix();
94 }
95
96
97 Widget::Loader::Loader(Widget &w):
98         wdg(w)
99 {
100         add("position", &Loader::position);
101         add("size",     &Loader::size);
102         add("style",    &Loader::style);
103 }
104
105 void Widget::Loader::position(int x, int y)
106 {
107         wdg.set_position(x, y);
108 }
109
110 void Widget::Loader::size(unsigned w, unsigned h)
111 {
112         wdg.set_size(w, h);
113 }
114
115 void Widget::Loader::style(const string &s)
116 {
117         wdg.set_style(s);
118 }
119
120 } // namespace GLtk
121 } // namespace Msp