FreeRDP
Loading...
Searching...
No Matches
SDL2/dialogs/sdl_buttons.cpp
1#include <cassert>
2#include <algorithm>
3
4#include <winpr/cast.h>
5
6#include "sdl_buttons.hpp"
7
8static const Uint32 hpadding = 10;
9
10SdlButtonList::~SdlButtonList() = default;
11
12bool SdlButtonList::populate(SDL_Renderer* renderer, const std::vector<std::string>& labels,
13 const std::vector<int>& ids, Sint32 total_width, Sint32 offsetY,
14 Sint32 width, Sint32 height)
15{
16 assert(renderer);
17 assert(width >= 0);
18 assert(height >= 0);
19 assert(labels.size() == ids.size());
20
21 _list.clear();
22 size_t button_width =
23 ids.size() * (WINPR_ASSERTING_INT_CAST(uint32_t, width) + hpadding) + hpadding;
24 size_t offsetX =
25 WINPR_ASSERTING_INT_CAST(uint32_t, total_width) -
26 std::min<size_t>(WINPR_ASSERTING_INT_CAST(uint32_t, total_width), button_width);
27 for (size_t x = 0; x < ids.size(); x++)
28 {
29 const size_t curOffsetX = offsetX + x * (static_cast<size_t>(width) + hpadding);
30 const SDL_Rect rect = { static_cast<int>(curOffsetX), offsetY, width, height };
31 _list.emplace_back(renderer, labels[x], ids[x], rect);
32 }
33 return true;
34}
35
36SdlButton* SdlButtonList::get_selected(const SDL_MouseButtonEvent& button)
37{
38 const Sint32 x = button.x;
39 const Sint32 y = button.y;
40
41 return get_selected(x, y);
42}
43
44SdlButton* SdlButtonList::get_selected(Sint32 x, Sint32 y)
45{
46 for (auto& btn : _list)
47 {
48 auto r = btn.rect();
49 if ((x >= r.x) && (x <= r.x + r.w) && (y >= r.y) && (y <= r.y + r.h))
50 return &btn;
51 }
52 return nullptr;
53}
54
55bool SdlButtonList::set_highlight_next(bool reset)
56{
57 if (reset)
58 _highlighted = nullptr;
59 else
60 {
61 auto next = _highlight_index++;
62 _highlight_index %= _list.size();
63 auto& element = _list[next];
64 _highlighted = &element;
65 }
66 return true;
67}
68
69bool SdlButtonList::set_highlight(size_t index)
70{
71 if (index >= _list.size())
72 {
73 _highlighted = nullptr;
74 return false;
75 }
76 auto& element = _list[index];
77 _highlighted = &element;
78 _highlight_index = ++index % _list.size();
79 return true;
80}
81
82bool SdlButtonList::set_mouseover(Sint32 x, Sint32 y)
83{
84 _mouseover = get_selected(x, y);
85 return _mouseover != nullptr;
86}
87
88void SdlButtonList::clear()
89{
90 _list.clear();
91 _mouseover = nullptr;
92 _highlighted = nullptr;
93 _highlight_index = 0;
94}
95
96bool SdlButtonList::update(SDL_Renderer* renderer)
97{
98 assert(renderer);
99
100 for (auto& btn : _list)
101 {
102 if (!btn.update(renderer))
103 return false;
104 }
105
106 if (_highlighted)
107 _highlighted->highlight(renderer);
108
109 if (_mouseover)
110 _mouseover->mouseover(renderer);
111 return true;
112}