Root/src/iconbutton.cpp

1#include "iconbutton.h"
2
3#include "font.h"
4#include "gmenu2x.h"
5#include "surface.h"
6
7using namespace std;
8
9
10IconButton::IconButton(
11        GMenu2X *gmenu2x, Touchscreen &ts,
12        const string &icon, const string &label)
13    : gmenu2x(gmenu2x)
14    , ts(ts)
15    , icon(icon)
16    , label(label)
17    , action([] {})
18    , rect({ 0, 0, 0, 0 })
19{
20    iconSurface = gmenu2x->sc[icon];
21    recalcRects();
22}
23
24void IconButton::setAction(function_t action) {
25    this->action = action;
26}
27
28void IconButton::setPosition(int x, int y) {
29    if (rect.x != x || rect.y != y) {
30        rect.x = x;
31        rect.y = y;
32        recalcRects();
33    }
34}
35
36void IconButton::recalcRects() {
37    Uint16 h = 0, w = 0;
38    if (iconSurface) {
39        w += iconSurface->width();
40        h += iconSurface->height();
41    }
42    iconRect = { rect.x, rect.y, w, h };
43
44    if (!label.empty()) {
45        Uint16 margin = iconSurface ? 2 : 0;
46        labelRect = {
47            static_cast<Sint16>(iconRect.x + iconRect.w + margin),
48            static_cast<Sint16>(rect.y + h / 2),
49            static_cast<Uint16>(gmenu2x->font->getTextWidth(label)),
50            static_cast<Uint16>(gmenu2x->font->getHeight())
51        };
52        w += margin + labelRect.w;
53    }
54
55    rect.w = w;
56    rect.h = h;
57}
58
59bool IconButton::handleTS() {
60    if (ts.released() && ts.inRect(rect)) {
61        ts.setHandled();
62        action();
63        return true;
64    }
65    return false;
66}
67
68void IconButton::paint() {
69    if (iconSurface) {
70        iconSurface->blit(gmenu2x->s, iconRect);
71    }
72    if (!label.empty()) {
73        gmenu2x->s->write(gmenu2x->font, label, labelRect.x, labelRect.y,
74                Font::HAlignLeft, Font::VAlignMiddle);
75    }
76}
77

Archive Download this file



interactive