Chesto 0.9
A declarative and element-based library for creating GUIs on homebrew'd consoles
Grid.cpp
1#include "Grid.hpp"
2#include "InputEvents.hpp"
3
4namespace Chesto {
5
14Grid::Grid(int columns, int width, int cellPadding, int rowPadding)
15 : columns(columns)
16 , width(width)
17 , cellPadding(cellPadding)
18 , rowPadding(rowPadding)
19{
20 this->width = width;
21 this->height = 0; // calculated on refresh()
22}
23
25{
26 if (elements.empty()) {
27 this->height = 0;
28 return;
29 }
30
31 // calculate cell width: (total width - padding between cells) / columns
32 int cellWidth = (this->width - (cellPadding * (columns - 1))) / columns;
33
34 int xPos = 0;
35 int yPos = 0;
36 int currentRowHeight = 0;
37 int col = 0;
38
39 for (auto& elem : elements) {
40 // actually position the element
41 elem->x = xPos;
42 elem->y = yPos;
43
44 // the tallest element in this row
45 if (elem->height > currentRowHeight) {
46 currentRowHeight = elem->height;
47 }
48
49 // advance column
50 col++;
51 xPos += cellWidth + cellPadding;
52
53 // do we need to start a new row?
54 if (col >= columns) {
55 col = 0;
56 xPos = 0;
57 yPos += currentRowHeight + rowPadding;
58 currentRowHeight = 0;
59 }
60 }
61
62 // final grid height
63 if (col > 0) {
64 yPos += currentRowHeight; // commit last row height
65 } else if (yPos > 0) {
66 yPos -= rowPadding;
67 }
68
69 this->height = yPos;
70}
71
73{
74 // This method lets the children elements handle their
75 // touch events, but manages grid-like cursor navigation
76 bool ret = false;
77
78 // normal event handling
79 ret |= Element::process(event);
80
81 if (elements.empty()) {
82 return ret;
83 }
84
85 if (touchMode) {
86 return ret;
87 }
88
89 // cursor logic from HBAS's AppList
90 // int origHighlighted = highlighted;
91
92 // start highlight if none
93 if (highlighted < 0 && !elements.empty()) {
94 highlighted = 0;
95 }
96
97 // ensure highlighted is in bounds
98 if (highlighted >= (int)elements.size()) {
99 highlighted = elements.size() - 1;
100 }
101
102 // TODO: fiinsh grid navigation logic
103 ret = true;
104
105 return ret;
106}
107
108} // namespace Chesto
std::vector< std::unique_ptr< Element, std::function< void(Element *)> > > elements
visible GUI child elements of this element
Definition: Element.hpp:59
virtual bool process(InputEvents *event)
process any input that is received for this element
Definition: Element.cpp:29
Grid(int columns, int width, int cellPadding=0, int rowPadding=0)
Definition: Grid.cpp:14
int highlighted
Cursor state.
Definition: Grid.hpp:23
bool process(InputEvents *event) override
process any input that is received for this element
Definition: Grid.cpp:72
void refresh()
Recalculate positions for all child elements.
Definition: Grid.cpp:24