summaryrefslogtreecommitdiff
path: root/Servers/WindowServer/WSButton.cpp
blob: bf26ffb5523e47553155e1cc90a6c2621c7e7237 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <WindowServer/WSButton.h>
#include <WindowServer/WSEvent.h>
#include <WindowServer/WSWindowManager.h>
#include <SharedGraphics/Painter.h>
#include <SharedGraphics/StylePainter.h>
#include <SharedGraphics/CharacterBitmap.h>

WSButton::WSButton(WSWindowFrame& frame, Retained<CharacterBitmap>&& bitmap, Function<void(WSButton&)>&& on_click_handler)
    : on_click(move(on_click_handler))
    , m_frame(frame)
    , m_bitmap(move(bitmap))
{
}

WSButton::~WSButton()
{
}

void WSButton::paint(Painter& painter)
{
    PainterStateSaver saver(painter);
    painter.translate(relative_rect().location());
    StylePainter::paint_button(painter, rect(), ButtonStyle::Normal, m_pressed, m_hovered);
    auto x_location = rect().center();
    x_location.move_by(-(m_bitmap->width() / 2), -(m_bitmap->height() / 2));
    if (m_pressed)
        x_location.move_by(1, 1);
    painter.draw_bitmap(x_location, *m_bitmap, Color::Black);
}

void WSButton::on_mouse_event(const WSMouseEvent& event)
{
    auto& wm = WSWindowManager::the();

    if (event.type() == WSEvent::MouseDown && event.button() == MouseButton::Left) {
        m_pressed = true;
        wm.set_cursor_tracking_button(this);
        wm.invalidate(screen_rect());
        return;
    }

    if (event.type() == WSEvent::MouseUp && event.button() == MouseButton::Left) {
        if (wm.cursor_tracking_button() != this)
            return;
        wm.set_cursor_tracking_button(nullptr);
        bool old_pressed = m_pressed;
        m_pressed = false;
        if (rect().contains(event.position())) {
            if (on_click)
                on_click(*this);
        }
        if (old_pressed != m_pressed)
            wm.invalidate(screen_rect());
        return;
    }

    if (event.type() == WSEvent::MouseMove) {
        bool old_hovered = m_hovered;
        m_hovered = rect().contains(event.position());
        wm.set_hovered_button(m_hovered ? this : nullptr);
        if (old_hovered != m_hovered)
            wm.invalidate(screen_rect());
    }

    if (event.type() == WSEvent::MouseMove && event.buttons() & (unsigned)MouseButton::Left) {
        if (wm.cursor_tracking_button() != this)
            return;
        bool old_pressed = m_pressed;
        m_pressed = m_hovered;
        if (old_pressed != m_pressed)
            wm.invalidate(screen_rect());
    }
}

Rect WSButton::screen_rect() const
{
    return m_relative_rect.translated(m_frame.rect().location());
}