@geastack/engine 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +29 -0
  3. package/bitmap_font.cpp +165 -0
  4. package/canvas.cpp +4608 -0
  5. package/components/Button.d.ts +4 -0
  6. package/components/Button.tsx +32 -0
  7. package/components/Image.d.ts +3 -0
  8. package/components/Image.tsx +17 -0
  9. package/components/Text.d.ts +3 -0
  10. package/components/Text.tsx +9 -0
  11. package/components/View.d.ts +3 -0
  12. package/components/View.tsx +24 -0
  13. package/components/index.d.ts +8 -0
  14. package/components/index.ts +4 -0
  15. package/css/animation.h +252 -0
  16. package/css/declarative.h +131 -0
  17. package/css/easing.h +160 -0
  18. package/css/engine.h +223 -0
  19. package/css/interpolate.h +38 -0
  20. package/image_store.cpp +807 -0
  21. package/package.json +62 -0
  22. package/rasterized_font.cpp +570 -0
  23. package/touch_runtime.cpp +513 -0
  24. package/ui/absolute_leaf_refresh.cpp +279 -0
  25. package/ui/absolute_leaf_refresh.h +12 -0
  26. package/ui/canvas_element.cpp +2314 -0
  27. package/ui/canvas_element.h +353 -0
  28. package/ui/canvas_store.cpp +188 -0
  29. package/ui/canvas_store.h +59 -0
  30. package/ui/core.cpp +135 -0
  31. package/ui/css_atom.cpp +155 -0
  32. package/ui/css_atom.h +21 -0
  33. package/ui/dirty_regions.cpp +66 -0
  34. package/ui/dirty_regions.h +34 -0
  35. package/ui/display_invalidation.cpp +101 -0
  36. package/ui/display_invalidation.h +15 -0
  37. package/ui/document.cpp +356 -0
  38. package/ui/document.h +101 -0
  39. package/ui/image.h +16 -0
  40. package/ui/image_element.cpp +13 -0
  41. package/ui/image_node.cpp +165 -0
  42. package/ui/input.cpp +936 -0
  43. package/ui/input_render.cpp +213 -0
  44. package/ui/internal.h +567 -0
  45. package/ui/layout.cpp +2025 -0
  46. package/ui/layout_snapshot.cpp +82 -0
  47. package/ui/layout_snapshot.h +12 -0
  48. package/ui/mirror.h +25 -0
  49. package/ui/node.cpp +243 -0
  50. package/ui/node.h +154 -0
  51. package/ui/node_lifecycle.cpp +137 -0
  52. package/ui/node_lifecycle.h +13 -0
  53. package/ui/node_model.h +597 -0
  54. package/ui/refresh_perf.h +235 -0
  55. package/ui/refresh_trace.h +68 -0
  56. package/ui/render.cpp +12097 -0
  57. package/ui/root_scroll_refresh.cpp +859 -0
  58. package/ui/root_scroll_refresh.h +30 -0
  59. package/ui/state_init.h +21 -0
  60. package/ui/style.cpp +14994 -0
  61. package/ui/style.h +727 -0
  62. package/ui/style_values.h +31 -0
  63. package/ui/text.cpp +2010 -0
  64. package/ui/text.h +15 -0
  65. package/ui/text_element.cpp +15 -0
  66. package/ui/tree_events.cpp +621 -0
  67. package/ui/tree_events.h +69 -0
  68. package/ui/tree_internal.h +191 -0
  69. package/ui/tree_nodes.cpp +628 -0
  70. package/ui/tree_render.cpp +3138 -0
  71. package/ui/tree_scroll_mirror.cpp +101 -0
  72. package/ui/tree_state.cpp +574 -0
  73. package/ui/tree_state.h +235 -0
  74. package/ui/tree_style.cpp +698 -0
  75. package/ui/ui.h +9 -0
  76. package/ui/view.cpp +2232 -0
  77. package/ui/view.h +14 -0
  78. package/ui/view_element.cpp +13 -0
  79. package/ui/viewport_region.cpp +36 -0
  80. package/ui/viewport_region.h +12 -0
  81. package/ui/virtual_keyboard.cpp +908 -0
  82. package/ui/virtual_keyboard.h +59 -0
  83. package/vendor/AnimatedGIF/AnimatedGIF.c +982 -0
  84. package/vendor/AnimatedGIF/AnimatedGIF.h +216 -0
  85. package/vendor/stb/stb_image.h +7988 -0
  86. package/vendor/stb/stb_truetype.h +5079 -0
package/ui/input.cpp ADDED
@@ -0,0 +1,936 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #include "internal.h"
3
+
4
+ #include "pixel.h"
5
+ #include "tree_state.h"
6
+
7
+ #include "services/frame_scheduler.h"
8
+
9
+ #include <algorithm>
10
+ #include <cmath>
11
+ #include <cstdint>
12
+ #include <cstdio>
13
+ #include <cstdlib>
14
+ #include <cstring>
15
+
16
+ namespace gea::embedded::ui {
17
+
18
+ namespace {
19
+
20
+ // Scroll-pacing trace (GEA_SCROLL_TRACE=1): logs gesture brackets, every
21
+ // applied drag delta, fling launches, and each momentum tick on the shared
22
+ // monotonic-ms timebase so uneven per-frame scroll jumps can be correlated
23
+ // with touch-event arrival ([sc.ev]) and frame pacing ([sc.fr]).
24
+ // A compile-time define as well as the environment variable: an embedded target
25
+ // has no environment, so getenv() left this trace -- and the hit-routing audit
26
+ // below it -- unreachable on exactly the devices whose input routing is hardest
27
+ // to observe from the outside.
28
+ #ifndef GEA_SCROLL_TRACE
29
+ #define GEA_SCROLL_TRACE 0
30
+ #endif
31
+
32
+ bool scrollTraceEnabled()
33
+ {
34
+ #if GEA_SCROLL_TRACE
35
+ return true;
36
+ #else
37
+ static const bool enabled = [] {
38
+ const char *v = std::getenv("GEA_SCROLL_TRACE");
39
+ return v && *v && *v != '0';
40
+ }();
41
+ return enabled;
42
+ #endif
43
+ }
44
+
45
+ class InputController {
46
+ enum class ScrollAxis : std::int8_t {
47
+ None = 0,
48
+ X,
49
+ Y
50
+ };
51
+
52
+ public:
53
+ static InputController &instance()
54
+ {
55
+ static InputController controller;
56
+ return controller;
57
+ }
58
+
59
+ int hitTest(int x, int y)
60
+ {
61
+ Tree &tree = Tree::instance();
62
+ if (tree.nodeCount() == 0) return -1;
63
+ const int nodeId = hitTestNodeId(0, x, y);
64
+ return pressTargetForNode(nodeId);
65
+ }
66
+
67
+ int hitTestNode(int x, int y)
68
+ {
69
+ Tree &tree = Tree::instance();
70
+ if (tree.nodeCount() == 0) return -1;
71
+ return hitTestNodeId(0, x, y);
72
+ }
73
+
74
+ void pointerDown(int x, int y)
75
+ {
76
+ Tree &tree = Tree::instance();
77
+ clearActiveTouch();
78
+ // A new finger touch pauses any in-flight momentum scroll. Stash
79
+ // the current velocity so that if the user flicks again in the same
80
+ // direction, the new fling can add to it — iOS-style "re-flick to
81
+ // accelerate". If the next gesture turns out to be just a tap, we
82
+ // drop the carry-over in startMomentum().
83
+ carryOverVelocity_ = momentumVelocity_;
84
+ carryOverAxis_ = momentumAxis_;
85
+ cancelMomentum();
86
+ activeScrollNode_ = tree.nodeCount() == 0 ? -1 : findScrollNodeId(0, x, y);
87
+ snapAccumDy_ = 0;
88
+ activeScrollAxis_ = ScrollAxis::None;
89
+ scrollLastX_ = x;
90
+ scrollLastY_ = y;
91
+ resetVelocitySamples();
92
+ pushVelocitySample(x, y);
93
+ if (scrollTraceEnabled())
94
+ std::fprintf(stderr, "[sc.down] t=%d x=%d y=%d node=%d carry=%.3f\n",
95
+ gea::framework::services::FrameScheduler::nowMs(), x, y, activeScrollNode_,
96
+ carryOverVelocity_);
97
+
98
+ if (tree.nodeCount() == 0) {
99
+ return;
100
+ }
101
+
102
+ const int nodeId = hitTestNodeId(0, x, y);
103
+ if (nodeId < 0) {
104
+ return;
105
+ }
106
+ // A `touch-action="none"` element (e.g. a horizontal drag slider) owns the
107
+ // gesture: don't let an ancestor scroll container steal it.
108
+ if (activeScrollNode_ >= 0 && nodeChainDisablesScroll(nodeId)) {
109
+ activeScrollNode_ = -1;
110
+ }
111
+ // Hit-routing audit (camera-studio tap-misrouting investigation): the
112
+ // resolved node, its tag, and its layout box for every pointer down.
113
+ // Behind the same switch as every other trace in this file -- it went out
114
+ // ungated and wrote to stderr on every pointer down in every app, which
115
+ // is a per-tap stdio call on the frame task and, on a target where
116
+ // stderr is not usable, a crash in the input path rather than a log line.
117
+ if (scrollTraceEnabled()) {
118
+ Node &hit = tree.nodes()[nodeId];
119
+ std::fprintf(stderr, "[hit.down] (%d,%d) -> node=%d tag=%s rect=(%d,%d %dx%d)\n", x, y, nodeId,
120
+ tree.tagName(nodeId) ? tree.tagName(nodeId) : "?", hit.layout.x, hit.layout.y,
121
+ hit.layout.width, hit.layout.height);
122
+ }
123
+
124
+ const int activeNodeId = findActiveTouchNodeId(nodeId);
125
+ if (activeNodeId < 0) {
126
+ return;
127
+ }
128
+
129
+ Node &node = tree.nodes()[activeNodeId];
130
+ activeTouchNode_ = activeNodeId;
131
+ savedBackgroundColor_ = node.style.bg_color;
132
+ savedHasBackground_ = node.style.has_bg;
133
+ node.style.bg_color = node.style.has_active_bg ? node.style.active_bg_color : lightenRgb565(node.style.bg_color);
134
+ node.style.has_bg = 1;
135
+ activeBackgroundColor_ = node.style.bg_color;
136
+ activeHasBackground_ = node.style.has_bg;
137
+ node.render.dirty = 1; // paint-only: press highlight recolors in place
138
+ node.render.non_scroll_dirty = 1;
139
+ // We mutated bg_color directly (bypassing setStyleValue), so the
140
+ // direct-replay refresh path would otherwise keep the cached
141
+ // pre-press color in the display list. Mark commands dirty so the
142
+ // new pressed color actually renders.
143
+ tree.markNodeDisplayCommandsDirty(activeNodeId);
144
+ }
145
+
146
+ int pointerMove(int x, int y)
147
+ {
148
+ Tree &tree = Tree::instance();
149
+ if (activeScrollNode_ < 0 || activeScrollNode_ >= tree.nodeCount()) {
150
+ scrollLastX_ = x;
151
+ scrollLastY_ = y;
152
+ return 0;
153
+ }
154
+
155
+ Node &node = tree.nodes()[activeScrollNode_];
156
+ const int dx = x - scrollLastX_;
157
+ const int dy = y - scrollLastY_;
158
+ scrollLastX_ = x;
159
+ scrollLastY_ = y;
160
+ // Sample the finger on every move — even when scroll hits a boundary
161
+ // the finger is still moving and that velocity should drive the
162
+ // eventual fling once the user moves back inside the range.
163
+ pushVelocitySample(x, y);
164
+ if (dx == 0 && dy == 0) return 0;
165
+
166
+ const bool canScrollX = nodeCanScrollX(activeScrollNode_, node);
167
+ const bool canScrollY = nodeCanScrollY(activeScrollNode_, node);
168
+ if (activeScrollAxis_ == ScrollAxis::None) {
169
+ const int absDx = std::abs(dx);
170
+ const int absDy = std::abs(dy);
171
+ if (canScrollX && (!canScrollY || absDx >= absDy)) {
172
+ activeScrollAxis_ = ScrollAxis::X;
173
+ } else if (canScrollY) {
174
+ activeScrollAxis_ = ScrollAxis::Y;
175
+ }
176
+ }
177
+
178
+ bool changed = false;
179
+ if (dx != 0 && canScrollX && activeScrollAxis_ == ScrollAxis::X) {
180
+ int next = scrollLeft(activeScrollNode_) - dx;
181
+ const int maxX = scrollMaxX(activeScrollNode_, node);
182
+ if (next < 0) next = 0;
183
+ if (next > maxX) next = maxX;
184
+ if (next != scrollLeft(activeScrollNode_)) {
185
+ clearActiveTouch();
186
+ setScrollLeft(activeScrollNode_, next);
187
+ changed = true;
188
+ if (scrollTraceEnabled())
189
+ std::fprintf(stderr, "[sc.mv] t=%d x=%d dx=%d sx=%d\n",
190
+ gea::framework::services::FrameScheduler::nowMs(), x, dx, next);
191
+ }
192
+ }
193
+ if (dy != 0 && canScrollY && activeScrollAxis_ == ScrollAxis::Y) {
194
+ // Row-snap container (snap-step attr): hold the panel still while the
195
+ // finger moves — pointerUp applies ONE quantized scroll, which lands as
196
+ // a single isolated (quality-waveform) refresh on e-paper instead of a
197
+ // refresh per touch-move.
198
+ if (nodeSnapStepY(activeScrollNode_) > 0) {
199
+ snapAccumDy_ += dy;
200
+ if (std::abs(snapAccumDy_) > 8) clearActiveTouch();
201
+ return 1;
202
+ }
203
+ int next = scrollTop(activeScrollNode_) - dy;
204
+ const int maxY = scrollMaxY(activeScrollNode_, node);
205
+ if (next < 0) next = 0;
206
+ if (next > maxY) next = maxY;
207
+ if (next != scrollTop(activeScrollNode_)) {
208
+ clearActiveTouch();
209
+ setScrollTop(activeScrollNode_, next);
210
+ changed = true;
211
+ if (scrollTraceEnabled())
212
+ std::fprintf(stderr, "[sc.mv] t=%d y=%d dy=%d sy=%d\n",
213
+ gea::framework::services::FrameScheduler::nowMs(), y, dy, next);
214
+ }
215
+ }
216
+ if (!changed) return 0;
217
+
218
+ return 1;
219
+ }
220
+
221
+ int pointerUp()
222
+ {
223
+ const int scrollNode = activeScrollNode_;
224
+ const ScrollAxis scrollAxis = activeScrollAxis_;
225
+ activeScrollNode_ = -1;
226
+ activeScrollAxis_ = ScrollAxis::None;
227
+ if (scrollTraceEnabled())
228
+ std::fprintf(stderr, "[sc.up] t=%d node=%d\n",
229
+ gea::framework::services::FrameScheduler::nowMs(), scrollNode);
230
+
231
+ const int snapStep = scrollNode >= 0 ? nodeSnapStepY(scrollNode) : 0;
232
+ if (snapStep > 0 && scrollAxis == ScrollAxis::Y) {
233
+ // Commit the held drag as one row-aligned scroll (no momentum).
234
+ const int accum = snapAccumDy_;
235
+ snapAccumDy_ = 0;
236
+ Tree &tree = Tree::instance();
237
+ Node &node = tree.node(scrollNode);
238
+ const int cur = scrollTop(scrollNode);
239
+ const int maxY = scrollMaxY(scrollNode, node);
240
+ int raw = cur - accum;
241
+ if (raw < 0) raw = 0;
242
+ if (raw > maxY) raw = maxY;
243
+ int snapped = ((raw + snapStep / 2) / snapStep) * snapStep;
244
+ // An intentional drag always advances at least one row, even when the
245
+ // quantizer would round back to the current offset.
246
+ if (snapped == cur && std::abs(accum) >= 48)
247
+ snapped = cur + (accum < 0 ? snapStep : -snapStep);
248
+ if (snapped < 0) snapped = 0;
249
+ if (snapped > maxY) snapped = maxY;
250
+ if (snapped != cur) setScrollTop(scrollNode, snapped);
251
+ resetVelocitySamples();
252
+ if (activeTouchNode_ >= 0) clearActiveTouch();
253
+ return -1;
254
+ }
255
+ snapAccumDy_ = 0;
256
+ if (scrollNode >= 0 && nodeHasMomentumOptIn(scrollNode)) {
257
+ pushVelocitySample(scrollLastX_, scrollLastY_);
258
+ startMomentum(scrollNode, scrollAxis);
259
+ }
260
+ resetVelocitySamples();
261
+
262
+ if (activeTouchNode_ >= 0) {
263
+ clearActiveTouch();
264
+ }
265
+ return -1;
266
+ }
267
+
268
+ // Programmatic vertical scroll for non-pointer input — e.g. hardware
269
+ // Up/Down buttons on touchless boards. Finds the first vertically
270
+ // scrollable container in tree order and nudges it by `dy` layout pixels
271
+ // (positive = toward the end of the content, i.e. "scroll down"), clamped
272
+ // to the scroll range. Returns true if the offset actually changed. This
273
+ // reuses the same scroll primitives as the touch path so VirtualList and
274
+ // overflow:auto views behave identically.
275
+ bool scrollFirstContainerY(int dy)
276
+ {
277
+ if (dy == 0) return false;
278
+ Tree &tree = Tree::instance();
279
+ const int count = tree.nodeCount();
280
+ for (int id = 0; id < count; ++id) {
281
+ Node &node = tree.nodes()[id];
282
+ if (node.style.display == 1) continue; // display:none
283
+ if (!nodeCanScrollY(id, node)) continue;
284
+ const int cur = scrollTop(id);
285
+ int next = cur + dy;
286
+ const int maxY = scrollMaxY(id, node);
287
+ if (next < 0) next = 0;
288
+ if (next > maxY) next = maxY;
289
+ if (next == cur) return false;
290
+ setScrollTop(id, next);
291
+ return true;
292
+ }
293
+ return false;
294
+ }
295
+
296
+ // Drop every piece of per-touch / per-fling state that points into the
297
+ // previous tree's nodes. Called by Tree::clear() on app switch so the
298
+ // next app's first frame doesn't get a momentum tick targeted at a
299
+ // stale node id, an activeScrollNode that points to nothing valid, or
300
+ // velocity samples from a touch the new app never saw.
301
+ void reset()
302
+ {
303
+ activeTouchNode_ = -1;
304
+ savedBackgroundColor_ = 0;
305
+ savedHasBackground_ = 0;
306
+ activeBackgroundColor_ = 0;
307
+ activeHasBackground_ = 0;
308
+ activeScrollNode_ = -1;
309
+ activeScrollAxis_ = ScrollAxis::None;
310
+ snapAccumDy_ = 0;
311
+ scrollLastX_ = 0;
312
+ scrollLastY_ = 0;
313
+ resetVelocitySamples();
314
+ cancelMomentum();
315
+ carryOverVelocity_ = 0.0f;
316
+ carryOverAxis_ = ScrollAxis::None;
317
+ }
318
+
319
+ void tick(int timestampMs)
320
+ {
321
+ if (momentumNode_ < 0) return;
322
+ Tree &tree = Tree::instance();
323
+ if (momentumNode_ >= tree.nodeCount()) {
324
+ cancelMomentum();
325
+ return;
326
+ }
327
+
328
+ Node &node = tree.nodes()[momentumNode_];
329
+ if (momentumAxis_ == ScrollAxis::None || !nodeCanScrollAxis(momentumNode_, node, momentumAxis_)) {
330
+ cancelMomentum();
331
+ return;
332
+ }
333
+
334
+ int dt = timestampMs - momentumLastTickMs_;
335
+ if (dt <= 0) return;
336
+ if (dt > 100) dt = 100; // clamp huge dt (paused tab, GC, etc.)
337
+ momentumLastTickMs_ = timestampMs;
338
+
339
+ // scroll -= velocity * dt (matches pointerMove convention:
340
+ // finger moving right/down → delta > 0 → scroll decreases → content follows finger).
341
+ momentumScrollAccum_ -= momentumVelocity_ * static_cast<float>(dt);
342
+
343
+ int wholePixels = static_cast<int>(momentumScrollAccum_);
344
+ momentumScrollAccum_ -= static_cast<float>(wholePixels);
345
+
346
+ if (wholePixels != 0) {
347
+ int next = momentumAxis_ == ScrollAxis::X ? scrollLeft(momentumNode_) + wholePixels
348
+ : scrollTop(momentumNode_) + wholePixels;
349
+ const int maxScroll = momentumAxis_ == ScrollAxis::X ? scrollMaxX(momentumNode_, node)
350
+ : scrollMaxY(momentumNode_, node);
351
+ bool clamped = false;
352
+ if (next < 0) {
353
+ next = 0;
354
+ clamped = true;
355
+ } else if (next > maxScroll) {
356
+ next = maxScroll;
357
+ clamped = true;
358
+ }
359
+ if (momentumAxis_ == ScrollAxis::X)
360
+ setScrollLeft(momentumNode_, next);
361
+ else
362
+ setScrollTop(momentumNode_, next);
363
+ // A <virtual-list>'s recycled slots stay in sync on the scroll-only
364
+ // fast path: RootScrollOnlyRefresh reconciles repositioned slot
365
+ // children natively (no layout pass) and replays their old/new
366
+ // rects, so momentum ticks no longer force the full-relayout path.
367
+ // (That forced `non_scroll_dirty` halved the frame rate during
368
+ // flings — 33-50ms full repaints — which read as scroll judder.)
369
+ if (scrollTraceEnabled())
370
+ std::fprintf(stderr, "[sc.fl] t=%d dt=%d v=%.3f px=%d s=%d%s\n",
371
+ timestampMs, dt, momentumVelocity_, wholePixels, next,
372
+ clamped ? " clamp" : "");
373
+ if (clamped) {
374
+ // Hit a boundary — kill the fling. (Could rubber-band here later.)
375
+ cancelMomentum();
376
+ return;
377
+ }
378
+ } else if (scrollTraceEnabled()) {
379
+ std::fprintf(stderr, "[sc.fl] t=%d dt=%d v=%.3f px=0\n", timestampMs, dt, momentumVelocity_);
380
+ }
381
+
382
+ // Exponential decay. Keep the time constant closer to iOS-style
383
+ // inertial scrolling: repeated flicks should build speed, and a long
384
+ // list should coast instead of stopping under heavy friction.
385
+ const float decay = std::exp(-static_cast<float>(dt) / kMomentumDecayMs);
386
+ momentumVelocity_ *= decay;
387
+
388
+ // Stop once velocity falls below a visible sub-pixel coast.
389
+ if (std::fabs(momentumVelocity_) < kStopVelocity) {
390
+ if (scrollTraceEnabled())
391
+ std::fprintf(stderr, "[sc.stop] t=%d\n", timestampMs);
392
+ cancelMomentum();
393
+ }
394
+ }
395
+
396
+ private:
397
+ InputController() = default;
398
+
399
+ void sortChildrenByZIndex(int *children, int childCount) const
400
+ {
401
+ Node *nodes = Tree::instance().nodes();
402
+ for (int i = 1; i < childCount; i++) {
403
+ const int key = children[i];
404
+ int j = i - 1;
405
+ while (j >= 0 && nodes[children[j]].style.z_index > nodes[key].style.z_index) {
406
+ children[j + 1] = children[j];
407
+ j--;
408
+ }
409
+ children[j + 1] = key;
410
+ }
411
+ }
412
+
413
+ static bool pointInsideNodeHitArea(const Node &node, int x, int y)
414
+ {
415
+ if (node.layout.width <= 0 || node.layout.height <= 0) return false;
416
+
417
+ int16_t xs[4], ys[4];
418
+ ViewRenderer::transformedRectCorners(node,
419
+ false,
420
+ node.layout.x,
421
+ node.layout.y,
422
+ node.layout.width,
423
+ node.layout.height,
424
+ xs,
425
+ ys);
426
+ int minX = xs[0];
427
+ int maxX = xs[0];
428
+ int minY = ys[0];
429
+ int maxY = ys[0];
430
+ for (int i = 1; i < 4; ++i) {
431
+ minX = std::min(minX, static_cast<int>(xs[i]));
432
+ maxX = std::max(maxX, static_cast<int>(xs[i]));
433
+ minY = std::min(minY, static_cast<int>(ys[i]));
434
+ maxY = std::max(maxY, static_cast<int>(ys[i]));
435
+ }
436
+ if (x < minX || x >= maxX || y < minY || y >= maxY) return false;
437
+
438
+ bool hasNegative = false;
439
+ bool hasPositive = false;
440
+ for (int i = 0; i < 4; ++i) {
441
+ const int j = (i + 1) & 3;
442
+ const std::int64_t edgeX = static_cast<std::int64_t>(xs[j]) - xs[i];
443
+ const std::int64_t edgeY = static_cast<std::int64_t>(ys[j]) - ys[i];
444
+ const std::int64_t pointX = static_cast<std::int64_t>(x) - xs[i];
445
+ const std::int64_t pointY = static_cast<std::int64_t>(y) - ys[i];
446
+ const std::int64_t cross = edgeX * pointY - edgeY * pointX;
447
+ if (cross < 0) hasNegative = true;
448
+ if (cross > 0) hasPositive = true;
449
+ if (hasNegative && hasPositive) return false;
450
+ }
451
+ return true;
452
+ }
453
+
454
+ int hitTestNodeId(int id, int x, int y)
455
+ {
456
+ Node &node = Tree::instance().nodes()[id];
457
+ if (node.style.display == 1) return -1;
458
+ // CSS `pointer-events: none` — this node and its subtree are never the
459
+ // target of a pointer event, so the hit-test falls through to whatever is
460
+ // painted behind it. Without this, a decorative overlay image positioned
461
+ // over interactive controls (e.g. the weather hero art over the city rail)
462
+ // swallows their clicks. Matches the browser/DOM build, which honors it.
463
+ if (node.style.pointer_events == 1) return -1;
464
+
465
+ const bool inside = pointInsideNodeHitArea(node, x, y);
466
+ if (!inside && node.style.overflow != 0) return -1;
467
+
468
+ int children[kMaxChildren];
469
+ const int childCount = LayoutEngine::instance().collectChildren(id, children, kMaxChildren, false);
470
+ sortChildrenByZIndex(children, childCount);
471
+
472
+ for (int i = childCount - 1; i >= 0; i--) {
473
+ const int result = hitTestNodeId(children[i], x, y);
474
+ if (result >= 0) return result;
475
+ }
476
+
477
+ if (!inside) return -1;
478
+ return id;
479
+ }
480
+
481
+ int findScrollNodeId(int id, int x, int y)
482
+ {
483
+ Node &node = Tree::instance().nodes()[id];
484
+ if (node.style.display == 1) return -1;
485
+
486
+ const bool inside = pointInsideNodeHitArea(node, x, y);
487
+ if (!inside && node.style.overflow != 0) return -1;
488
+
489
+ int children[kMaxChildren];
490
+ const int childCount = LayoutEngine::instance().collectChildren(id, children, kMaxChildren, false);
491
+ sortChildrenByZIndex(children, childCount);
492
+
493
+ for (int i = childCount - 1; i >= 0; i--) {
494
+ const int result = findScrollNodeId(children[i], x, y);
495
+ if (result >= 0) return result;
496
+ }
497
+
498
+ if (!inside) return -1;
499
+ const bool scrollableVirtualList = node.type == NodeType::VirtualList && VirtualListRenderer::scrollMaxY(id) > 0;
500
+ const bool scrollableView = node.type != NodeType::VirtualList && isViewLikeNodeType(node.type) &&
501
+ (nodeCanScrollX(id, node) || nodeCanScrollY(id, node));
502
+ return (scrollableVirtualList || scrollableView) ? id : -1;
503
+ }
504
+
505
+ static int scrollLeft(int nodeId)
506
+ {
507
+ Tree &tree = Tree::instance();
508
+ if (nodeId < 0 || nodeId >= tree.nodeCount()) return 0;
509
+ return tree.node(nodeId).type == NodeType::VirtualList ? 0 : tree.node(nodeId).layout.scroll_x;
510
+ }
511
+
512
+ static int scrollTop(int nodeId)
513
+ {
514
+ Tree &tree = Tree::instance();
515
+ if (nodeId < 0 || nodeId >= tree.nodeCount()) return 0;
516
+ return tree.node(nodeId).type == NodeType::VirtualList ? VirtualListRenderer::scrollTop(nodeId) : tree.node(nodeId).layout.scroll_y;
517
+ }
518
+
519
+ static int scrollMaxX(int nodeId, const Node &node)
520
+ {
521
+ (void)nodeId;
522
+ return node.type == NodeType::VirtualList ? 0 : ViewRenderer::scrollMaxX(node);
523
+ }
524
+
525
+ static int scrollMaxY(int nodeId, const Node &node)
526
+ {
527
+ return node.type == NodeType::VirtualList ? VirtualListRenderer::scrollMaxY(nodeId) : ViewRenderer::scrollMaxY(node);
528
+ }
529
+
530
+ static bool nodeCanScrollX(int nodeId, const Node &node)
531
+ {
532
+ (void)nodeId;
533
+ return node.type != NodeType::VirtualList && scrollsOverflowX(node.style) && ViewRenderer::scrollMaxX(node) > 0;
534
+ }
535
+
536
+ static bool nodeCanScrollY(int nodeId, const Node &node)
537
+ {
538
+ if (node.type == NodeType::VirtualList) return VirtualListRenderer::scrollMaxY(nodeId) > 0;
539
+ return scrollsOverflowY(node.style) && ViewRenderer::scrollMaxY(node) > 0;
540
+ }
541
+
542
+ static bool nodeCanScrollAxis(int nodeId, const Node &node, ScrollAxis axis)
543
+ {
544
+ if (axis == ScrollAxis::X) return nodeCanScrollX(nodeId, node);
545
+ if (axis == ScrollAxis::Y) return nodeCanScrollY(nodeId, node);
546
+ return false;
547
+ }
548
+
549
+ static void setScrollLeft(int nodeId, int next)
550
+ {
551
+ Tree &tree = Tree::instance();
552
+ if (nodeId < 0 || nodeId >= tree.nodeCount()) return;
553
+ Node &node = tree.node(nodeId);
554
+ if (node.type == NodeType::VirtualList) return;
555
+ if (next == node.layout.scroll_x) return;
556
+ node.layout.scroll_x = static_cast<int32_t>(next);
557
+ node.render.dirty = 1;
558
+ node.render.layout_dirty = 1;
559
+ // Horizontal scroll now has a scrollRect fast path (RootScrollOnlyRefresh
560
+ // handles either axis), so it no longer forces the full clipped-replay
561
+ // path via non_scroll_dirty — mirror the vertical setScrollTop path.
562
+ tree.markScrollDirty(nodeId);
563
+ }
564
+
565
+ static void setScrollTop(int nodeId, int next)
566
+ {
567
+ Tree &tree = Tree::instance();
568
+ if (nodeId < 0 || nodeId >= tree.nodeCount()) return;
569
+ if (tree.node(nodeId).type == NodeType::VirtualList) {
570
+ VirtualListRenderer::setScrollTop(nodeId, next);
571
+ return;
572
+ }
573
+ Node &node = tree.node(nodeId);
574
+ if (next == node.layout.scroll_y) return;
575
+ node.layout.scroll_y = static_cast<int32_t>(next);
576
+ node.render.dirty = 1;
577
+ node.render.layout_dirty = 1;
578
+ tree.markScrollDirty(nodeId);
579
+ }
580
+
581
+ static std::uint16_t lightenRgb565(std::uint16_t color)
582
+ {
583
+ int r;
584
+ int g;
585
+ int b;
586
+ gea::framework::graphics::pixel::unpackRgb565(color, &r, &g, &b);
587
+
588
+ r += ((31 - r) * 6) / 32;
589
+ g += ((63 - g) * 6) / 32;
590
+ b += ((31 - b) * 6) / 32;
591
+
592
+ return gea::framework::graphics::pixel::packRgb565Components(r, g, b);
593
+ }
594
+
595
+ static int findActiveTouchNodeId(int nodeId)
596
+ {
597
+ Tree &tree = Tree::instance();
598
+ for (int current = nodeId; current >= 0 && current < tree.nodeCount(); current = tree.node(current).parent) {
599
+ const Node &node = tree.node(current);
600
+ if (node.style.has_active_bg || (node.style.has_bg && isNativeButtonNodeType(node.type))) return current;
601
+ }
602
+ return -1;
603
+ }
604
+
605
+ static int pressTargetForNode(int nodeId)
606
+ {
607
+ Tree &tree = Tree::instance();
608
+ for (int current = nodeId; current >= 0 && current < tree.nodeCount(); current = tree.node(current).parent) {
609
+ const int pressId = tree.pressId(current);
610
+ if (pressId >= 0) return pressId;
611
+ }
612
+ return -1;
613
+ }
614
+
615
+ // A touched element (or any ancestor) that opts out of scrolling with a
616
+ // `touch-action="none"` attribute claims the whole gesture — e.g. a
617
+ // horizontal drag slider inside a vertical scroll list should set its value,
618
+ // not scroll the list. Stops the scroll system from claiming this touch.
619
+ static bool nodeChainDisablesScroll(int nodeId)
620
+ {
621
+ Tree &tree = Tree::instance();
622
+ for (int current = nodeId; current >= 0 && current < tree.nodeCount(); current = tree.node(current).parent) {
623
+ if (!tree.hasAttribute(current, "touch-action")) continue;
624
+ const char *v = tree.getAttribute(current, "touch-action");
625
+ if (v && std::strcmp(v, "none") == 0) return true;
626
+ }
627
+ return false;
628
+ }
629
+
630
+ bool clearActiveTouch()
631
+ {
632
+ if (activeTouchNode_ < 0) return false;
633
+
634
+ Node &node = Tree::instance().node(activeTouchNode_);
635
+ const bool ownsActiveBackground =
636
+ node.style.bg_color == activeBackgroundColor_ &&
637
+ node.style.has_bg == activeHasBackground_;
638
+ if (ownsActiveBackground) {
639
+ node.style.bg_color = savedBackgroundColor_;
640
+ node.style.has_bg = savedHasBackground_;
641
+ node.render.dirty = 1; // paint-only: press highlight restore
642
+ node.render.non_scroll_dirty = 1;
643
+ Tree::instance().markNodeDisplayCommandsDirty(activeTouchNode_);
644
+ }
645
+ activeTouchNode_ = -1;
646
+ activeBackgroundColor_ = 0;
647
+ activeHasBackground_ = 0;
648
+ return ownsActiveBackground;
649
+ }
650
+
651
+ // --- Momentum-scroll helpers ----------------------------------------
652
+
653
+ void pushVelocitySample(int x, int y)
654
+ {
655
+ velocitySamples_[velocitySampleNext_] =
656
+ VelocitySample{gea::framework::services::FrameScheduler::nowMs(), x, y};
657
+ velocitySampleNext_ = (velocitySampleNext_ + 1) % kVelocitySampleCount;
658
+ if (velocitySampleCount_ < kVelocitySampleCount) velocitySampleCount_++;
659
+ }
660
+
661
+ void resetVelocitySamples()
662
+ {
663
+ velocitySampleCount_ = 0;
664
+ velocitySampleNext_ = 0;
665
+ }
666
+
667
+ // Vertical row-snap opt-in: a positive integer `snap-step` attribute on the
668
+ // scrollable is the row pitch in px. 0 = no snapping (normal live scroll).
669
+ int nodeSnapStepY(int nodeId) const
670
+ {
671
+ Tree &tree = Tree::instance();
672
+ if (nodeId < 0 || nodeId >= tree.nodeCount()) return 0;
673
+ if (!tree.hasAttribute(nodeId, "snap-step")) return 0;
674
+ const char *attr = tree.getAttribute(nodeId, "snap-step");
675
+ if (!attr) return 0;
676
+ const int step = std::atoi(attr);
677
+ return step > 0 ? step : 0;
678
+ }
679
+
680
+ bool nodeHasMomentumOptIn(int nodeId) const
681
+ {
682
+ Tree &tree = Tree::instance();
683
+ // Momentum/fling is OPT-IN via the `momentum` attribute. The old
684
+ // fling-by-default behavior generated long tails of post-release scroll
685
+ // frames — on e-paper each one is a panel refresh, so an un-opted list
686
+ // kept repainting seconds after the finger lifted.
687
+ if (nodeId < 0 || nodeId >= tree.nodeCount()) return false;
688
+ if (!tree.hasAttribute(nodeId, "momentum")) return false;
689
+ const char *attr = tree.getAttribute(nodeId, "momentum");
690
+ if (!attr) return true;
691
+ if (std::strcmp(attr, "false") == 0) return false;
692
+ if (std::strcmp(attr, "0") == 0) return false;
693
+ return true;
694
+ }
695
+
696
+ void startMomentum(int scrollNode, ScrollAxis axis)
697
+ {
698
+ if (velocitySampleCount_ < 2) return;
699
+ if (axis == ScrollAxis::None) return;
700
+ Tree &tree = Tree::instance();
701
+ if (scrollNode < 0 || scrollNode >= tree.nodeCount()) return;
702
+ if (!nodeCanScrollAxis(scrollNode, tree.node(scrollNode), axis)) return;
703
+
704
+ // Average velocity from the oldest sample to the newest in the ring.
705
+ // Using two endpoints rather than a per-sample derivative smooths
706
+ // out the noisy last few touch reports right before lift-off.
707
+ const int newestIdx =
708
+ (velocitySampleNext_ + kVelocitySampleCount - 1) % kVelocitySampleCount;
709
+ const int oldestIdx =
710
+ velocitySampleCount_ < kVelocitySampleCount
711
+ ? 0
712
+ : velocitySampleNext_;
713
+ const VelocitySample &newest = velocitySamples_[newestIdx];
714
+ const VelocitySample &oldest = velocitySamples_[oldestIdx];
715
+ const int dtMs = newest.timestampMs - oldest.timestampMs;
716
+ if (dtMs <= 0) return;
717
+
718
+ const int nowMs = gea::framework::services::FrameScheduler::nowMs();
719
+
720
+ const int delta = axis == ScrollAxis::X ? newest.x - oldest.x : newest.y - oldest.y;
721
+ float velocityPxPerMs = static_cast<float>(delta) / static_cast<float>(dtMs);
722
+
723
+ // Below ~0.06 px/ms = 60 px/sec, the fling is so weak it'd stop in a
724
+ // frame or two — not worth the tick overhead and visually a no-op.
725
+ // A tap (no drag, weak velocity) also lands here, which is what we
726
+ // want: a tap should NOT resume a stashed fling.
727
+ if (std::fabs(velocityPxPerMs) < kMinFlingVelocity) {
728
+ if (scrollTraceEnabled())
729
+ std::fprintf(stderr, "[sc.start] t=%d reject v=%.3f win=%dms d=%d\n",
730
+ nowMs, velocityPxPerMs, dtMs, delta);
731
+ carryOverVelocity_ = 0.0f;
732
+ carryOverAxis_ = ScrollAxis::None;
733
+ return;
734
+ }
735
+
736
+ const float carryAtLaunch = carryOverVelocity_;
737
+ velocityPxPerMs *= kLaunchVelocityBoost;
738
+
739
+ // iOS "re-flick to accelerate": if there was an in-flight fling and
740
+ // the new flick goes in the same direction, add the leftover
741
+ // velocity to the new one. Opposite direction → user is reversing
742
+ // course, drop the stash.
743
+ if (carryOverAxis_ == axis && carryOverVelocity_ != 0.0f &&
744
+ (carryOverVelocity_ > 0.0f) == (velocityPxPerMs > 0.0f)) {
745
+ velocityPxPerMs += carryOverVelocity_ * kCarryOverBoost;
746
+ }
747
+ carryOverVelocity_ = 0.0f;
748
+ carryOverAxis_ = ScrollAxis::None;
749
+
750
+ // Cap absolute velocity so successive rapid flicks can't chain into
751
+ // an absurd speed. iOS can hit very high projected speeds; allow
752
+ // that headroom while still bounding pathological repeated flicks.
753
+ if (velocityPxPerMs > kMaxMomentumVelocity) velocityPxPerMs = kMaxMomentumVelocity;
754
+ else if (velocityPxPerMs < -kMaxMomentumVelocity) velocityPxPerMs = -kMaxMomentumVelocity;
755
+
756
+ momentumNode_ = scrollNode;
757
+ momentumAxis_ = axis;
758
+ momentumVelocity_ = velocityPxPerMs;
759
+ momentumLastTickMs_ = nowMs;
760
+ momentumScrollAccum_ = 0.0f;
761
+ treeState().inputTickRequired = true;
762
+ if (scrollTraceEnabled())
763
+ std::fprintf(stderr, "[sc.start] t=%d v=%.3f win=%dms d=%d carry=%.3f node=%d\n",
764
+ nowMs, velocityPxPerMs, dtMs, delta, carryAtLaunch, scrollNode);
765
+ }
766
+
767
+ void cancelMomentum()
768
+ {
769
+ momentumNode_ = -1;
770
+ momentumAxis_ = ScrollAxis::None;
771
+ momentumVelocity_ = 0.0f;
772
+ momentumScrollAccum_ = 0.0f;
773
+ treeState().inputTickRequired = false;
774
+ }
775
+
776
+ struct VelocitySample {
777
+ int timestampMs;
778
+ int x;
779
+ int y;
780
+ };
781
+ static constexpr int kVelocitySampleCount = 5;
782
+ static constexpr float kLaunchVelocityBoost = 1.45f;
783
+ static constexpr float kCarryOverBoost = 2.0f;
784
+ static constexpr float kMaxMomentumVelocity = 24.0f; // px/ms = 24000 px/s
785
+ static constexpr float kMinFlingVelocity = 0.06f; // px/ms = 60 px/s
786
+ static constexpr float kMomentumDecayMs = 680.0f;
787
+ static constexpr float kStopVelocity = 0.012f; // px/ms = 12 px/s
788
+
789
+ int activeTouchNode_ = -1;
790
+ std::uint16_t savedBackgroundColor_ = 0;
791
+ std::int8_t savedHasBackground_ = 0;
792
+ std::uint16_t activeBackgroundColor_ = 0;
793
+ std::int8_t activeHasBackground_ = 0;
794
+ int activeScrollNode_ = -1;
795
+ int snapAccumDy_ = 0;
796
+ ScrollAxis activeScrollAxis_ = ScrollAxis::None;
797
+ int scrollLastX_ = 0;
798
+ int scrollLastY_ = 0;
799
+
800
+ // Momentum-scroll state.
801
+ VelocitySample velocitySamples_[kVelocitySampleCount] = {};
802
+ int velocitySampleCount_ = 0;
803
+ int velocitySampleNext_ = 0;
804
+ int momentumNode_ = -1;
805
+ ScrollAxis momentumAxis_ = ScrollAxis::None;
806
+ float momentumVelocity_ = 0.0f; // px/ms in finger movement direction
807
+ int momentumLastTickMs_ = 0;
808
+ float momentumScrollAccum_ = 0.0f;
809
+
810
+ // Leftover fling velocity at the moment a new pointerDown lands.
811
+ // Folded into the next flick if same-direction so successive flicks
812
+ // accelerate (iOS-style).
813
+ float carryOverVelocity_ = 0.0f;
814
+ ScrollAxis carryOverAxis_ = ScrollAxis::None;
815
+ };
816
+
817
+ } // namespace
818
+
819
+ int Tree::hitTest(int x, int y)
820
+ {
821
+ return InputController::instance().hitTest(x, y);
822
+ }
823
+
824
+ int Tree::hitTestNode(int x, int y)
825
+ {
826
+ return InputController::instance().hitTestNode(x, y);
827
+ }
828
+
829
+ void Tree::pointerDown(int x, int y)
830
+ {
831
+ InputController::instance().pointerDown(x, y);
832
+ }
833
+
834
+ int Tree::pointerMove(int x, int y)
835
+ {
836
+ return InputController::instance().pointerMove(x, y);
837
+ }
838
+
839
+ int Tree::pointerUp()
840
+ {
841
+ return InputController::instance().pointerUp();
842
+ }
843
+
844
+ bool Tree::scrollByKeyStep(int dy)
845
+ {
846
+ return InputController::instance().scrollFirstContainerY(dy);
847
+ }
848
+
849
+ void Tree::tickInput(int timestampMs)
850
+ {
851
+ InputController::instance().tick(timestampMs);
852
+ }
853
+
854
+ void Tree::resetInput()
855
+ {
856
+ InputController::instance().reset();
857
+ }
858
+
859
+ int Tree::activeInputId() const
860
+ {
861
+ return treeState().activeInputId;
862
+ }
863
+
864
+ void Tree::setActiveInput(int nodeId)
865
+ {
866
+ auto &state = treeState();
867
+ if (nodeId < -1 || nodeId >= state.nodeCount) nodeId = -1;
868
+ if (state.activeInputId == nodeId) return;
869
+ const int previousId = state.activeInputId;
870
+ state.activeInputId = nodeId;
871
+ state.caretVisible = true;
872
+ state.caretLastFlipMs = state.lastFrameMs;
873
+ // Both the old input (caret needs to disappear) and the new input
874
+ // (caret needs to appear) must be re-recorded AND their screen rects
875
+ // flushed. Without render.dirty + nodeCommandDirty the rebuilt
876
+ // display list drops/adds the caret command but the dirty-region
877
+ // tracker leaves the old pixels on the panel.
878
+ auto markInputDirty = [&](int id) {
879
+ if (id < 0 || id >= state.nodeCount) return;
880
+ Node &n = state.nodes[id];
881
+ n.render.dirty = 1;
882
+ n.render.layout_dirty = 1;
883
+ n.render.non_scroll_dirty = 1;
884
+ state.nodeCommandDirty[id] = 1;
885
+ };
886
+ markInputDirty(previousId);
887
+ markInputDirty(nodeId);
888
+ // NOTE: previously this also flipped `inputTickRequired` to mirror the
889
+ // keyboard-active state. That field belongs to the momentum-scroll
890
+ // InputController — touching it from here was canceling in-flight scroll
891
+ // ticks every time a Press landed on a non-input, which broke tap
892
+ // responsiveness on ESP32. The caret has its own redraw signal via
893
+ // `displayListDirty`; the keyboard subsystem decides activity in
894
+ // notifyActiveInputChanged.
895
+ state.displayListDirty = true;
896
+ }
897
+
898
+ bool Tree::activeInputCaretVisible() const
899
+ {
900
+ return treeState().caretVisible;
901
+ }
902
+
903
+ void Tree::tickInputCaret(int timestampMs)
904
+ {
905
+ auto &state = treeState();
906
+ if (state.activeInputId < 0) {
907
+ state.caretVisible = false;
908
+ return;
909
+ }
910
+ constexpr int kCaretBlinkMs = 500;
911
+ if (state.caretLastFlipMs == 0) state.caretLastFlipMs = timestampMs;
912
+ if (timestampMs - state.caretLastFlipMs >= kCaretBlinkMs) {
913
+ state.caretVisible = !state.caretVisible;
914
+ state.caretLastFlipMs = timestampMs;
915
+ // Three flags, all required:
916
+ // - nodeCommandDirty: tells the direct-replay path that this
917
+ // node needs re-recording on the next refresh
918
+ // - displayListDirty: forces a full rebuild (skipping direct-
919
+ // replay) — InputRenderer reads activeInputCaretVisible
920
+ // fresh on each record so we always get the latest blink
921
+ // phase in the output DrawText / FillRect commands
922
+ // - render.dirty + non_scroll_dirty: tells the per-frame
923
+ // dirty-region tracker that the input's rect needs to be
924
+ // pushed to the panel. Without this the commands change
925
+ // but the screen doesn't (the framework decides the
926
+ // bounding box hasn't moved so nothing needs to flush).
927
+ state.nodeCommandDirty[state.activeInputId] = 1;
928
+ state.displayListDirty = true;
929
+ Node &n = state.nodes[state.activeInputId];
930
+ n.render.dirty = 1;
931
+ n.render.layout_dirty = 1;
932
+ n.render.non_scroll_dirty = 1;
933
+ }
934
+ }
935
+
936
+ } // namespace gea::embedded::ui