4 * Created on: Aug 8, 2012
8 #ifndef GRAPHICS_MENU_H_
9 #define GRAPHICS_MENU_H_
12 #include "../geometry/operators.h"
13 #include "../geometry/Point.h"
14 #include "../geometry/Vector.h"
23 // TODO: disabled entries + alternate font for those
24 // TODO: sprite for the cursor
25 // TODO: animation when top row changes
30 explicit Menu(const Font *font = NULL, int charsPerEntry = 16, int rows = 1, int rowGap = 0, int cols = 1, int colGap = 0);
35 int ColWidth() const { return font->CharWidth() * charsPerEntry; }
36 int RowHeight() const { return font->CharHeight() + rowGap; }
38 T &Selected() { return entries[selected].value; }
39 const T &Selected() const { return entries[selected].value; }
40 const char *SelectedTitle() const { return entries[selected].title; }
46 void SelectIndex(int index);
48 void Add(const char *title, const T &value, const Sprite *icon = 0) { entries.push_back(Entry(title, value, icon)); }
49 void Reserve(int n) { entries.reserve(n); }
51 void Draw(SDL_Surface *dest, geometry::Point<int> position) const;
54 int GetRow(int index) const { return index / cols; }
55 int GetCol(int index) const { return index % cols; }
59 Entry(const char *title, const T &value, const Sprite *icon = 0)
60 : title(title), icon(icon), value(value) { }
66 std::vector<Entry> entries;
79 Menu<T>::Menu(const Font *font, int charsPerEntry, int rows, int rowGap, int cols, int colGap)
81 , charsPerEntry(charsPerEntry)
93 int Menu<T>::Width() const {
94 return cols * ColWidth() + (cols - 1) * colGap;
98 int Menu<T>::Height() const {
99 return rows * font->CharHeight() + (rows - 1) * rowGap;
104 void Menu<T>::NextItem() {
105 SelectIndex(selected + 1);
109 void Menu<T>::PreviousItem() {
110 SelectIndex(selected - 1);
114 void Menu<T>::NextRow() {
115 SelectIndex(selected + cols);
119 void Menu<T>::PreviousRow() {
120 SelectIndex(selected - cols);
124 void Menu<T>::SelectIndex(int index) {
125 if (index < 0 || entries.size() < index) return;
127 if (GetRow(selected) - rows > topRow) {
128 topRow = GetRow(selected) - rows;
129 } else if (GetRow(selected) < topRow) {
130 topRow = GetRow(selected);
136 void Menu<T>::Draw(SDL_Surface *dest, geometry::Point<int> position) const {
137 int start(topRow * cols);
138 int slots((topRow + rows) * cols);
139 int items(entries.size() - start);
140 int end(items < slots ? items : slots);
141 for (int i(0), count(end - start); i < count; ++i) {
142 geometry::Vector<int> offset((i % cols) * (ColWidth() + colGap), (i / cols) * RowHeight());
143 font->DrawString(entries[start + i].title, dest, position + offset, charsPerEntry);
149 #endif /* GRAPHICS_MENU_H_ */