TinyMaterialDesign
Loading...
Searching...
No Matches
Container.h
Go to the documentation of this file.
1#pragma once
2#include <algorithm>
3#include <functional>
4#include <utility>
5#include <vector>
6
7#include "TinyGPU/Input/GestureDetector.h"
8#include "TinyMaterialDesign/Core/Widget.h"
9#include "TinyMaterialDesign/Core/OffsetSurface.h"
10
11namespace tinymd {
12
13/**
14 * @brief A widget that holds child widgets, draws/dispatches gestures to
15 * them, and scrolls its content vertically when it overflows its own bounds.
16 *
17 * This is the nestable counterpart to Screen (which does the same job once,
18 * for the one root every sketch already has) - unlike GridLayout/LinearLayout/
19 * etc. (pure rect calculators consumed before construction), Container is a
20 * real Widget: it owns a child list, and since it's a Widget itself it can be
21 * added as a child of another Container, nesting arbitrarily deep.
22 *
23 * Container<RGB565> panel(Bounds(16, 56, 288, 300));
24 * panel.addChild(card1);
25 * panel.addChild(card2); // more content than panel.bounds.h -> scrolls
26 * screen.addWidget(panel);
27 *
28 * Children are non-owning references (same convention as every other
29 * composite in this library - Dialog's actions, Drawer's items, ...) and are
30 * authored with absolute Bounds starting at/near this container's own
31 * bounds.y, exactly like Screen's own scrollable content: at scrollOffset 0
32 * a child renders at its own authored position, and scrolling shifts that
33 * the same way Screen::draw() does.
34 *
35 * Children partially or fully scrolled past this container's own bounds
36 * are cropped to it (see ISurface::pushClipRect()), not just skipped or
37 * drawn in full - matching Screen's own root-level clip.
38 *
39 * Known limitation (shared with Screen - see its class comment): scrolling
40 * is vertical only, one axis.
41 *
42 * Alternative to addChild(): setChildProvider(count, at) switches this
43 * container to callback-driven content, for lists too large to keep every
44 * item's Widget resident at once (thousands of rows) - `count` reports how
45 * many logical items there are, `at(index)` returns a *reference* to the
46 * Widget representing item `index`, typically a small pool of real Widgets
47 * reused/repositioned/relabeled for whichever indices are currently visible
48 * (the classic "recycler" pattern), rather than one Widget per item. Once a
49 * provider is set it takes over completely - addChild()'d children are
50 * ignored while one is active. Caution: a continuous gesture (drag/scroll)
51 * latches the Widget* returned by `at()` at kBegan and keeps calling
52 * methods on it through kChanged/kEnded - don't let the pool reassign that
53 * same slot to a different index while a gesture is still in progress.
54 */
55template <typename RGB_T = TINYMD_DEFAULT_RGB_T>
56class Container : public Widget<RGB_T> {
57 public:
58 using Widget<RGB_T>::bounds;
59 using ChildCountFn = std::function<int()>;
60 using ChildAtFn = std::function<Widget<RGB_T>&(int index)>;
61
62 Container() = default;
63 explicit Container(Bounds containerBounds) { bounds = containerBounds; }
64
65 /// Registers `child` as content of this container. Not owned - see the
66 /// class comment. `child` may itself be a Container. Ignored while a
67 /// child provider is active - see setChildProvider().
68 void addChild(Widget<RGB_T>& child) {
69 children_.push_back(&child);
70 if (this->theme_ != nullptr) child.setTheme(*this->theme_);
71 }
72
73 /// Removes `child` (it is not deleted - the container does not own it).
74 /// @return false if it was not a child.
75 bool removeChild(Widget<RGB_T>& child) {
76 for (size_t i = 0; i < children_.size(); ++i) {
77 if (children_[i] == &child) {
78 if (activeChild_ == &child) activeChild_ = nullptr;
79 children_.erase(children_.begin() + static_cast<long>(i));
80 return true;
81 }
82 }
83 return false;
84 }
85
86 /// Removes all children (they are not deleted) and scrolls to the top.
88 children_.clear();
89 activeChild_ = nullptr;
90 scrollOffset_ = 0;
91 }
92
93 /// Number of children added with addChild().
94 int childrenCount() const { return static_cast<int>(children_.size()); }
95
96 /// Scrolls the content by `offset` pixels (0 = top), limited to the
97 /// content height.
98 void setScrollOffset(int32_t offset) {
99 scrollOffset_ = offset;
101 }
102
103 /// Scrolls so that `child` is `margin` pixels below the top of the
104 /// container (as far as the content height allows) - e.g. to keep a text
105 /// field visible above an on-screen keyboard.
106 void scrollToChild(const Widget<RGB_T>& child, int32_t margin = 4) {
107 setScrollOffset(child.bounds.y - bounds.y - margin);
108 }
109
110 /// Switches this container to callback-driven content - see the class
111 /// comment. Pass empty functions (the default-constructed state) to
112 /// switch back to addChild()'s stored-vector mode.
113 void setChildProvider(ChildCountFn count, ChildAtFn at) {
114 childCountFn_ = std::move(count);
115 childAtFn_ = std::move(at);
116 }
117
118 /// Fast path for contentHeight(): when every item is exactly `height`
119 /// tall (uniform-height rows, the common case for a huge provider-backed
120 /// list), content height becomes `effectiveCount() * height` - an O(1)
121 /// calculation - instead of fetching and measuring every single item
122 /// every frame (see contentHeight()'s own doc comment on why that
123 /// matters at large counts). Pass 0 (the default) to go back to
124 /// measuring each item; irrelevant in addChild() vector mode, where
125 /// items are typically few enough that measuring them all is already
126 /// cheap.
127 void setUniformItemHeight(int32_t height) { uniformItemHeight_ = height; }
128
129 /// Cascades the theme to every already-added child (vector mode). In
130 /// provider mode, each Widget the provider hands back is themed at the
131 /// point it's fetched instead (see effectiveChild()) - there's no fixed
132 /// set of children to cascade to ahead of time.
133 void setTheme(const MaterialTheme<RGB_T>& theme) override {
134 Widget<RGB_T>::setTheme(theme);
135 for (Widget<RGB_T>* child : children_) {
136 if (child != nullptr) child->setTheme(theme);
137 }
138 }
139
140 void draw(tinygpu::ISurface<RGB_T>& target) override {
142 drawChildren(target);
143 drawScrollbar(target);
144 }
145
146 /// Everything this container draws except its children - see
147 /// Widget::drawBackground(). Just the scrollbar, since a Container has no
148 /// chrome of its own.
149 void drawBackground(tinygpu::ISurface<RGB_T>& target) override {
151 drawScrollbar(target);
152 }
153
154 bool update(uint32_t nowMs) override {
155 bool changed = false;
156 const int count = effectiveCount();
157 for (int i = 0; i < count; ++i) {
158 Widget<RGB_T>* child = effectiveChild(i);
159 if (child != nullptr) changed |= child->update(nowMs);
160 }
161 return changed;
162 }
163
164 bool onGesture(const tinygpu::GestureEvent& event) override {
165 using tinygpu::GesturePhase;
166 using tinygpu::GestureType;
167
168 if (isContinuousType(event.type)) {
169 if (event.phase == GesturePhase::kBegan) {
170 scrollbarDragActive_ = isOnScrollbar(event.startPoint.x, event.startPoint.y);
171 }
172 if (event.phase == GesturePhase::kBegan && !scrollbarDragActive_) {
173 // Only claim a pan/scroll for this container's own scroll if it
174 // actually has somewhere to scroll to - otherwise it would swallow
175 // every such gesture starting anywhere inside it (clamped to a
176 // no-op) before a nested Container/Screen underneath ever saw it,
177 // even one that genuinely needs to scroll. When this container has
178 // nothing to scroll, fall through to the same "find the hit child"
179 // path as any other continuous gesture, so - directly or through a
180 // few levels of nesting - whichever Container actually has
181 // overflowing content gets the drag. If more than one level in the
182 // chain needs to scroll, the outermost one still wins once it
183 // needs to (unchanged from before) - only the "nothing to scroll,
184 // so don't claim it" case is new.
185 if ((event.type == GestureType::kPan || event.type == GestureType::kScroll) &&
186 contentHeight() > bounds.h) {
187 scrollDragActive_ = true;
188 activeChild_ = nullptr;
189 } else {
190 scrollDragActive_ = false;
191 activeChild_ = hitTest(event.startPoint.x, event.startPoint.y);
192 }
193 }
194
195 bool handled = false;
197 // dragging on the scrollbar: the thumb follows the finger
198 scrollToTrackY(event.point.y);
199 handled = true;
200 } else if (scrollDragActive_) {
201 scrollOffset_ -= event.stepDeltaY;
203 handled = true;
204 } else if (activeChild_ != nullptr && activeChild_->enabled) {
205 handled = dispatch(*activeChild_, event);
206 }
207
208 if (event.phase == GesturePhase::kEnded) {
209 activeChild_ = nullptr;
210 scrollDragActive_ = false;
211 scrollbarDragActive_ = false;
212 }
213 return handled;
214 }
215
216 // a tap on the scrollbar jumps to the touched position
217 if (isTapGesture(event.type) && isOnScrollbar(event.point.x, event.point.y)) {
218 scrollToTrackY(event.point.y);
219 return true;
220 }
221
222 Widget<RGB_T>* hit = hitTest(event.point.x, event.point.y);
223 if (hit != nullptr && hit->enabled) return dispatch(*hit, event);
224 return false;
225 }
226
227 int childCount() const override { return effectiveCount(); }
228
229 Widget<RGB_T>* child(int index) override { return effectiveChild(index); }
230
231 /// Current vertical scroll offset (0 = content's natural top).
232 int32_t scrollOffset() const { return scrollOffset_; }
233
234 /// True if there's a child at (x, y) - this container's own coordinate
235 /// space - that's draggable, recursing into it via its own
236 /// isDraggableAt() if it's itself a composite (a nested Container,
237 /// Dialog, ...) - see Widget::isDraggableAt(). Wire Screen::
238 /// isDraggableAt() (or, for a Container nested inside another, this
239 /// same method on the outer one) to this so a drag starting on it, at
240 /// any nesting depth, is classified correctly.
241 bool isDraggableAt(int32_t x, int32_t y) const override {
242 // a drag starting on the scrollbar moves the thumb (see onGesture())
243 if (isOnScrollbar(x, y)) return true;
244 Widget<RGB_T>* hit = hitTest(x, y);
245 if (hit == nullptr) return false;
246 return hit->isDraggableAt(x, y + scrollOffset_);
247 }
248
249 /// Width (in pixels, from the right edge) of the touch zone of the
250 /// scrollbar - wider than the drawn bar so it is easy to hit with a
251 /// finger. Tapping in it scrolls to the touched position, dragging in it
252 /// moves the thumb with the finger. The zone only exists while the content
253 /// overflows and takes priority over children below it, so keep
254 /// interactive children this far from the right edge of a scrolling
255 /// container.
256 static constexpr int32_t kScrollbarTouchWidth = 12;
257
258 /// True for a gesture type that spans multiple events (kBegan/kChanged/
259 /// kEnded) rather than firing once - used by callers that compose a
260 /// Container (Screen; Drawer/BottomSheet/Menu's own item area) to decide
261 /// whether to route a gesture here at all before it's mid-flight.
262 static bool isContinuousType(tinygpu::GestureType type) {
263 using tinygpu::GestureType;
264 switch (type) {
265 case GestureType::kDrag:
266 case GestureType::kPan:
267 case GestureType::kScroll:
268 case GestureType::kPinchIn:
269 case GestureType::kPinchOut:
270 case GestureType::kRotate:
271 return true;
272 default:
273 return false;
274 }
275 }
276
277 bool isContainer() const override { return true; }
278
279 protected:
280 /// Height of this container's content, measured from its own bounds.y -
281 /// mirrors Screen::contentHeight() but relative to this container's own
282 /// top rather than the whole surface. Protected: Screen reuses this
283 /// directly for its own drawDirect()/drawScrollbarDirect(), since it's a
284 /// Container itself and drives the same scroll math one layer further out.
285 /// In provider mode this visits every logical index to find the tallest -
286 /// still O(count) rather than O(memory), but a huge count makes this (and
287 /// so every clampScroll() call, i.e. every frame) proportionally slower;
288 /// keep item heights cheap to compute if count is large, or call
289 /// setUniformItemHeight() for an O(1) alternative when rows are all the
290 /// same height.
291 int32_t contentHeight() const {
292 const int count = effectiveCount();
293 if (uniformItemHeight_ > 0) return count * uniformItemHeight_;
294 int32_t bottom = bounds.y;
295 for (int i = 0; i < count; ++i) {
296 Widget<RGB_T>* child = effectiveChild(i);
297 if (child != nullptr) bottom = std::max(bottom, child->bounds.bottom());
298 }
299 return bottom - bounds.y;
300 }
301
302 /// Height of the scrollbar thumb for `content` pixels of content (see
303 /// contentHeight()). Shared by drawing and touch handling so both agree.
304 int32_t scrollThumbHeight(int32_t content) const {
305 return std::max(int32_t(24), bounds.h * bounds.h / content);
306 }
307
308 /// True if (x, y) - same coordinate space as `bounds` - is inside the
309 /// scrollbar touch zone (see kScrollbarTouchWidth) while the content
310 /// overflows.
311 bool isOnScrollbar(int32_t x, int32_t y) const {
312 return x >= bounds.right() - kScrollbarTouchWidth && x < bounds.right() && y >= bounds.y &&
313 y < bounds.bottom() && contentHeight() > bounds.h;
314 }
315
316 /// Scrolls so that the thumb is centered on track position `y` (same
317 /// coordinate space as `bounds`).
318 void scrollToTrackY(int32_t y) {
319 const int32_t content = contentHeight();
320 const int32_t maxScroll = content - bounds.h;
321 if (maxScroll <= 0) return;
322 const int32_t thumb = scrollThumbHeight(content);
323 const int32_t track = bounds.h - thumb;
324 scrollOffset_ = track > 0 ? (y - bounds.y - thumb / 2) * maxScroll / track : 0;
326 }
327
328 void clampScroll() {
329 const int32_t maxScroll = std::max(int32_t{0}, contentHeight() - bounds.h);
330 scrollOffset_ = std::min(std::max(scrollOffset_, int32_t{0}), maxScroll);
331 }
332
333 /// Number of children right now - the provider's count() if
334 /// setChildProvider() is active, else the addChild()'d vector's size.
335 /// Protected: Screen's drawDirect() drives the same loop one layer out.
336 int effectiveCount() const {
337 return childCountFn_ ? childCountFn_() : static_cast<int>(children_.size());
338 }
339
340 /// The child at `index` right now - from the provider if active (themed
341 /// immediately, since there's no fixed set to cascade setTheme() to ahead
342 /// of time - see setChildProvider()), else from the addChild()'d vector.
343 /// Protected: Screen's drawDirect() drives the same loop one layer out.
344 Widget<RGB_T>* effectiveChild(int index) const {
345 if (childAtFn_) {
346 Widget<RGB_T>& child = childAtFn_(index);
347 if (this->theme_ != nullptr) child.setTheme(*this->theme_);
348 return &child;
349 }
350 return children_[static_cast<size_t>(index)];
351 }
352
354 ChildCountFn childCountFn_;
355 ChildAtFn childAtFn_;
357 Widget<RGB_T>* activeChild_ = nullptr;
358 bool scrollDragActive_ = false;
359 /// A continuous gesture started on the scrollbar (see isOnScrollbar()).
361 int32_t scrollOffset_ = 0;
362
363 private:
364 /// True if screen-space `b` overlaps this container's own bounds at all -
365 /// a cheap pre-filter so a child scrolled entirely out of view is skipped
366 /// without even being drawn (drawChildren()'s clip rect handles correctly
367 /// cropping the ones that only partially overlap).
368 bool intersectsBounds(const Bounds& b) const {
369 return b.bottom() > bounds.y && b.y < bounds.bottom() && b.right() > bounds.x && b.x < bounds.right();
370 }
371
372 /// Draws every visible child, each cropped to this container's own
373 /// bounds (see ISurface::pushClipRect()) - a child only partially
374 /// overlapping (scrolled halfway past the top/bottom edge) is cropped
375 /// to the visible portion instead of drawn in full or skipped outright.
376 void drawChildren(tinygpu::ISurface<RGB_T>& target) {
377 target.pushClipRect(toPx(bounds.x), toPx(bounds.y), toPx(bounds.w), toPx(bounds.h));
378 const int count = effectiveCount();
379 for (int i = 0; i < count; ++i) {
380 Widget<RGB_T>* child = effectiveChild(i);
381 if (child == nullptr || !child->visible) continue;
382 child->bounds.y -= scrollOffset_;
383 if (intersectsBounds(child->bounds)) {
384 if (child->bounds.y < 0) {
385 drawAboveTop(target, *child);
386 } else {
387 child->draw(target);
388 }
389 }
390 child->bounds.y += scrollOffset_;
391 }
392 target.popClipRect();
393 }
394
395 /// A child whose top is above the edge of the surface (scrolled up): the
396 /// drawing primitives only take coordinates >= 0 (toPx() clamps), so it is
397 /// drawn moved down and an OffsetSurface writes it back to its real place,
398 /// clipped to this container.
399 void drawAboveTop(tinygpu::ISurface<RGB_T>& target, Widget<RGB_T>& child) {
400 const int32_t dy = -child.bounds.y;
401 OffsetSurface<RGB_T> shifted(target, dy, bounds.y, bounds.bottom());
402 child.bounds.y += dy;
403 child.draw(shifted);
404 child.bounds.y -= dy;
405 }
406
407 /// A thin right-edge indicator of scroll position/range, confined to this
408 /// container's own bounds - mirrors Screen::drawScrollbar(). Omitted
409 /// entirely once content already fits.
410 void drawScrollbar(tinygpu::ISurface<RGB_T>& target) {
411 const int32_t content = contentHeight();
412 if (content <= bounds.h) return;
413
414 constexpr int32_t kBarWidth = 4;
415 const int32_t trackX = bounds.right() - kBarWidth;
416 target.fillRect(toPx(trackX), toPx(bounds.y), toPx(kBarWidth), toPx(bounds.h),
417 blend(this->theme().colors.surface, this->theme().colors.outline, 0.25f));
418
419 const int32_t maxScroll = content - bounds.h;
420 const int32_t thumbHeight = scrollThumbHeight(content);
421 const int32_t thumbY =
422 maxScroll > 0 ? bounds.y + (scrollOffset_ * (bounds.h - thumbHeight)) / maxScroll : bounds.y;
423 target.fillRoundRect(toPx(trackX), toPx(thumbY), toPx(kBarWidth), toPx(thumbHeight), toPx(kBarWidth / 2),
424 this->theme().colors.primary);
425 }
426
427 /// Last-added child wins ties, i.e. later addChild() calls are treated as
428 /// drawn on top (matches drawChildren()). (x, y) is this container's own
429 /// coordinate space; translated into content space by the current scroll
430 /// offset before testing, since child bounds are authored in content
431 /// space (see the class comment).
432 Widget<RGB_T>* hitTest(int32_t x, int32_t y) const {
433 const int32_t contentY = y + scrollOffset_;
434 for (int i = effectiveCount() - 1; i >= 0; --i) {
435 Widget<RGB_T>* child = effectiveChild(i);
436 if (child != nullptr && child->visible && child->enabled && child->bounds.contains(x, contentY)) {
437 return child;
438 }
439 }
440 return nullptr;
441 }
442
443 /// Forwards `event` to `child`, translating its point/startPoint back into
444 /// content space first - mirrors Screen::dispatch().
445 bool dispatch(Widget<RGB_T>& child, const tinygpu::GestureEvent& event) {
446 if (scrollOffset_ == 0) return child.onGesture(event);
447 tinygpu::GestureEvent shifted = event;
448 shifted.point.y = static_cast<int16_t>(shifted.point.y + scrollOffset_);
449 shifted.startPoint.y = static_cast<int16_t>(shifted.startPoint.y + scrollOffset_);
450 return child.onGesture(shifted);
451 }
452};
453
454} // namespace tinymd
A widget that holds child widgets, draws/dispatches gestures to them, and scrolls its content vertica...
Definition: Container.h:56
void scrollToTrackY(int32_t y)
Definition: Container.h:318
ChildCountFn childCountFn_
Definition: Container.h:354
void clearChildren()
Removes all children (they are not deleted) and scrolls to the top.
Definition: Container.h:87
int32_t uniformItemHeight_
Definition: Container.h:356
bool isContainer() const override
Provides true if the widget is a container.
Definition: Container.h:277
bool isDraggableAt(int32_t x, int32_t y) const override
Definition: Container.h:241
int32_t contentHeight() const
Definition: Container.h:291
int32_t scrollThumbHeight(int32_t content) const
Definition: Container.h:304
bool onGesture(const tinygpu::GestureEvent &event) override
Handles one gesture event. Returns true if this widget consumed it.
Definition: Container.h:164
int32_t scrollOffset() const
Current vertical scroll offset (0 = content's natural top).
Definition: Container.h:232
bool isOnScrollbar(int32_t x, int32_t y) const
Definition: Container.h:311
void addChild(Widget< RGB_T > &child)
Definition: Container.h:68
int childrenCount() const
Number of children added with addChild().
Definition: Container.h:94
static constexpr int32_t kScrollbarTouchWidth
Definition: Container.h:256
Widget< RGB_T > * child(int index) override
Definition: Container.h:229
Container()=default
std::vector< Widget< RGB_T > * > children_
Definition: Container.h:353
void setChildProvider(ChildCountFn count, ChildAtFn at)
Definition: Container.h:113
bool scrollDragActive_
Definition: Container.h:358
Widget< RGB_T > * effectiveChild(int index) const
Definition: Container.h:344
void scrollToChild(const Widget< RGB_T > &child, int32_t margin=4)
Definition: Container.h:106
void setUniformItemHeight(int32_t height)
Definition: Container.h:127
int32_t scrollOffset_
Definition: Container.h:361
void draw(tinygpu::ISurface< RGB_T > &target) override
Definition: Container.h:140
int effectiveCount() const
Definition: Container.h:336
Container(Bounds containerBounds)
Definition: Container.h:63
Widget< RGB_T > * activeChild_
Definition: Container.h:357
bool update(uint32_t nowMs) override
Definition: Container.h:154
int childCount() const override
Definition: Container.h:227
ChildAtFn childAtFn_
Definition: Container.h:355
bool removeChild(Widget< RGB_T > &child)
Definition: Container.h:75
void setTheme(const MaterialTheme< RGB_T > &theme) override
Definition: Container.h:133
void drawBackground(tinygpu::ISurface< RGB_T > &target) override
Definition: Container.h:149
bool scrollbarDragActive_
A continuous gesture started on the scrollbar (see isOnScrollbar()).
Definition: Container.h:360
void setScrollOffset(int32_t offset)
Definition: Container.h:98
static bool isContinuousType(tinygpu::GestureType type)
Definition: Container.h:262
void clampScroll()
Definition: Container.h:328
Draws into target moved up by dy pixels, only inside the rows [clipTop, clipBottom) of target.
Definition: OffsetSurface.h:22
Base class every TinyMaterialDesign widget derives from.
Definition: Widget.h:58
Definition: AnchorLayout.h:4
Axis-aligned pixel rectangle used for widget bounds and hit-testing.
Definition: Bounds.h:21
int32_t right() const
Definition: Bounds.h:30
int32_t bottom() const
Definition: Bounds.h:31
int32_t y
Definition: Bounds.h:23
int32_t x
Definition: Bounds.h:22
Bundles a color scheme, shape tokens, typography, and spacing into one theme, passed to widgets so th...
Definition: MaterialTheme.h:50