TinyMaterialDesign
Loading...
Searching...
No Matches
App.h
Go to the documentation of this file.
1#pragma once
2#include "TinyGPU/Boards/LCDBoards.h"
3#include "TinyGPU/Drivers/DeviceOutput.h"
4#include "TinyGPU/IO/BMPExporter.h"
5#include "TinyGPU/Input/GestureDetector.h"
6#include "TinyGPU/Surface/Surface.h"
8#include "TinyMaterialDesign/Core/Screen.h"
9#include "TinyMaterialDesign/Theme/MaterialTheme.h"
10
11#include <stdio.h>
12#if !(defined(ARDUINO) || __has_include(<Print.h>))
13// Plain desktop build: TinyGPU's byte-output interface stands in for Arduino's Print.
14#include "TinyGPU/IO/AVIWriter.h"
15#endif
16
17namespace tinymd {
18
19#if !(defined(ARDUINO) || __has_include(<Print.h>))
21#endif
22
23
24/**
25 * @brief Bundles the surface + display + gesture routing + Screen
26 * boilerplate that every single-widget example under examples/controls and
27 * examples/layouts otherwise hand-rolls identically, down to a constructor
28 * plus two calls: begin() and update().
29 *
30 * Without `App`, every one of those sketches repeats the same ~15 lines:
31 *
32 * Surface<RGB565> surface(kWidth, kHeight, FontRGB565);
33 * DeviceOutput<RGB565> display(board.display());
34 * GestureDetector gestures;
35 * Screen<RGB565> screen(theme);
36 * // ...then in setup(): display.begin(); surface.begin();
37 * // gestures.onGesture = ...; gestures.isDraggable = ...;
38 * // ...then in loop(): gestures.update(*board.touch()); screen.update(...);
39 * // if (screen.isDirty()) { screen.draw(surface); display.writeData(surface); }
40 *
41 * `App` is exactly that, reduced to:
42 *
43 * LCDBoardGuitionESP32_LVGL_2_4Display board;
44 * App<RGB565> app(board);
45 * Button<RGB565> myButton(Bounds(...), "Tap me");
46 *
47 * void setup() {
48 * Serial.begin(115200);
49 * app.begin();
50 * myButton.onClick = []() { ... };
51 * app.screen().addWidget(myButton);
52 * }
53 *
54 * void loop() {
55 * app.update();
56 * }
57 *
58 * The board itself is left to the sketch, not `App` - board *types* differ
59 * per target (a desktop board takes width/height in its constructor, most
60 * real hardware boards take none, and a board with nonstandard wiring
61 * takes pin numbers) enough that there's no one constructor `App` could
62 * call on your behalf - `TinyMaterialDesignConfig.h`'s `DefaultBoard` is a
63 * ready-made object of whichever concrete type fits the current platform,
64 * for exactly this reason (see its own doc comment); pass a different
65 * `LCDBoard` instead for anything else. Whatever you pass must already be
66 * fully constructed and must outlive this `App` - the same
67 * non-owning-reference convention every other TinyMaterialDesign class
68 * uses. Width/height are read from `board.width()`/`board.height()`, so
69 * they don't need to be passed again.
70 *
71 * Pinned to `LCDBoard`'s own RGB565-only `display()` (see
72 * `TinyGPU/Boards/LCDBoardsCommon.h`'s class comment) - `RGB_T` is
73 * templated for consistency with every other class in this library, but in
74 * practice only `RGB565` compiles today, the same constraint every
75 * hand-rolled example already has.
76 *
77 * begin() falls back to Screen::drawDirect()'s small-per-widget-buffer
78 * rendering automatically if the full-screen framebuffer `surface()` needs
79 * can't be allocated (see that method's own doc comment for why this can
80 * happen even with plenty of free heap) - a board without enough RAM for a
81 * full framebuffer draws exactly the same widgets through the same
82 * `screen()` API, just via a smaller reused buffer. See usesDirectRender().
83 *
84 * Only one `App` may be alive at a time (per `RGB_T` instantiation): the
85 * gesture callbacks it wires up in begin() are plain C function pointers
86 * (`GestureDetector::onGesture`/`isDraggable`, not `std::function`), so
87 * they can't capture `this` - `App` routes them through a static
88 * self-pointer instead. Every example this replaces already only ever
89 * created one `Screen`/`GestureDetector` pair as globals, so this isn't a
90 * new restriction in practice.
91 */
92template <typename RGB_T = TINYMD_DEFAULT_RGB_T>
93class App {
94 public:
95 /// `board` must already be fully constructed (with whatever constructor
96 /// arguments its concrete type needs) and must outlive this `App` - see
97 /// the class comment.
98 explicit App(tinygpu::LCDBoard& board, const MaterialTheme<RGB_T>& theme = defaultTheme<RGB_T>())
99 : board_(board),
103 screen_(theme) {
104 instance_ = this;
105 }
106
107 /// Starts the board, display, and surface, and wires gesture routing to
108 /// the Screen - call once from setup() (after Serial.begin(115200) -
109 /// see the class comment), before or after registering widgets via
110 /// screen() (order between the two doesn't matter).
111 ///
112 /// If the full-screen framebuffer `surface()` needs can't be allocated
113 /// (see Screen::drawDirect()'s doc comment - typically a classic ESP32
114 /// without PSRAM, where a contiguous block that size may not exist even
115 /// with plenty of free heap overall), `update()` transparently falls
116 /// back to drawDirect() instead: same widgets, same screen() API, just a
117 /// small reused per-widget buffer rather than one full-screen one.
118 void begin() {
119 board_.begin();
120 display_.begin();
121 directRender_ = !surface_.begin();
122 if (directRender_) {
123#if defined(ARDUINO)
124 Serial.println(
125 "App: full-screen framebuffer allocation failed - falling back to "
126 "Screen::drawDirect()");
127#else
128 fprintf(stderr, "App: full-screen framebuffer allocation failed - falling back to "
129 "Screen::drawDirect()\n");
130#endif
131 scratch_.begin();
132 }
133 gestures_.onGesture = &App::onGestureTrampoline;
134 gestures_.isDraggable = &App::isDraggableTrampoline;
135 }
136
137 /// Call once per loop(): polls touch input, advances widget animations,
138 /// and redraws only if something actually changed - see
139 /// Screen::isDirty().
140 void update() {
141 gestures_.update(*board_.touch());
142 screen_.update(nowMillis());
143 if (screen_.isDirty()) {
144 if (directRender_) {
145 screen_.drawDirect(board_.display(), scratch_, static_cast<int32_t>(width()),
146 static_cast<int32_t>(height()));
147 } else {
148 screen_.draw(surface_);
149 display_.writeData(surface_);
150 }
151 }
152 }
153
154 /// Writes the current screen content as an uncompressed 24-bit BMP image
155 /// to `out` - anything that is a `Print`: a `File` on an SD card or
156 /// LittleFS, a network client, Serial, or on the desktop a file stream.
157 /// Pending changes are drawn (and written to the display) first, so the
158 /// image always matches what is on screen. Returns false while
159 /// usesDirectRender() is true - there is no full-screen framebuffer to
160 /// export then.
161 /// Milliseconds since start: Arduino's millis(), or TinyGPU's clock on the desktop.
162 static uint32_t nowMillis() {
163#if defined(ARDUINO)
164 return millis();
165#else
166 return tinygpu::millis();
167#endif
168 }
169
170 bool saveScreenshot(Print& out) {
171 if (directRender_) return false;
172 if (screen_.isDirty()) {
173 screen_.draw(surface_);
174 display_.writeData(surface_);
175 }
176 tinygpu::BMPExporter<RGB_T> exporter(surface_);
177 return exporter.save(out);
178 }
179
180 /// True once begin() has fallen back to the low-RAM Screen::drawDirect()
181 /// path because surface()'s full-screen framebuffer couldn't be
182 /// allocated - see begin()'s doc comment. Mainly useful for logging/
183 /// diagnostics; sketches don't need to branch on it themselves.
184 bool usesDirectRender() const { return directRender_; }
185
186 /// Register widgets here - addWidget()/addFixedWidget()/presentDialog(),
187 /// same as any other sketch's `screen`.
188 Screen<RGB_T>& screen() { return screen_; }
189
190 /// The theme in effect - see Screen::theme(). Handy for reading a color
191 /// role directly (e.g. for a widget's own setColorOverride()) without
192 /// keeping a separate MaterialTheme alongside `App`.
193 const MaterialTheme<RGB_T>& theme() const { return screen_.theme(); }
194
195 /// Rarely needed directly (App's own update() already draws to it) -
196 /// exposed for the odd sketch that wants to draw something outside the
197 /// widget tree. Empty/unused while usesDirectRender() is true - update()
198 /// draws to the display through `scratch` instead in that case.
199 tinygpu::Surface<RGB_T>& surface() { return surface_; }
200
201 /// The display's width/height in pixels - straight from the board (see
202 /// its own constructor), so a sketch never needs to declare its own
203 /// `kWidth`/`kHeight` just to lay out widgets; use `app.width()`/
204 /// `app.height()` directly wherever a widget's `Bounds` needs them.
205 size_t width() const { return board_.width(); }
206 size_t height() const { return board_.height(); }
207
208 private:
209 static void onGestureTrampoline(tinygpu::GestureEvent& event) { instance_->screen_.handleGesture(event); }
210 static bool isDraggableTrampoline(int16_t x, int16_t y) {
211 return instance_->screen_.isDraggableAt(x, y);
212 }
213
214 static App<RGB_T>* instance_;
215
216 tinygpu::LCDBoard& board_;
217 tinygpu::Surface<RGB_T> surface_;
218 tinygpu::Surface<RGB_T> scratch_;
219 tinygpu::DeviceOutput<RGB_T> display_;
220 tinygpu::GestureDetector gestures_;
221 Screen<RGB_T> screen_;
222 bool directRender_ = false;
223};
224
225template <typename RGB_T>
226App<RGB_T>* App<RGB_T>::instance_ = nullptr;
227
228} // namespace tinymd
Bundles the surface + display + gesture routing + Screen boilerplate that every single-widget example...
Definition: App.h:93
App(tinygpu::LCDBoard &board, const MaterialTheme< RGB_T > &theme=defaultTheme< RGB_T >())
Definition: App.h:98
bool usesDirectRender() const
Definition: App.h:184
bool saveScreenshot(Print &out)
Definition: App.h:170
static uint32_t nowMillis()
Definition: App.h:162
size_t width() const
Definition: App.h:205
Screen< RGB_T > & screen()
Definition: App.h:188
void begin()
Definition: App.h:118
void update()
Definition: App.h:140
const MaterialTheme< RGB_T > & theme() const
Definition: App.h:193
size_t height() const
Definition: App.h:206
tinygpu::Surface< RGB_T > & surface()
Definition: App.h:199
Owns a set of widgets, draws them, and routes gesture events to whichever one should handle each even...
Definition: Screen.h:71
Definition: AnchorLayout.h:4
Bundles a color scheme, shape tokens, typography, and spacing into one theme, passed to widgets so th...
Definition: MaterialTheme.h:50