TinyMaterialDesign
Loading...
Searching...
No Matches
Keyboard.h
Go to the documentation of this file.
1#pragma once
2#include <cctype>
3#include <functional>
4
5#include "TinyGPU/Color/RGB565.h"
6#include "TinyGPU/Color/RGB666.h"
7#include "TinyGPU/Color/RGB888.h"
8#include "TinyMaterialDesign/Core/TextInputTarget.h"
9#include "TinyMaterialDesign/Core/Widget.h"
10
11namespace tinymd {
12
13/**
14 * @brief On-screen QWERTY keyboard that drives one text input at a time.
15 *
16 * A single Keyboard instance can serve any number of fields, TextField and
17 * TextArea interchangeably (see Core/TextInputTarget.h) - call manage(field)
18 * once per field to wire it up:
19 *
20 * Keyboard<RGB565> keyboard(Bounds(0, 420, 340, 190));
21 * keyboard.manage(nameField); // TextField
22 * keyboard.manage(notesField); // TextArea
23 *
24 * manage() makes tapping a field show this keyboard targeted at it (and
25 * blur whichever field it was previously targeting). Add the keyboard to
26 * Screen *after* every field it manages, so it draws (and hit-tests) on top
27 * of them while shown.
28 *
29 * Layout: a numbers row (which also holds the "123"/"ABC" key), three rows
30 * that switch between QWERTY letters and a page of common symbols
31 * (!@#$%^&*() / -_=+[]{}\\ / ;:'",./), and a control row (Shift / Space /
32 * Enter / Backspace / Done). Shift is a toggle (caps-lock style, not "one
33 * letter then auto-revert") and has no effect on the symbols page. Enter and
34 * Done are deliberately separate keys: Enter always inserts a literal '\n'
35 * and moves to the next line, regardless of field type; Done always means
36 * "finished editing" and closes the keyboard (see TextInputTarget::
37 * handleEnter(), which every field implements to return true) - so on a
38 * TextArea, Enter adds a line without leaving the keyboard, and Done closes
39 * it whenever you're actually done, mid-line or not. There is only this one
40 * symbols page (no further "more symbols" page) - a deliberate cut to keep
41 * this a two-layer keyboard rather than a deeper multi-page one.
42 */
43template <typename RGB_T = TINYMD_DEFAULT_RGB_T>
44class Keyboard : public Widget<RGB_T> {
45 public:
46 Keyboard() = default;
47 explicit Keyboard(Bounds bounds) {
48 this->bounds = bounds;
49 this->visible = false;
50 }
51
52 /// Wires `field` so tapping it shows this keyboard targeted at it. `Field`
53 /// must implement TextInputTarget and expose a public
54 /// `std::function<void()> onFocus` - true of both TextField and TextArea.
55 template <typename Field>
56 void manage(Field& field) {
57 field.onFocus = [this, &field]() {
58 if (target_ != nullptr && target_ != &field) target_->blur();
59 target_ = &field;
60 // numeric keypad for number fields, letters otherwise
61 if (field.inputType() == InputType::kNumber) {
62 mode_ = Mode::kNumeric;
63 } else if (mode_ == Mode::kNumeric) {
64 mode_ = Mode::kLetters;
65 }
66 this->visible = true;
67 };
68 }
69
70 void hide() { this->visible = false; }
71
72 void draw(tinygpu::ISurface<RGB_T>& target) override {
73 target.fillRect(toPx(this->bounds.x), toPx(this->bounds.y), toPx(this->bounds.w),
74 toPx(this->bounds.h), this->theme().colors.surfaceVariant);
75
76 forEachKey([&](const Key& key, const Bounds& rect) {
77 const bool highlighted = key.action == Action::kShift && shift_;
78 const RGB_T keyColor = highlighted ? this->theme().colors.secondaryContainer : this->theme().colors.surface;
79 target.fillRoundRect(toPx(rect.x + 2), toPx(rect.y + 2), toPx(rect.w - 4), toPx(rect.h - 4),
80 toPx(this->theme().shape.small), keyColor);
81
82 char labelBuffer[2] = {0, 0};
83 const char* labelText = key.label;
84 if (key.action == Action::kChar) {
85 labelBuffer[0] = shift_ ? static_cast<char>(std::toupper(key.ch)) : key.ch;
86 labelText = labelBuffer;
87 } else if (key.action == Action::kToggleSymbols) {
88 labelText = (mode_ == Mode::kLetters) ? "123" : "ABC";
89 }
90
91 const size_t textWidth = this->theme().typography.body->measureTextWidth(labelText);
92 const int32_t textX = rect.centerX() - static_cast<int32_t>(textWidth) / 2;
93 const int32_t textY = rect.centerY() - static_cast<int32_t>(this->theme().typography.body->getHeight(1)) / 2;
94 this->theme().typography.body->drawText(target, static_cast<int16_t>(textX),
95 static_cast<int16_t>(textY), labelText,
96 this->theme().colors.onSurface, keyColor, false);
97 return false;
98 });
99 }
100
101 bool onGesture(const tinygpu::GestureEvent& event) override {
102 if (!isTapGesture(event.type)) return false;
103 const Key* hit = nullptr;
104 forEachKey([&](const Key& key, const Bounds& rect) {
105 if (rect.contains(event.point.x, event.point.y)) {
106 hit = &key;
107 return true; // stop iterating
108 }
109 return false;
110 });
111 if (hit == nullptr) return true; // swallow the tap either way
112 handleKey(*hit);
113 return true;
114 }
115
116 private:
117 enum class Action { kChar, kShift, kBackspace, kSpace, kNewline, kEnter, kToggleSymbols };
118 enum class Mode { kLetters, kSymbols, kNumeric };
119
120 struct Key {
121 Action action;
122 char ch;
123 const char* label;
124 float weight;
125 };
126
127 // Numbers row, plus a "123"/"ABC" key (prepended) that swaps rows 1-3
128 // between letters and symbols - the numbers row itself stays the same in
129 // both modes.
130 static constexpr Key kRow0[] = {
131 {Action::kToggleSymbols, 0, "123", 1.5f},
132 {Action::kChar, '1', "1", 1}, {Action::kChar, '2', "2", 1}, {Action::kChar, '3', "3", 1},
133 {Action::kChar, '4', "4", 1}, {Action::kChar, '5', "5", 1}, {Action::kChar, '6', "6", 1},
134 {Action::kChar, '7', "7", 1}, {Action::kChar, '8', "8", 1}, {Action::kChar, '9', "9", 1},
135 {Action::kChar, '0', "0", 1},
136 };
137 static constexpr Key kRow1[] = {
138 {Action::kChar, 'q', "q", 1}, {Action::kChar, 'w', "w", 1}, {Action::kChar, 'e', "e", 1},
139 {Action::kChar, 'r', "r", 1}, {Action::kChar, 't', "t", 1}, {Action::kChar, 'y', "y", 1},
140 {Action::kChar, 'u', "u", 1}, {Action::kChar, 'i', "i", 1}, {Action::kChar, 'o', "o", 1},
141 {Action::kChar, 'p', "p", 1},
142 };
143 static constexpr Key kRow2[] = {
144 {Action::kChar, 'a', "a", 1}, {Action::kChar, 's', "s", 1}, {Action::kChar, 'd', "d", 1},
145 {Action::kChar, 'f', "f", 1}, {Action::kChar, 'g', "g", 1}, {Action::kChar, 'h', "h", 1},
146 {Action::kChar, 'j', "j", 1}, {Action::kChar, 'k', "k", 1}, {Action::kChar, 'l', "l", 1},
147 };
148 static constexpr Key kRow3[] = {
149 {Action::kChar, 'z', "z", 1}, {Action::kChar, 'x', "x", 1}, {Action::kChar, 'c', "c", 1},
150 {Action::kChar, 'v', "v", 1}, {Action::kChar, 'b', "b", 1}, {Action::kChar, 'n', "n", 1},
151 {Action::kChar, 'm', "m", 1},
152 };
153 // Symbols page, same shape (10/9/7 keys) as the letter rows it replaces.
154 static constexpr Key kRow1Symbols[] = {
155 {Action::kChar, '!', "!", 1}, {Action::kChar, '@', "@", 1}, {Action::kChar, '#', "#", 1},
156 {Action::kChar, '$', "$", 1}, {Action::kChar, '%', "%", 1}, {Action::kChar, '^', "^", 1},
157 {Action::kChar, '&', "&", 1}, {Action::kChar, '*', "*", 1}, {Action::kChar, '(', "(", 1},
158 {Action::kChar, ')', ")", 1},
159 };
160 static constexpr Key kRow2Symbols[] = {
161 {Action::kChar, '-', "-", 1}, {Action::kChar, '_', "_", 1}, {Action::kChar, '=', "=", 1},
162 {Action::kChar, '+', "+", 1}, {Action::kChar, '[', "[", 1}, {Action::kChar, ']', "]", 1},
163 {Action::kChar, '{', "{", 1}, {Action::kChar, '}', "}", 1}, {Action::kChar, '\\', "\\", 1},
164 };
165 static constexpr Key kRow3Symbols[] = {
166 {Action::kChar, ';', ";", 1}, {Action::kChar, ':', ":", 1}, {Action::kChar, '\'', "'", 1},
167 {Action::kChar, '"', "\"", 1}, {Action::kChar, ',', ",", 1}, {Action::kChar, '.', ".", 1},
168 {Action::kChar, '/', "/", 1},
169 };
170 // Numeric keypad (number fields): 7-8-9 / 4-5-6 / 1-2-3 / . 0 - and a
171 // control row; "ABC" switches to the letters.
172 static constexpr Key kNum0[] = {
173 {Action::kChar, '7', "7", 1}, {Action::kChar, '8', "8", 1}, {Action::kChar, '9', "9", 1}};
174 static constexpr Key kNum1[] = {
175 {Action::kChar, '4', "4", 1}, {Action::kChar, '5', "5", 1}, {Action::kChar, '6', "6", 1}};
176 static constexpr Key kNum2[] = {
177 {Action::kChar, '1', "1", 1}, {Action::kChar, '2', "2", 1}, {Action::kChar, '3', "3", 1}};
178 static constexpr Key kNum3[] = {
179 {Action::kChar, '.', ".", 1}, {Action::kChar, '0', "0", 1}, {Action::kChar, '-', "-", 1}};
180 static constexpr Key kNum4[] = {
181 {Action::kToggleSymbols, 0, "ABC", 1}, {Action::kBackspace, 0, "<-", 1}, {Action::kEnter, 0, "Done", 1}};
182 static constexpr Key kRow4[] = {
183 {Action::kShift, 0, "Shift", 1.5f},
184 {Action::kSpace, 0, "", 3.5f},
185 {Action::kNewline, 0, "Enter", 1.5f},
186 {Action::kBackspace, 0, "<-", 1.5f},
187 {Action::kEnter, 0, "Done", 1.5f},
188 };
189
190 TextInputTarget* target_ = nullptr;
191 bool shift_ = false;
192 Mode mode_ = Mode::kLetters;
193
194 /// Walks every key, computing its Bounds from its row's weighted layout,
195 /// invoking `visitor(key, rect)`. Used by both draw() and onGesture() so
196 /// the layout math lives in exactly one place. `visitor` returns true to
197 /// stop iterating early (hit-testing); draw() always returns false.
198 /// Rows 1-3 swap between letters and symbols depending on mode_; row 0
199 /// (numbers + the mode toggle) and row 4 (controls) are the same either way.
200 template <typename Visitor>
201 void forEachKey(Visitor visitor) const {
202 struct Row {
203 const Key* keys;
204 size_t count;
205 };
206 const bool symbols = mode_ == Mode::kSymbols;
207 const Row numeric[] = {
208 {kNum0, 3}, {kNum1, 3}, {kNum2, 3}, {kNum3, 3}, {kNum4, 3},
209 };
210 const Row letters[] = {
211 {kRow0, sizeof(kRow0) / sizeof(kRow0[0])},
212 symbols ? Row{kRow1Symbols, sizeof(kRow1Symbols) / sizeof(kRow1Symbols[0])}
213 : Row{kRow1, sizeof(kRow1) / sizeof(kRow1[0])},
214 symbols ? Row{kRow2Symbols, sizeof(kRow2Symbols) / sizeof(kRow2Symbols[0])}
215 : Row{kRow2, sizeof(kRow2) / sizeof(kRow2[0])},
216 symbols ? Row{kRow3Symbols, sizeof(kRow3Symbols) / sizeof(kRow3Symbols[0])}
217 : Row{kRow3, sizeof(kRow3) / sizeof(kRow3[0])},
218 {kRow4, sizeof(kRow4) / sizeof(kRow4[0])},
219 };
220 const Row* rows = mode_ == Mode::kNumeric ? numeric : letters;
221 constexpr size_t kRowCount = sizeof(letters) / sizeof(letters[0]);
222 const int32_t rowHeight = this->bounds.h / static_cast<int32_t>(kRowCount);
223
224 for (size_t r = 0; r < kRowCount; ++r) {
225 float totalWeight = 0.0f;
226 for (size_t i = 0; i < rows[r].count; ++i) totalWeight += rows[r].keys[i].weight;
227
228 const int32_t rowY = this->bounds.y + static_cast<int32_t>(r) * rowHeight;
229 float cursor = 0.0f;
230 for (size_t i = 0; i < rows[r].count; ++i) {
231 const Key& key = rows[r].keys[i];
232 const int32_t x0 = this->bounds.x + static_cast<int32_t>(cursor / totalWeight * this->bounds.w);
233 cursor += key.weight;
234 const int32_t x1 = this->bounds.x + static_cast<int32_t>(cursor / totalWeight * this->bounds.w);
235 const Bounds rect(x0, rowY, x1 - x0, rowHeight);
236 if (visitor(key, rect)) return;
237 }
238 }
239 }
240
241 void handleKey(const Key& key) {
242 switch (key.action) {
243 case Action::kChar:
244 if (target_ != nullptr) {
245 target_->insertChar(shift_ ? static_cast<char>(std::toupper(key.ch)) : key.ch);
246 }
247 break;
248 case Action::kShift:
249 shift_ = !shift_;
250 break;
251 case Action::kBackspace:
252 if (target_ != nullptr) target_->backspace();
253 break;
254 case Action::kSpace:
255 if (target_ != nullptr) target_->insertChar(' ');
256 break;
257 case Action::kNewline:
258 // Unlike Done/handleEnter(), this always inserts a literal '\n' and
259 // moves to the next line, regardless of the target's field type.
260 if (target_ != nullptr) target_->insertChar('\n');
261 break;
262 case Action::kEnter:
263 // Both TextField and TextArea return true from handleEnter() -
264 // Done always finishes editing and closes the keyboard.
265 if (target_ == nullptr || target_->handleEnter()) this->visible = false;
266 break;
267 case Action::kToggleSymbols:
268 // letters <-> symbols; from the numeric keypad back to the letters
269 mode_ = (mode_ == Mode::kLetters) ? Mode::kSymbols : Mode::kLetters;
270 break;
271 }
272 }
273};
274
278
279} // namespace tinymd
On-screen QWERTY keyboard that drives one text input at a time.
Definition: Keyboard.h:44
bool onGesture(const tinygpu::GestureEvent &event) override
Handles one gesture event. Returns true if this widget consumed it.
Definition: Keyboard.h:101
void manage(Field &field)
Definition: Keyboard.h:56
Keyboard(Bounds bounds)
Definition: Keyboard.h:47
Keyboard()=default
void draw(tinygpu::ISurface< RGB_T > &target) override
Definition: Keyboard.h:72
void hide()
Definition: Keyboard.h:70
Definition: TextInputTarget.h:22
virtual bool handleEnter()=0
virtual void blur()=0
virtual void insertChar(char c)=0
virtual void backspace()=0
Base class every TinyMaterialDesign widget derives from.
Definition: Widget.h:58
Definition: AnchorLayout.h:4
InputType
Minimal interface a Keyboard drives.
Definition: TextInputTarget.h:20
Axis-aligned pixel rectangle used for widget bounds and hit-testing.
Definition: Bounds.h:21
int32_t centerY() const
Definition: Bounds.h:33