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