@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/text.cpp ADDED
@@ -0,0 +1,2010 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #include "internal.h"
3
+ #include "display.h"
4
+ #include "graphics/font.h"
5
+ #include "refresh_perf.h"
6
+ #include "tree_state.h"
7
+
8
+ #include <algorithm>
9
+ #include <cctype>
10
+ #include <cmath>
11
+ #include <cstdint>
12
+ #include <cstdio>
13
+ #include <cstdlib>
14
+ #include <cstring>
15
+ #include <string>
16
+
17
+ #ifndef GEA_EMBEDDED_RENDER_HOT_SRAM
18
+ #define GEA_EMBEDDED_RENDER_HOT_SRAM 0
19
+ #endif
20
+
21
+ #if GEA_EMBEDDED_RENDER_HOT_SRAM
22
+ #define GEA_TEXT_HOT_SRAM __attribute__((noinline, noclone, section(".time_critical.gea_text.record")))
23
+ #else
24
+ #define GEA_TEXT_HOT_SRAM
25
+ #endif
26
+
27
+ namespace gea::embedded::ui {
28
+
29
+ namespace {
30
+
31
+ struct ScopedRefreshStat
32
+ {
33
+ std::int64_t start;
34
+ std::int64_t &slot;
35
+
36
+ explicit ScopedRefreshStat(std::int64_t &slot)
37
+ : start(refreshPerfNowUs()), slot(slot)
38
+ {
39
+ }
40
+
41
+ ~ScopedRefreshStat()
42
+ {
43
+ slot += refreshPerfNowUs() - start;
44
+ }
45
+ };
46
+
47
+ bool hasTransformState(const Node &node)
48
+ {
49
+ return rstyle(node.style).transform_rotate != 0 ||
50
+ node.render.previous_transform_rotate != 0 ||
51
+ rstyle(node.style).transform_rotate_x != 0 ||
52
+ node.render.previous_transform_rotate_x != 0 ||
53
+ rstyle(node.style).transform_rotate_y != 0 ||
54
+ node.render.previous_transform_rotate_y != 0 ||
55
+ rstyle(node.style).transform_translate_x != 0 ||
56
+ node.render.previous_transform_translate_x != 0 ||
57
+ rstyle(node.style).transform_translate_y != 0 ||
58
+ node.render.previous_transform_translate_y != 0 ||
59
+ rstyle(node.style).transform_translate_z != 0 ||
60
+ node.render.previous_transform_translate_z != 0 ||
61
+ rstyle(node.style).transform_translate_x_percent != 0 ||
62
+ node.render.previous_transform_translate_x_percent != 0 ||
63
+ rstyle(node.style).transform_translate_y_percent != 0 ||
64
+ node.render.previous_transform_translate_y_percent != 0 ||
65
+ rstyle(node.style).transform_scale_x != 1000 ||
66
+ node.render.previous_transform_scale_x != 1000 ||
67
+ rstyle(node.style).transform_scale_y != 1000 ||
68
+ node.render.previous_transform_scale_y != 1000 ||
69
+ rstyle(node.style).perspective > 0 ||
70
+ node.render.previous_perspective > 0;
71
+ }
72
+
73
+ constexpr int kBitmapFontWidth = gea::framework::graphics::BitmapFont8x16::kWidth;
74
+ constexpr int kBitmapFontHeight = gea::framework::graphics::BitmapFont8x16::kHeight;
75
+ constexpr int kWrappedLineBufferBytes = 512;
76
+
77
+ // Line-break cache for TextDrawer. drawRasterizedWrapped / drawBitmapWrapped
78
+ // previously iterated every line of a text command in their inner per-char
79
+ // glyph-advance loop just to find where each line ends — even for lines that
80
+ // would be skipped by the Y-clip check. With many text commands re-rendered
81
+ // each scroll frame (typography uses ~40 paragraphs of varied font specimens)
82
+ // and per-chunk streaming replaying the same command across multiple chunks,
83
+ // this per-line layout work piles up.
84
+ //
85
+ // The cache stores chars-per-line + lineWidth-per-line for the most recently
86
+ // laid-out text commands, keyed by (text_ptr, content fingerprint, maxWidth,
87
+ // fontId, fontSize, lineHeight, scale_times_256). On hit, the inner glyph-
88
+ // advance loop is skipped entirely — the renderer iterates the cached chars[]
89
+ // array and only emits draw calls for in-clip lines.
90
+ //
91
+ // Direct-mapped by a hash of text_ptr; collisions overwrite. Capped at 64
92
+ // lines per entry — text commands with more lines fall back to the original
93
+ // uncached path (a paragraph that long would already be unusual for a
94
+ // 502-px-tall display).
95
+ #ifndef GEA_EMBEDDED_LINE_BREAK_CACHE_SLOTS
96
+ #define GEA_EMBEDDED_LINE_BREAK_CACHE_SLOTS 16
97
+ #endif
98
+ #ifndef GEA_EMBEDDED_LINE_BREAK_CACHE_LINES
99
+ #define GEA_EMBEDDED_LINE_BREAK_CACHE_LINES 64
100
+ #endif
101
+
102
+ constexpr int kLineBreakCacheSlots = GEA_EMBEDDED_LINE_BREAK_CACHE_SLOTS; // must be power of two
103
+ constexpr int kMaxCachedLines = GEA_EMBEDDED_LINE_BREAK_CACHE_LINES;
104
+ static_assert(kLineBreakCacheSlots > 0);
105
+ static_assert((kLineBreakCacheSlots & (kLineBreakCacheSlots - 1)) == 0);
106
+ static_assert(kMaxCachedLines > 0);
107
+
108
+ struct LineBreakCacheEntry {
109
+ const char *textPtr = nullptr;
110
+ std::uint32_t textHashPrefix = 0;
111
+ int maxWidth = -1;
112
+ // The first line of an inline continuation gets a different budget and origin
113
+ // than the rest, so two runs of the same string at the same maxWidth can break
114
+ // differently — the indent is part of the key.
115
+ int firstLineIndent = 0;
116
+ int fontId = -2;
117
+ int fontSize = -1;
118
+ int lineHeight = 0;
119
+ int scaleQ8 = 0; // scale * 256, integer key for bitmap-font variant
120
+ int lineCount = 0;
121
+ std::uint16_t renderBytes[kMaxCachedLines];
122
+ std::uint16_t consumedBytes[kMaxCachedLines];
123
+ std::uint16_t lineWidths[kMaxCachedLines];
124
+ };
125
+
126
+ LineBreakCacheEntry gLineBreakCache[kLineBreakCacheSlots];
127
+
128
+ inline std::uint32_t hashTextPrefix(const char *text)
129
+ {
130
+ // 32-bit FNV-1a over first 16 bytes (or up to NUL). Cheap and good
131
+ // enough to disambiguate text-mutations on the same buffer.
132
+ std::uint32_t h = 2166136261u;
133
+ for (int i = 0; i < 16; i++) {
134
+ const unsigned char c = static_cast<unsigned char>(text[i]);
135
+ if (!c) break;
136
+ h ^= c;
137
+ h *= 16777619u;
138
+ }
139
+ return h;
140
+ }
141
+
142
+ inline int lineBreakCacheSlot(const char *text, int maxWidth)
143
+ {
144
+ auto ptr = reinterpret_cast<std::uintptr_t>(text);
145
+ std::uint32_t mix = static_cast<std::uint32_t>(ptr) ^ static_cast<std::uint32_t>(ptr >> 16);
146
+ mix ^= static_cast<std::uint32_t>(maxWidth);
147
+ mix *= 0x9e3779b1u;
148
+ return static_cast<int>(mix & (kLineBreakCacheSlots - 1));
149
+ }
150
+
151
+ inline int textDecorationThickness(int fontSize)
152
+ {
153
+ if (fontSize <= 0) fontSize = kBitmapFontHeight;
154
+ int thickness = (fontSize + 11) / 12;
155
+ return thickness < 1 ? 1 : thickness;
156
+ }
157
+
158
+ inline int textDecorationY(int textTop, int fontSize, int thickness, int decoration)
159
+ {
160
+ if (fontSize <= 0) fontSize = kBitmapFontHeight;
161
+ int center = textTop;
162
+ if (decoration == 2)
163
+ center = textTop + (fontSize * 62 + 50) / 100;
164
+ else if (decoration == 1)
165
+ center = textTop + (fontSize * 88 + 50) / 100;
166
+
167
+ int y = center - thickness / 2;
168
+ if (y < textTop) y = textTop;
169
+ const int maxY = textTop + fontSize - thickness;
170
+ if (y > maxY) y = maxY;
171
+ return y;
172
+ }
173
+
174
+ inline int minInt(int a, int b)
175
+ {
176
+ return a < b ? a : b;
177
+ }
178
+
179
+ inline int maxInt(int a, int b)
180
+ {
181
+ return a > b ? a : b;
182
+ }
183
+
184
+ inline int roundedHalf(int value)
185
+ {
186
+ return value >= 0 ? (value + 1) / 2 : (value - 1) / 2;
187
+ }
188
+
189
+ inline float clampFloat(float value, float minValue, float maxValue)
190
+ {
191
+ if (value < minValue) return minValue;
192
+ if (value > maxValue) return maxValue;
193
+ return value;
194
+ }
195
+
196
+ bool currentTransformChainIsPureTranslate(const Node &node, float *outX, float *outY)
197
+ {
198
+ const Tree &tree = Tree::instance();
199
+ const Node *nodes = tree.nodes();
200
+ const int count = tree.nodeCount();
201
+ int id = -1;
202
+ if (nodes && &node >= nodes && &node < nodes + count)
203
+ id = static_cast<int>(&node - nodes);
204
+
205
+ float dx = 0.0f;
206
+ float dy = 0.0f;
207
+ bool anyTranslate = false;
208
+ for (;;) {
209
+ const Node &n = id >= 0 ? tree.node(id) : node;
210
+ if ((rstyle(n.style).transform_rotate % 3600) != 0 ||
211
+ (rstyle(n.style).transform_rotate_x % 3600) != 0 ||
212
+ (rstyle(n.style).transform_rotate_y % 3600) != 0 ||
213
+ rstyle(n.style).transform_translate_z != 0 ||
214
+ rstyle(n.style).transform_scale_x != 1000 ||
215
+ rstyle(n.style).transform_scale_y != 1000 ||
216
+ rstyle(n.style).perspective > 0)
217
+ return false;
218
+
219
+ const float localDx = static_cast<float>(rstyle(n.style).transform_translate_x) +
220
+ static_cast<float>(n.layout.width) * static_cast<float>(rstyle(n.style).transform_translate_x_percent) * 0.001f;
221
+ const float localDy = static_cast<float>(rstyle(n.style).transform_translate_y) +
222
+ static_cast<float>(n.layout.height) * static_cast<float>(rstyle(n.style).transform_translate_y_percent) * 0.001f;
223
+ if (localDx != 0.0f || localDy != 0.0f) {
224
+ anyTranslate = true;
225
+ dx += localDx;
226
+ dy += localDy;
227
+ }
228
+
229
+ if (id < 0) break;
230
+ id = n.parent;
231
+ if (id < 0 || id >= count) break;
232
+ }
233
+
234
+ if (!anyTranslate) return false;
235
+ if (outX) *outX = dx;
236
+ if (outY) *outY = dy;
237
+ return true;
238
+ }
239
+
240
+ inline int translateCoord(int value, float delta)
241
+ {
242
+ return static_cast<int>(std::lroundf(static_cast<float>(value) + delta));
243
+ }
244
+
245
+ uint8_t combineAlpha(uint8_t parentAlpha, uint8_t localAlpha)
246
+ {
247
+ return static_cast<uint8_t>((static_cast<int>(parentAlpha) * static_cast<int>(localAlpha) + 127) / 255);
248
+ }
249
+
250
+ void appendAlphaCommand(uint8_t alpha, int bx, int by, int bw, int bh)
251
+ {
252
+ DisplayCommand *cmd = DisplayList::instance().append();
253
+ if (!cmd) return;
254
+ cmd->type = DisplayCommandType::SetAlpha;
255
+ cmd->bx = bx; cmd->by = by; cmd->bw = bw; cmd->bh = bh;
256
+ cmd->alpha.alpha = alpha;
257
+ }
258
+
259
+ void boundsFromCorners(const int16_t *xs, const int16_t *ys, int *x0, int *y0, int *x1, int *y1)
260
+ {
261
+ *x0 = *x1 = xs[0];
262
+ *y0 = *y1 = ys[0];
263
+ for (int i = 1; i < 4; i++) {
264
+ if (xs[i] < *x0) *x0 = xs[i];
265
+ if (xs[i] > *x1) *x1 = xs[i];
266
+ if (ys[i] < *y0) *y0 = ys[i];
267
+ if (ys[i] > *y1) *y1 = ys[i];
268
+ }
269
+ }
270
+
271
+ int alignedOffset(int textAlign, int containerWidth, int lineWidth)
272
+ {
273
+ int offset = 0;
274
+ if (textAlign == 1) offset = (containerWidth - lineWidth) / 2;
275
+ else if (textAlign == 2) offset = containerWidth - lineWidth;
276
+ return offset < 0 ? 0 : offset;
277
+ }
278
+
279
+ inline bool isAsciiWordChar(unsigned char c)
280
+ {
281
+ return std::isalnum(c) != 0;
282
+ }
283
+
284
+ int nextUtf8Codepoint(const char *&p)
285
+ {
286
+ const unsigned char c0 = static_cast<unsigned char>(*p++);
287
+ if (c0 < 0x80) return c0;
288
+
289
+ const auto isContinuation = [](unsigned char c) {
290
+ return (c & 0xc0) == 0x80;
291
+ };
292
+ if ((c0 & 0xe0) == 0xc0) {
293
+ const unsigned char c1 = static_cast<unsigned char>(*p);
294
+ if (c1 && isContinuation(c1)) {
295
+ ++p;
296
+ return ((c0 & 0x1f) << 6) | (c1 & 0x3f);
297
+ }
298
+ return c0;
299
+ }
300
+ if ((c0 & 0xf0) == 0xe0) {
301
+ const unsigned char c1 = static_cast<unsigned char>(p[0]);
302
+ const unsigned char c2 = static_cast<unsigned char>(p[1]);
303
+ if (c1 && c2 && isContinuation(c1) && isContinuation(c2)) {
304
+ p += 2;
305
+ return ((c0 & 0x0f) << 12) | ((c1 & 0x3f) << 6) | (c2 & 0x3f);
306
+ }
307
+ return c0;
308
+ }
309
+ if ((c0 & 0xf8) == 0xf0) {
310
+ const unsigned char c1 = static_cast<unsigned char>(p[0]);
311
+ const unsigned char c2 = static_cast<unsigned char>(p[1]);
312
+ const unsigned char c3 = static_cast<unsigned char>(p[2]);
313
+ if (c1 && c2 && c3 && isContinuation(c1) && isContinuation(c2) && isContinuation(c3)) {
314
+ p += 3;
315
+ return ((c0 & 0x07) << 18) | ((c1 & 0x3f) << 12) | ((c2 & 0x3f) << 6) | (c3 & 0x3f);
316
+ }
317
+ }
318
+ return c0;
319
+ }
320
+
321
+ struct WrappedLine {
322
+ int renderBytes = 0;
323
+ int consumedBytes = 0;
324
+ int width = 0;
325
+ // True when the line had to cut a word open because no break opportunity fit.
326
+ // An inline formatting context uses this to move a run that cannot start on
327
+ // the space left to the next line box, instead of splitting "technical" into
328
+ // "t" + "echnical".
329
+ bool hardSplit = false;
330
+ };
331
+
332
+ inline bool isWrappingSpace(int cp)
333
+ {
334
+ // NBSP deliberately is not included: it is a word-joining space.
335
+ return cp == ' ' || cp == '\t' || cp == '\r' || cp == '\f';
336
+ }
337
+
338
+ inline bool canBreakAfter(int cp)
339
+ {
340
+ return cp == '-' || cp == '/' || cp == 0x2010 || cp == 0x2013 || cp == 0x2014;
341
+ }
342
+
343
+ // CSS white-space: normal/pre-line line breaking for the embedded renderer.
344
+ // Prefer the last legal word boundary; only split a word when that single word
345
+ // is wider than the line. `consumedBytes` includes discarded wrapping spaces or
346
+ // an explicit newline, while `renderBytes` contains only the visible run.
347
+ template <typename AdvanceForCodepoint>
348
+ WrappedLine nextWrappedLine(const char *text, int maxWidth, AdvanceForCodepoint advanceForCodepoint)
349
+ {
350
+ WrappedLine line{};
351
+ if (!text || !*text) return line;
352
+ if (maxWidth <= 0) maxWidth = 32767;
353
+
354
+ const char *p = text;
355
+ int width = 0;
356
+ int bytes = 0;
357
+ int breakRenderBytes = -1;
358
+ int breakConsumedBytes = -1;
359
+ int breakWidth = 0;
360
+ bool extendingSpaceBreak = false;
361
+
362
+ while (*p) {
363
+ const char *glyphStart = p;
364
+ const int cp = nextUtf8Codepoint(p);
365
+ const int glyphBytes = static_cast<int>(p - glyphStart);
366
+ if (cp == '\n') {
367
+ line.renderBytes = bytes;
368
+ line.consumedBytes = bytes + glyphBytes;
369
+ line.width = width;
370
+ return line;
371
+ }
372
+
373
+ const int advance = advanceForCodepoint(cp);
374
+ // A collapsible space at the end of a line HANGS: CSS trims it when the
375
+ // line is positioned, so it never overflows and never forces the break
376
+ // itself. Letting it break the line makes this wrapper non-idempotent —
377
+ // re-wrapping a run at the max line width it just produced pushes the
378
+ // last word off that line (its width is exactly maxWidth, so the space
379
+ // behind it "overflows"). Layout depends on idempotence: TextRenderer::
380
+ // layout stores the measured max line width as layout.width and the
381
+ // renderer re-wraps the run at that width, so a disagreement drew one
382
+ // more line than the box was tall and the run overlapped its next
383
+ // sibling (typography's specimen paragraphs).
384
+ if (!isWrappingSpace(cp) && width + advance > maxWidth && bytes > 0) {
385
+ if (breakRenderBytes >= 0) {
386
+ line.renderBytes = breakRenderBytes;
387
+ line.consumedBytes = breakConsumedBytes;
388
+ line.width = breakWidth;
389
+ } else {
390
+ line.renderBytes = bytes;
391
+ line.consumedBytes = bytes;
392
+ line.width = width;
393
+ line.hardSplit = true;
394
+ }
395
+ return line;
396
+ }
397
+
398
+ const int widthBefore = width;
399
+ const int bytesBefore = bytes;
400
+ width += advance;
401
+ bytes += glyphBytes;
402
+
403
+ if (isWrappingSpace(cp)) {
404
+ if (!extendingSpaceBreak) {
405
+ breakRenderBytes = bytesBefore;
406
+ breakWidth = widthBefore;
407
+ }
408
+ breakConsumedBytes = bytes;
409
+ extendingSpaceBreak = true;
410
+ } else {
411
+ extendingSpaceBreak = false;
412
+ if (canBreakAfter(cp)) {
413
+ breakRenderBytes = bytes;
414
+ breakConsumedBytes = bytes;
415
+ breakWidth = width;
416
+ }
417
+ }
418
+ }
419
+
420
+ line.renderBytes = bytes;
421
+ line.consumedBytes = bytes;
422
+ line.width = width;
423
+ return line;
424
+ }
425
+
426
+ void appendUtf8(std::string &out, int cp)
427
+ {
428
+ if (cp < 0) return;
429
+ if (cp <= 0x7f) {
430
+ out.push_back(static_cast<char>(cp));
431
+ } else if (cp <= 0x7ff) {
432
+ out.push_back(static_cast<char>(0xc0 | ((cp >> 6) & 0x1f)));
433
+ out.push_back(static_cast<char>(0x80 | (cp & 0x3f)));
434
+ } else if (cp <= 0xffff) {
435
+ out.push_back(static_cast<char>(0xe0 | ((cp >> 12) & 0x0f)));
436
+ out.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3f)));
437
+ out.push_back(static_cast<char>(0x80 | (cp & 0x3f)));
438
+ } else if (cp <= 0x10ffff) {
439
+ out.push_back(static_cast<char>(0xf0 | ((cp >> 18) & 0x07)));
440
+ out.push_back(static_cast<char>(0x80 | ((cp >> 12) & 0x3f)));
441
+ out.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3f)));
442
+ out.push_back(static_cast<char>(0x80 | (cp & 0x3f)));
443
+ }
444
+ }
445
+
446
+ int transformedTextCodepoint(int cp, int textTransform, bool &wordStart)
447
+ {
448
+ if (cp < 0 || cp > 0x7f) {
449
+ if (textTransform == 3) wordStart = true;
450
+ return cp;
451
+ }
452
+ const unsigned char uc = static_cast<unsigned char>(cp);
453
+ if (textTransform == 1) return static_cast<char>(std::toupper(uc));
454
+ if (textTransform == 2) return static_cast<char>(std::tolower(uc));
455
+ if (textTransform == 3) {
456
+ if (!isAsciiWordChar(uc)) {
457
+ wordStart = true;
458
+ return cp;
459
+ }
460
+ const int out = wordStart
461
+ ? std::toupper(uc)
462
+ : std::tolower(uc);
463
+ wordStart = false;
464
+ return out;
465
+ }
466
+ return cp;
467
+ }
468
+
469
+ std::string transformedTextCopy(const char *text, int textTransform)
470
+ {
471
+ std::string out;
472
+ if (!text || !text[0] || textTransform == 0) return out;
473
+ out.reserve(std::strlen(text));
474
+ bool wordStart = true;
475
+ for (const char *p = text; *p;) {
476
+ const int cp = nextUtf8Codepoint(p);
477
+ appendUtf8(out, transformedTextCodepoint(cp, textTransform, wordStart));
478
+ }
479
+ return out;
480
+ }
481
+
482
+ const char *textWithTransform(const char *text, int textTransform, std::string &storage)
483
+ {
484
+ if (!text || textTransform == 0) return text;
485
+ storage = transformedTextCopy(text, textTransform);
486
+ return storage.c_str();
487
+ }
488
+
489
+ struct TextMeasure {
490
+ int width = 0;
491
+ int height = 0;
492
+ };
493
+
494
+ struct TextLayoutMeasure {
495
+ int width = 0;
496
+ int height = 0;
497
+ };
498
+
499
+ #ifdef GEA_EMBEDDED_HAS_GENERATED_FONTS
500
+ bool rasterizedTextInkBounds(const char *text,
501
+ int maxWidth,
502
+ int textAlign,
503
+ int containerWidth,
504
+ int fontId,
505
+ int fontSize,
506
+ int lineHeight,
507
+ int *outX0,
508
+ int *outY0,
509
+ int *outX1,
510
+ int *outY1)
511
+ {
512
+ if (!text || !text[0] || !outX0 || !outY0 || !outX1 || !outY1) return false;
513
+ gea::framework::graphics::RasterizedFont font =
514
+ gea::framework::graphics::FontRegistry::rasterizedFamily(fontId, fontSize);
515
+ if (!font.valid()) return false;
516
+ if (maxWidth <= 0) maxWidth = 32767;
517
+
518
+ const int fontLineHeight = font.lineHeight();
519
+ const int lineAdvance = lineHeight > 0 ? lineHeight : fontLineHeight;
520
+ const int lineBoxOffset = lineHeight > 0 ? (lineAdvance - fontLineHeight) / 2 : 0;
521
+ bool any = false;
522
+ int bx0 = 0;
523
+ int by0 = 0;
524
+ int bx1 = -1;
525
+ int by1 = -1;
526
+ const char *lineStart = text;
527
+ int penY = 0;
528
+ while (*lineStart) {
529
+ const WrappedLine line = nextWrappedLine(lineStart, maxWidth, [&](int cp) {
530
+ gea::framework::graphics::Glyph glyph{};
531
+ return font.glyph(cp, &glyph) ? glyph.advance : (font.sizePx() / 2);
532
+ });
533
+
534
+ int penX = alignedOffset(textAlign, containerWidth, line.width);
535
+ const int lineY = penY + lineBoxOffset;
536
+ const char *glyphPtr = lineStart;
537
+ int consumed = 0;
538
+ while (consumed < line.renderBytes) {
539
+ const char *glyphStart = glyphPtr;
540
+ const int cp = nextUtf8Codepoint(glyphPtr);
541
+ consumed += static_cast<int>(glyphPtr - glyphStart);
542
+ gea::framework::graphics::Glyph glyph{};
543
+ if (!font.glyph(cp, &glyph)) {
544
+ penX += font.sizePx() / 2;
545
+ continue;
546
+ }
547
+ const int gx0 = penX + glyph.bearingX;
548
+ const int gy0 = lineY + font.ascender() - glyph.bearingY;
549
+ const int gx1 = gx0 + glyph.width - 1;
550
+ const int gy1 = gy0 + glyph.height - 1;
551
+ if (!any) {
552
+ bx0 = gx0;
553
+ by0 = gy0;
554
+ bx1 = gx1;
555
+ by1 = gy1;
556
+ any = true;
557
+ } else {
558
+ if (gx0 < bx0) bx0 = gx0;
559
+ if (gy0 < by0) by0 = gy0;
560
+ if (gx1 > bx1) bx1 = gx1;
561
+ if (gy1 > by1) by1 = gy1;
562
+ }
563
+ penX += glyph.advance;
564
+ }
565
+
566
+ lineStart += line.consumedBytes;
567
+ penY += lineAdvance;
568
+ }
569
+ if (!any) return false;
570
+ *outX0 = bx0;
571
+ *outY0 = by0;
572
+ *outX1 = bx1;
573
+ *outY1 = by1;
574
+ return true;
575
+ }
576
+
577
+ // The vertical ink extent of a FONT: how far above the baseline its tallest
578
+ // glyph reaches and how far below its deepest one does. Every run drawn in this
579
+ // font shares these two numbers, which is the whole point — see the comment on
580
+ // rasterizedSingleLineInkCenterOffsetY.
581
+ //
582
+ // Probed through Font::glyph rather than read out of RasterizedFontData::glyphs
583
+ // so a runtime-rasterized font fills its metrics on demand exactly as a paint
584
+ // would. ASCII is the alphabet that decides it: a cap and a descender are all
585
+ // the extremes are, and a font whose Latin letters fit its own ascender and
586
+ // descender is every font we ship.
587
+ struct FontInkExtent {
588
+ int above = 0; // rows of ink above the baseline
589
+ int below = 0; // rows of ink below it
590
+ bool valid = false;
591
+ };
592
+
593
+ FontInkExtent rasterizedFontInkExtent(const gea::framework::graphics::RasterizedFont &font)
594
+ {
595
+ // Paint calls this per text node per frame; the answer is a constant of the
596
+ // font, so a handful of entries keyed on the font data pointer keeps the
597
+ // 95-glyph probe off the frame.
598
+ struct Entry {
599
+ const gea::framework::graphics::RasterizedFontData *key = nullptr;
600
+ FontInkExtent extent{};
601
+ };
602
+ static Entry cache[8];
603
+ static int next = 0;
604
+
605
+ const gea::framework::graphics::RasterizedFontData *key = font.data();
606
+ if (!key) return {};
607
+ for (const Entry &entry : cache)
608
+ if (entry.key == key) return entry.extent;
609
+
610
+ FontInkExtent extent{};
611
+ for (int cp = 0x21; cp <= 0x7e; ++cp) {
612
+ gea::framework::graphics::Glyph glyph{};
613
+ if (!font.glyph(cp, &glyph) || glyph.width <= 0 || glyph.height <= 0) continue;
614
+ const int above = glyph.bearingY;
615
+ const int below = glyph.height - glyph.bearingY;
616
+ if (!extent.valid || above > extent.above) extent.above = above;
617
+ if (!extent.valid || below > extent.below) extent.below = below;
618
+ extent.valid = true;
619
+ }
620
+ if (!extent.valid) return extent;
621
+
622
+ cache[next].key = key;
623
+ cache[next].extent = extent;
624
+ next = (next + 1) % static_cast<int>(sizeof(cache) / sizeof(cache[0]));
625
+ return extent;
626
+ }
627
+
628
+ // How far to move a single-line run so its ink sits centred in the line box.
629
+ //
630
+ // Centred on the FONT's ink, never on the run's own. Centring each run on the
631
+ // glyphs it happens to contain gives every string its own baseline: "Comp" and
632
+ // "Delay" carry a descender, so their ink box is taller and its centre sits
633
+ // lower relative to the baseline, and centring it lifts them; "Gate", "Drive"
634
+ // and "Mod" have none and stay put. Side by side in a row — a pedal chain, a
635
+ // tab bar, a table header — that reads as a two-pixel stagger with no cause the
636
+ // author can see, because the text is identically styled and only the letters
637
+ // differ. Text sits on a baseline; a baseline is a property of the font and the
638
+ // line box, not of the word.
639
+ //
640
+ // What the font-wide box keeps is the reason ink centring exists at all: a
641
+ // font's ascender and descender metrics carry padding that its glyphs never
642
+ // reach, so centring by metrics leaves the text visibly high in a tight box.
643
+ // The tallest ink the font can draw is still ink, so the run is still optically
644
+ // centred — it is just centred on the same thing every other run in that font
645
+ // is.
646
+ //
647
+ // The box ends AT the baseline: a descender hangs out of it. Most of what a UI
648
+ // writes — "SD card", "Gate", "1 / 3" — never reaches into the descender space,
649
+ // so reserving it inside the centred box lifts those lines by half a descender,
650
+ // and against a row's own edges that reads as text sitting too high. What the
651
+ // eye centres is the block of caps and x-heights standing on the baseline; the
652
+ // tail of a "p" is overhang, not mass. Trimming the box at the baseline is what
653
+ // a designer means by optically centred, and it costs nothing in consistency —
654
+ // the box is still the font's, so every run in it still shares one baseline.
655
+ //
656
+ // Except where there is no room: in a box no taller than the font's whole ink,
657
+ // pushing down by half a descender would only push the descenders out of the
658
+ // box and clip them, so the offset is clamped to keep all of the ink inside.
659
+ int rasterizedSingleLineInkCenterOffsetY(const char *text,
660
+ int /*textAlign*/,
661
+ int /*containerWidth*/,
662
+ int fontId,
663
+ int fontSize,
664
+ int lineHeight)
665
+ {
666
+ if (!text || !text[0] || std::strchr(text, '\n')) return 0;
667
+ gea::framework::graphics::RasterizedFont font =
668
+ gea::framework::graphics::FontRegistry::rasterizedFamily(fontId, fontSize);
669
+ if (!font.valid()) return 0;
670
+
671
+ const FontInkExtent ink = rasterizedFontInkExtent(font);
672
+ if (!ink.valid) return 0;
673
+
674
+ const int fontLineHeight = font.lineHeight();
675
+ const int lineAdvance = lineHeight > 0 ? lineHeight : fontLineHeight;
676
+ const int lineBoxOffset = lineHeight > 0 ? (lineAdvance - fontLineHeight) / 2 : 0;
677
+ const int baseline = lineBoxOffset + font.ascender();
678
+ const int iy0 = baseline - ink.above;
679
+ const int offset = roundedHalf((lineAdvance - 1) - (iy0 + baseline - 1));
680
+
681
+ const int lowest = baseline + ink.below - 1;
682
+ if (lowest + offset > lineAdvance - 1) return std::max((lineAdvance - 1) - lowest, -iy0);
683
+ if (iy0 + offset < 0) return -iy0;
684
+ return offset;
685
+ }
686
+
687
+ bool recordProjectedRasterText(const Node &node, uint8_t /*parentAlpha*/, int tx, int ty, int tw)
688
+ {
689
+ if (node.style.font_id < 0 || node.text.find('\n') != std::string::npos) return false;
690
+ const int fontSize = node.style.font_size > 0 ? node.style.font_size : kBitmapFontHeight;
691
+ gea::framework::graphics::RasterizedFont font =
692
+ gea::framework::graphics::FontRegistry::rasterizedFamily(node.style.font_id, fontSize);
693
+ if (!font.valid()) return false;
694
+
695
+ int lineWidth = 0;
696
+ bool wordStart = true;
697
+ for (const char *p = node.text.c_str(); *p;) {
698
+ gea::framework::graphics::Glyph glyph{};
699
+ const int cp = transformedTextCodepoint(nextUtf8Codepoint(p), node.style.text_transform, wordStart);
700
+ lineWidth += font.glyph(cp, &glyph) ? glyph.advance : (font.sizePx() / 2);
701
+ }
702
+
703
+ int bx0, by0, bx1, by1;
704
+ ViewRenderer::transformedBounds(node, false, &bx0, &by0, &bx1, &by1);
705
+
706
+ if (lineWidth <= 0 || node.style.text_alpha == 0) return true;
707
+
708
+ const int fontLineHeight = font.lineHeight();
709
+ const int lineAdvance = node.style.line_height > 0 ? node.style.line_height : fontLineHeight;
710
+ const int lineBoxOffset = node.style.line_height > 0 ? (lineAdvance - fontLineHeight) / 2 : 0;
711
+ const int srcX = tx + alignedOffset(node.style.text_align, tw, lineWidth);
712
+ const int srcY = ty + lineBoxOffset;
713
+ const int srcW = lineWidth;
714
+ const int srcH = fontLineHeight;
715
+ if (srcW <= 0 || srcH <= 0) return false;
716
+
717
+ int16_t xs[4], ys[4];
718
+ ViewRenderer::transformedRectCorners(node, false, srcX, srcY, srcW, srcH, xs, ys);
719
+ boundsFromCorners(xs, ys, &bx0, &by0, &bx1, &by1);
720
+
721
+ DisplayCommand *cmd = DisplayList::instance().append();
722
+ if (!cmd) return false;
723
+ cmd->type = DisplayCommandType::DrawProjectedText;
724
+ cmd->bx = bx0;
725
+ cmd->by = by0;
726
+ cmd->bw = bx1 - bx0 + 1;
727
+ cmd->bh = by1 - by0 + 1;
728
+ cmd->projectedText.text = node.text.c_str();
729
+ cmd->projectedText.srcX = srcX;
730
+ cmd->projectedText.srcY = srcY;
731
+ cmd->projectedText.srcW = srcW;
732
+ cmd->projectedText.srcH = srcH;
733
+ cmd->projectedText.x0 = xs[0];
734
+ cmd->projectedText.y0 = ys[0];
735
+ cmd->projectedText.x1 = xs[1];
736
+ cmd->projectedText.y1 = ys[1];
737
+ cmd->projectedText.x2 = xs[2];
738
+ cmd->projectedText.y2 = ys[2];
739
+ cmd->projectedText.x3 = xs[3];
740
+ cmd->projectedText.y3 = ys[3];
741
+ cmd->projectedText.fontId = node.style.font_id;
742
+ cmd->projectedText.fontSize = fontSize;
743
+ cmd->projectedText.color = node.style.text_color;
744
+ cmd->projectedText.alpha = node.style.text_alpha;
745
+ cmd->projectedText.textTransform = node.style.text_transform;
746
+ // CSS flattening: the label is painted into its transformed ancestor's plane
747
+ // (nothing below the face preserves 3D), so backface-visibility:hidden on any
748
+ // ancestor in the projection chain culls the flattened text together with its
749
+ // face. The property does not inherit, so the span itself never carries it —
750
+ // reading only node.style left labels floating over culled faces.
751
+ {
752
+ bool backfaceHidden = node.style.backface_hidden != 0;
753
+ const Tree &tree = Tree::instance();
754
+ const Node *nodes = tree.nodes();
755
+ for (int a = node.parent; !backfaceHidden && a >= 0 && a < tree.nodeCount(); a = nodes[a].parent)
756
+ backfaceHidden = nodes[a].style.backface_hidden != 0;
757
+ cmd->projectedText.backfaceHidden = backfaceHidden ? 1 : 0;
758
+ }
759
+ return true;
760
+ }
761
+ #endif
762
+
763
+ // Host-overridable text measurement hook. Platforms that render text through
764
+ // their own typesetter (e.g. macOS via NSTextField + CoreText) need the
765
+ // framework's layout sizes to match what the host will actually draw, not the
766
+ // framework's bitmap-font fallback. A platform that wants to take over
767
+ // measurement defines this symbol to return true and fill *outW/*outH; the
768
+ // default weak no-op returns false and lets the bitmap/rasterized paths run.
769
+ extern "C" __attribute__((weak)) bool gea_host_measure_text(const char *text,
770
+ int maxWidth,
771
+ int fontId,
772
+ int fontSize,
773
+ int *outWidth,
774
+ int *outHeight);
775
+ extern "C" __attribute__((weak)) bool gea_host_measure_text_with_line_height(const char *text,
776
+ int maxWidth,
777
+ int fontId,
778
+ int fontSize,
779
+ int lineHeight,
780
+ int *outWidth,
781
+ int *outHeight);
782
+ extern "C" __attribute__((weak)) bool gea_host_measure_text_with_style(const char *text,
783
+ int maxWidth,
784
+ int fontId,
785
+ int fontSize,
786
+ int fontWeight,
787
+ int lineHeight,
788
+ int *outWidth,
789
+ int *outHeight);
790
+ extern "C" __attribute__((weak)) bool gea_host_measure_text(const char *,
791
+ int,
792
+ int,
793
+ int,
794
+ int *,
795
+ int *)
796
+ {
797
+ return false;
798
+ }
799
+ extern "C" __attribute__((weak)) bool gea_host_measure_text_with_line_height(const char *,
800
+ int,
801
+ int,
802
+ int,
803
+ int,
804
+ int *,
805
+ int *)
806
+ {
807
+ return false;
808
+ }
809
+ extern "C" __attribute__((weak)) bool gea_host_measure_text_with_style(const char *,
810
+ int,
811
+ int,
812
+ int,
813
+ int,
814
+ int,
815
+ int *,
816
+ int *)
817
+ {
818
+ return false;
819
+ }
820
+
821
+ class TextMetrics {
822
+ public:
823
+ static TextMeasure measure(const char *text, int maxWidth, int fontId, int fontSize, int lineHeight = 0, int fontWeight = 400)
824
+ {
825
+ // Give the host first crack — when it returns true we trust its
826
+ // measurement absolutely, even if the values look surprising next to
827
+ // the bitmap fallback (e.g. macOS reports actual CoreText-laid-out
828
+ // widths which include kerning while the bitmap path would be a
829
+ // crude advance sum).
830
+ {
831
+ int hw = 0;
832
+ int hh = 0;
833
+ if (gea_host_measure_text_with_style(text, maxWidth, fontId, fontSize, fontWeight, lineHeight, &hw, &hh) ||
834
+ gea_host_measure_text_with_line_height(text, maxWidth, fontId, fontSize, lineHeight, &hw, &hh) ||
835
+ gea_host_measure_text(text, maxWidth, fontId, fontSize, &hw, &hh)) {
836
+ TextMeasure m;
837
+ m.width = hw;
838
+ m.height = hh;
839
+ return m;
840
+ }
841
+ }
842
+ #ifdef GEA_EMBEDDED_HAS_GENERATED_FONTS
843
+ if (fontId >= 0) {
844
+ const TextMeasure measured = measureRasterized(text, maxWidth, fontId, fontSize, lineHeight);
845
+ if (!text || !text[0] || measured.height > 0) return measured;
846
+ }
847
+ #else
848
+ (void)fontId;
849
+ #endif
850
+ const float scale = fontSize > 0 ? static_cast<float>(fontSize) / kBitmapFontHeight : 1.0f;
851
+ return measureBitmap(text, maxWidth, scale, lineHeight);
852
+ }
853
+
854
+ static TextMeasure measureBitmap(const char *text, int maxWidth, float scale, int lineHeight = 0)
855
+ {
856
+ TextMeasure result{};
857
+ if (!text || !text[0]) return result;
858
+
859
+ int glyphWidth = static_cast<int>(kBitmapFontWidth * scale + 0.5f);
860
+ int glyphHeight = static_cast<int>(kBitmapFontHeight * scale + 0.5f);
861
+ if (glyphWidth < 1) glyphWidth = 1;
862
+ if (glyphHeight < 1) glyphHeight = 1;
863
+ const int lineAdvance = lineHeight > 0 ? lineHeight : glyphHeight;
864
+
865
+ int maxLineWidth = 0;
866
+ int lines = 1;
867
+ if (maxWidth <= 0) maxWidth = 32767;
868
+ const char *lineStart = text;
869
+ while (*lineStart) {
870
+ const WrappedLine line = nextWrappedLine(lineStart, maxWidth, [&](int) { return glyphWidth; });
871
+ if (line.width > maxLineWidth) maxLineWidth = line.width;
872
+ lineStart += line.consumedBytes;
873
+ if (*lineStart) lines++;
874
+ }
875
+ result.width = maxLineWidth;
876
+ result.height = lines * lineAdvance;
877
+ return result;
878
+ }
879
+
880
+ #ifdef GEA_EMBEDDED_HAS_GENERATED_FONTS
881
+ static TextMeasure measureRasterized(const char *text, int maxWidth, int fontId, int fontSize, int lineHeight = 0)
882
+ {
883
+ TextMeasure result{};
884
+ if (!text || !text[0]) return result;
885
+
886
+ gea::framework::graphics::RasterizedFont font = gea::framework::graphics::FontRegistry::rasterizedFamily(fontId, fontSize);
887
+ if (!font.valid()) return result;
888
+ const int lineAdvance = lineHeight > 0 ? lineHeight : font.lineHeight();
889
+
890
+ int maxLineWidth = 0;
891
+ int lines = 1;
892
+ if (maxWidth <= 0) maxWidth = 32767;
893
+ const char *lineStart = text;
894
+ while (*lineStart) {
895
+ const WrappedLine line = nextWrappedLine(lineStart, maxWidth, [&](int cp) {
896
+ gea::framework::graphics::Glyph glyph{};
897
+ return font.glyph(cp, &glyph) ? glyph.advance : (font.sizePx() / 2);
898
+ });
899
+ if (line.width > maxLineWidth) maxLineWidth = line.width;
900
+ lineStart += line.consumedBytes;
901
+ if (*lineStart) lines++;
902
+ }
903
+ result.width = maxLineWidth;
904
+ result.height = lines * lineAdvance;
905
+ return result;
906
+ }
907
+ #endif
908
+ };
909
+
910
+ // Per-codepoint advances for one node, taken from exactly the source the DRAW
911
+ // path wraps with: the rasterized atlas when the family resolves, the fixed-cell
912
+ // bitmap font otherwise. Inline fragmentation must agree with the drawer glyph
913
+ // for glyph — a wrapper that disagrees with the one that paints puts a line
914
+ // where the box has no room for it.
915
+ struct GlyphAdvanceSource {
916
+ bool valid = false;
917
+ int lineAdvance = 0;
918
+ #ifdef GEA_EMBEDDED_HAS_GENERATED_FONTS
919
+ bool rasterized = false;
920
+ gea::framework::graphics::RasterizedFont font{};
921
+ #endif
922
+ int glyphWidth = 0;
923
+
924
+ int operator()(int cp) const
925
+ {
926
+ #ifdef GEA_EMBEDDED_HAS_GENERATED_FONTS
927
+ if (rasterized) {
928
+ gea::framework::graphics::Glyph glyph{};
929
+ return font.glyph(cp, &glyph) ? glyph.advance : (font.sizePx() / 2);
930
+ }
931
+ #else
932
+ (void)cp;
933
+ #endif
934
+ return glyphWidth;
935
+ }
936
+ };
937
+
938
+ GlyphAdvanceSource advanceSourceForNode(const Node &node)
939
+ {
940
+ GlyphAdvanceSource src;
941
+ const int fontSize = node.style.font_size > 0 ? node.style.font_size : kBitmapFontHeight;
942
+ #ifdef GEA_EMBEDDED_HAS_GENERATED_FONTS
943
+ if (node.style.font_id >= 0) {
944
+ src.font = gea::framework::graphics::FontRegistry::rasterizedFamily(node.style.font_id, fontSize);
945
+ if (src.font.valid()) {
946
+ src.rasterized = true;
947
+ src.valid = true;
948
+ src.lineAdvance = node.style.line_height > 0 ? node.style.line_height : src.font.lineHeight();
949
+ return src;
950
+ }
951
+ }
952
+ #endif
953
+ const float scale = static_cast<float>(fontSize) / kBitmapFontHeight;
954
+ src.glyphWidth = static_cast<int>(kBitmapFontWidth * scale + 0.5f);
955
+ if (src.glyphWidth < 1) src.glyphWidth = 1;
956
+ int glyphHeight = static_cast<int>(kBitmapFontHeight * scale + 0.5f);
957
+ if (glyphHeight < 1) glyphHeight = 1;
958
+ src.lineAdvance = node.style.line_height > 0 ? node.style.line_height : glyphHeight;
959
+ src.valid = true;
960
+ return src;
961
+ }
962
+
963
+ // Bytes of collapsible whitespace at the head of `text`. CSS removes them when
964
+ // they fall at the start of a line box.
965
+ int leadingCollapsibleBytes(const char *text)
966
+ {
967
+ const char *p = text;
968
+ while (*p) {
969
+ const char *glyphStart = p;
970
+ const char *probe = p;
971
+ const int cp = nextUtf8Codepoint(probe);
972
+ if (!isWrappingSpace(cp)) return static_cast<int>(glyphStart - text);
973
+ p = probe;
974
+ }
975
+ return static_cast<int>(p - text);
976
+ }
977
+
978
+ TextLayoutMeasure measureTextLayoutForNode(const Node &node, const char *text, int contentWidth)
979
+ {
980
+ if (contentWidth < 0) contentWidth = 0;
981
+ std::string transformed;
982
+ const char *measureText = textWithTransform(text, node.style.text_transform, transformed);
983
+ // white-space: nowrap lays the run out as a single line — measure against an
984
+ // unbounded width so the content box sizes to the full text (then max-width /
985
+ // the parent box clamps it). Drawing truncates/ellipsizes the overflow.
986
+ const int measureWidth = node.style.white_space == 1 ? 32767 : contentWidth;
987
+ const TextMeasure measured = TextMetrics::measure(measureText,
988
+ measureWidth,
989
+ node.style.font_id,
990
+ node.style.font_size,
991
+ node.style.line_height,
992
+ node.style.font_weight);
993
+ TextLayoutMeasure out;
994
+ out.width = measured.width + node.style.padding[1] + node.style.padding[3];
995
+ out.height = measured.height + node.style.padding[0] + node.style.padding[2];
996
+ if (node.style.width != kUnset) out.width = node.style.width;
997
+ else if (node.style.width_percent != kUnset && node.layout.width > 0) out.width = node.layout.width;
998
+ if (node.style.height != kUnset) out.height = node.style.height;
999
+ else if (node.style.height_percent != kUnset && node.layout.height > 0) out.height = node.layout.height;
1000
+ out.width = LayoutEngine::instance().clampSize(out.width, node.style.min_width, node.style.max_width);
1001
+ out.height = LayoutEngine::instance().clampSize(out.height, node.style.min_height, node.style.max_height);
1002
+ return out;
1003
+ }
1004
+
1005
+ int measureSingleLineTextWidthForNode(const Node &node, const char *text)
1006
+ {
1007
+ if (!text || !text[0]) return 0;
1008
+ std::string transformed;
1009
+ const char *measureText = textWithTransform(text, node.style.text_transform, transformed);
1010
+ return TextMetrics::measure(measureText,
1011
+ 32767,
1012
+ node.style.font_id,
1013
+ node.style.font_size,
1014
+ node.style.line_height,
1015
+ node.style.font_weight).width;
1016
+ }
1017
+
1018
+ class TextDrawer {
1019
+ public:
1020
+ static void drawWrapped(const char *text, int x, int y, int maxWidth, gea::framework::graphics::pixel::native_t color, float scale, int textAlign, int containerWidth, int fontId, int textTransform, int lineHeight, int whiteSpace, int textOverflow, int maxHeight = 0, int firstLineIndent = 0)
1021
+ {
1022
+ if (!text || !text[0]) return;
1023
+ std::string transformed;
1024
+ text = textWithTransform(text, textTransform, transformed);
1025
+
1026
+ int clipX0;
1027
+ int clipY0;
1028
+ int clipX1;
1029
+ int clipY1;
1030
+ gea::platform::display::Display::clip(&clipX0, &clipY0, &clipX1, &clipY1);
1031
+
1032
+ const bool noWrap = whiteSpace == 1;
1033
+ const bool ellipsis = textOverflow == 1;
1034
+
1035
+ #ifdef GEA_EMBEDDED_HAS_GENERATED_FONTS
1036
+ if (fontId >= 0) {
1037
+ const int fontSize = static_cast<int>(scale * kBitmapFontHeight + 0.5f);
1038
+ if (gea::framework::graphics::FontRegistry::rasterizedFamily(fontId, fontSize).valid()) {
1039
+ if (noWrap)
1040
+ drawRasterizedSingleLine(text, x, y, maxWidth, color, textAlign, containerWidth, fontId, fontSize, lineHeight, ellipsis, clipX0, clipY0, clipX1, clipY1);
1041
+ else
1042
+ drawRasterizedWrapped(text, x, y, maxWidth, color, textAlign, containerWidth, fontId, fontSize, lineHeight, clipX0, clipY0, clipX1, clipY1,
1043
+ ellipsis ? maxHeight : 0, firstLineIndent);
1044
+ return;
1045
+ }
1046
+ }
1047
+ #else
1048
+ (void)fontId;
1049
+ #endif
1050
+ if (noWrap)
1051
+ drawBitmapSingleLine(text, x, y, maxWidth, color, scale, textAlign, containerWidth, lineHeight, ellipsis, clipX0, clipY0, clipX1, clipY1);
1052
+ else
1053
+ drawBitmapWrapped(text, x, y, maxWidth, color, scale, textAlign, containerWidth, lineHeight, clipX0, clipY0, clipX1, clipY1, firstLineIndent);
1054
+ }
1055
+
1056
+ private:
1057
+ #ifdef GEA_EMBEDDED_HAS_GENERATED_FONTS
1058
+ static void drawRasterizedWrapped(const char *text, int x, int y, int maxWidth, std::uint16_t color, int textAlign, int containerWidth, int fontId, int fontSize, int lineHeight, int clipX0, int clipY0, int clipX1, int clipY1, int ellipsisMaxHeight = 0, int firstLineIndent = 0)
1059
+ {
1060
+ // Inline continuation: the run's first line starts `firstLineIndent` px in
1061
+ // from the box's left edge (the pen position it inherited from the box
1062
+ // before it on that line box) and therefore has that much less room. A
1063
+ // negative indent is the leading-whitespace trim — see
1064
+ // InlineFlowMeasure::firstLineIndentAdjust.
1065
+ const auto lineBudget_ = [&](int li) {
1066
+ const int budget = li == 0 ? maxWidth - firstLineIndent : maxWidth;
1067
+ return budget < 1 ? 1 : budget;
1068
+ };
1069
+ const auto lineOriginX_ = [&](int li) { return li == 0 ? x + firstLineIndent : x; };
1070
+ gea::framework::graphics::RasterizedFont font = gea::framework::graphics::FontRegistry::rasterizedFamily(fontId, fontSize);
1071
+ if (!font.valid()) return;
1072
+
1073
+ const int glyphHeight = font.lineHeight();
1074
+ const int lineAdvance = lineHeight > 0 ? lineHeight : glyphHeight;
1075
+ const int lineBoxOffset = lineHeight > 0 ? (lineAdvance - glyphHeight) / 2 : 0;
1076
+ // Multi-line clamp (text-overflow: ellipsis on WRAPPED text): the content
1077
+ // box caps how many lines draw; the last budgeted line renders through
1078
+ // the single-line ellipsis routine when more text would follow it.
1079
+ const int lineBudget = ellipsisMaxHeight > 0 ? (ellipsisMaxHeight / lineAdvance > 0 ? ellipsisMaxHeight / lineAdvance : 1) : 0x7fffffff;
1080
+
1081
+ // Cache lookup: if the same (text content, layout params) was laid out
1082
+ // previously, skip the per-glyph advance loop and iterate the cached
1083
+ // chars[] array directly. See LineBreakCacheEntry comment.
1084
+ const std::uint32_t hash = hashTextPrefix(text);
1085
+ const int slot = lineBreakCacheSlot(text, maxWidth);
1086
+ LineBreakCacheEntry &entry = gLineBreakCache[slot];
1087
+ const bool cacheHit =
1088
+ entry.textPtr == text &&
1089
+ entry.textHashPrefix == hash &&
1090
+ entry.maxWidth == maxWidth &&
1091
+ entry.firstLineIndent == firstLineIndent &&
1092
+ entry.fontId == fontId &&
1093
+ entry.fontSize == fontSize &&
1094
+ entry.lineHeight == lineAdvance;
1095
+
1096
+ if (!cacheHit) {
1097
+ entry.textPtr = text;
1098
+ entry.textHashPrefix = hash;
1099
+ entry.maxWidth = maxWidth;
1100
+ entry.firstLineIndent = firstLineIndent;
1101
+ entry.fontId = fontId;
1102
+ entry.fontSize = fontSize;
1103
+ entry.lineHeight = lineAdvance;
1104
+ entry.scaleQ8 = 0;
1105
+ entry.lineCount = 0;
1106
+
1107
+ const char *p = text;
1108
+ while (*p && entry.lineCount < kMaxCachedLines) {
1109
+ const WrappedLine line = nextWrappedLine(p, lineBudget_(entry.lineCount), [&](int cp) {
1110
+ gea::framework::graphics::Glyph glyph{};
1111
+ return font.glyph(cp, &glyph) ? glyph.advance : (font.sizePx() / 2);
1112
+ });
1113
+ entry.renderBytes[entry.lineCount] = static_cast<std::uint16_t>(line.renderBytes > 65535 ? 65535 : line.renderBytes);
1114
+ entry.consumedBytes[entry.lineCount] = static_cast<std::uint16_t>(line.consumedBytes > 65535 ? 65535 : line.consumedBytes);
1115
+ entry.lineWidths[entry.lineCount] = static_cast<std::uint16_t>(line.width > 65535 ? 65535 : line.width);
1116
+ entry.lineCount++;
1117
+ p += line.consumedBytes;
1118
+ }
1119
+ // If we ran out of cache slots, mark invalid so we don't read junk.
1120
+ if (*p) {
1121
+ entry.textPtr = nullptr; // invalidate; fall through to original loop
1122
+ }
1123
+ }
1124
+
1125
+ // Iterate cached (or freshly populated) lines with the Y-clip filter.
1126
+ // Above-clip lines skip the entire render call. The lineStart pointer
1127
+ // advances via cached `chars` — no per-glyph advance work.
1128
+ if (entry.textPtr == text) {
1129
+ int penY = y;
1130
+ const char *lineStart = text;
1131
+ for (int li = 0; li < entry.lineCount; li++) {
1132
+ if (penY + lineBoxOffset > clipY1) break;
1133
+ if (li == lineBudget - 1 && li < entry.lineCount - 1) {
1134
+ // Last budgeted line with more text behind it: ellipsize the rest.
1135
+ drawRasterizedSingleLine(lineStart, lineOriginX_(li), penY, lineBudget_(li), color, textAlign, containerWidth,
1136
+ fontId, fontSize, lineHeight, /*ellipsis=*/true,
1137
+ clipX0, clipY0, clipX1, clipY1);
1138
+ return;
1139
+ }
1140
+ const int chars = entry.renderBytes[li];
1141
+ const int lineBoxY = penY + lineBoxOffset;
1142
+ if (lineBoxY + glyphHeight - 1 >= clipY0) {
1143
+ const int lineWidth = entry.lineWidths[li];
1144
+ const int lineX = lineOriginX_(li) + alignedOffset(textAlign, containerWidth, lineWidth);
1145
+ if (lineX <= clipX1 && lineX + lineWidth - 1 >= clipX0) {
1146
+ char lineBuffer[kWrappedLineBufferBytes + 1];
1147
+ const int copyLen = chars < kWrappedLineBufferBytes ? chars : kWrappedLineBufferBytes;
1148
+ std::memcpy(lineBuffer, lineStart, copyLen);
1149
+ lineBuffer[copyLen] = '\0';
1150
+ gea::platform::display::Display::drawTextFontFamily(lineBuffer, lineX, lineBoxY, color, fontId, fontSize);
1151
+ }
1152
+ }
1153
+ lineStart += entry.consumedBytes[li];
1154
+ penY += lineAdvance;
1155
+ }
1156
+ return;
1157
+ }
1158
+
1159
+ // Fallback for the cache-overflow case (text with > 64 lines).
1160
+ const char *lineStart = text;
1161
+ int penY = y;
1162
+ int li = 0;
1163
+ while (*lineStart) {
1164
+ if (penY + lineBoxOffset > clipY1) break;
1165
+ if (li == lineBudget - 1) {
1166
+ // Budget reached: ellipsize whatever remains onto this final line.
1167
+ drawRasterizedSingleLine(lineStart, lineOriginX_(li), penY, lineBudget_(li), color, textAlign, containerWidth,
1168
+ fontId, fontSize, lineHeight, /*ellipsis=*/true,
1169
+ clipX0, clipY0, clipX1, clipY1);
1170
+ return;
1171
+ }
1172
+ const int lineIndex = li;
1173
+ li++;
1174
+
1175
+ const WrappedLine line = nextWrappedLine(lineStart, lineBudget_(lineIndex), [&](int cp) {
1176
+ gea::framework::graphics::Glyph glyph{};
1177
+ return font.glyph(cp, &glyph) ? glyph.advance : (font.sizePx() / 2);
1178
+ });
1179
+
1180
+ const int lineBoxY = penY + lineBoxOffset;
1181
+ if (lineBoxY + glyphHeight - 1 >= clipY0) {
1182
+ const int lineX = lineOriginX_(lineIndex) + alignedOffset(textAlign, containerWidth, line.width);
1183
+ if (lineX <= clipX1 && lineX + line.width - 1 >= clipX0) {
1184
+ char lineBuffer[kWrappedLineBufferBytes + 1];
1185
+ const int copyLen = line.renderBytes < kWrappedLineBufferBytes ? line.renderBytes : kWrappedLineBufferBytes;
1186
+ std::memcpy(lineBuffer, lineStart, copyLen);
1187
+ lineBuffer[copyLen] = '\0';
1188
+ gea::platform::display::Display::drawTextFontFamily(lineBuffer, lineX, lineBoxY, color, fontId, fontSize);
1189
+ }
1190
+ }
1191
+
1192
+ lineStart += line.consumedBytes;
1193
+ penY += lineAdvance;
1194
+ }
1195
+ }
1196
+
1197
+ // white-space: nowrap path. Lays the run out as a single line (newlines end
1198
+ // the line) and, when it overflows maxWidth, truncates at a glyph boundary —
1199
+ // appending an ASCII "..." when text-overflow: ellipsis is set, or hard-
1200
+ // clipping at the box edge otherwise. The truncated run always fits within
1201
+ // maxWidth, so it never wraps and never spills past the content box.
1202
+ static void drawRasterizedSingleLine(const char *text, int x, int y, int maxWidth, std::uint16_t color, int textAlign, int containerWidth, int fontId, int fontSize, int lineHeight, bool ellipsis, int clipX0, int clipY0, int clipX1, int clipY1)
1203
+ {
1204
+ gea::framework::graphics::RasterizedFont font = gea::framework::graphics::FontRegistry::rasterizedFamily(fontId, fontSize);
1205
+ if (!font.valid()) return;
1206
+
1207
+ const int glyphHeight = font.lineHeight();
1208
+ const int lineAdvance = lineHeight > 0 ? lineHeight : glyphHeight;
1209
+ const int lineBoxOffset = lineHeight > 0 ? (lineAdvance - glyphHeight) / 2 : 0;
1210
+ const int lineBoxY = y + lineBoxOffset;
1211
+ if (lineBoxY > clipY1 || lineBoxY + glyphHeight - 1 < clipY0) return;
1212
+ if (maxWidth <= 0) maxWidth = 32767;
1213
+
1214
+ const auto advanceOf = [&font](int cp) {
1215
+ gea::framework::graphics::Glyph glyph{};
1216
+ return font.glyph(cp, &glyph) ? glyph.advance : (font.sizePx() / 2);
1217
+ };
1218
+
1219
+ // Full single-line advance width (stop at the first newline).
1220
+ int fullWidth = 0;
1221
+ for (const char *p = text; *p && *p != '\n';) fullWidth += advanceOf(nextUtf8Codepoint(p));
1222
+
1223
+ char buf[256];
1224
+ int len = 0;
1225
+ int drawnWidth = 0;
1226
+ constexpr int kBufCap = static_cast<int>(sizeof(buf));
1227
+
1228
+ if (fullWidth <= maxWidth) {
1229
+ for (const char *p = text; *p && *p != '\n' && len < kBufCap - 1; ++p) buf[len++] = *p;
1230
+ drawnWidth = fullWidth;
1231
+ } else if (ellipsis) {
1232
+ const int dotAdvance = advanceOf('.');
1233
+ const int ellipsisWidth = dotAdvance * 3;
1234
+ const int budget = maxWidth > ellipsisWidth ? maxWidth - ellipsisWidth : 0;
1235
+ int w = 0;
1236
+ const char *p = text;
1237
+ while (*p && *p != '\n') {
1238
+ const char *glyphStart = p;
1239
+ const int advance = advanceOf(nextUtf8Codepoint(p));
1240
+ if (w + advance > budget) break;
1241
+ const int bytes = static_cast<int>(p - glyphStart);
1242
+ if (len + bytes > kBufCap - 4) break; // leave room for "..." + NUL
1243
+ for (int i = 0; i < bytes; ++i) buf[len++] = glyphStart[i];
1244
+ w += advance;
1245
+ }
1246
+ buf[len++] = '.';
1247
+ buf[len++] = '.';
1248
+ buf[len++] = '.';
1249
+ drawnWidth = w + ellipsisWidth;
1250
+ } else {
1251
+ int w = 0;
1252
+ const char *p = text;
1253
+ while (*p && *p != '\n') {
1254
+ const char *glyphStart = p;
1255
+ const int advance = advanceOf(nextUtf8Codepoint(p));
1256
+ if (w + advance > maxWidth && len > 0) break;
1257
+ const int bytes = static_cast<int>(p - glyphStart);
1258
+ if (len + bytes > kBufCap - 1) break;
1259
+ for (int i = 0; i < bytes; ++i) buf[len++] = glyphStart[i];
1260
+ w += advance;
1261
+ }
1262
+ drawnWidth = w;
1263
+ }
1264
+
1265
+ if (len <= 0) return;
1266
+ buf[len] = '\0';
1267
+ const int xOffset = alignedOffset(textAlign, containerWidth, drawnWidth);
1268
+ gea::platform::display::Display::drawTextFontFamily(buf, x + xOffset, lineBoxY, color, fontId, fontSize);
1269
+ }
1270
+ #endif
1271
+
1272
+ static void drawBitmapWrapped(const char *text, int x, int y, int maxWidth, std::uint16_t color, float scale, int textAlign, int containerWidth, int lineHeight, int clipX0, int clipY0, int clipX1, int clipY1, int firstLineIndent = 0)
1273
+ {
1274
+ if (scale < 0.1f) scale = 1.0f;
1275
+ int glyphWidth = static_cast<int>(kBitmapFontWidth * scale + 0.5f);
1276
+ int glyphHeight = static_cast<int>(kBitmapFontHeight * scale + 0.5f);
1277
+ if (glyphWidth < 1) glyphWidth = 1;
1278
+ if (glyphHeight < 1) glyphHeight = 1;
1279
+ const int lineAdvance = lineHeight > 0 ? lineHeight : glyphHeight;
1280
+
1281
+ const char *lineStart = text;
1282
+ int penY = y;
1283
+ int lineIndex = 0;
1284
+
1285
+ while (*lineStart) {
1286
+ if (penY > clipY1) break;
1287
+ // See drawRasterizedWrapped: line 0 of an inline continuation starts at
1288
+ // the inherited pen and has that much less room.
1289
+ const int budget = lineIndex == 0 ? maxWidth - firstLineIndent : maxWidth;
1290
+ const int lineOriginX = lineIndex == 0 ? x + firstLineIndent : x;
1291
+ const WrappedLine line = nextWrappedLine(lineStart, budget < 1 ? 1 : budget, [&](int) { return glyphWidth; });
1292
+ lineIndex++;
1293
+
1294
+ if (penY + glyphHeight - 1 >= clipY0) {
1295
+ int penX = lineOriginX + alignedOffset(textAlign, containerWidth, line.width);
1296
+ if (penX <= clipX1 && penX + line.width - 1 >= clipX0) {
1297
+ const char *glyph = lineStart;
1298
+ const char *renderEnd = lineStart + line.renderBytes;
1299
+ while (glyph < renderEnd) {
1300
+ const char *glyphStart = glyph;
1301
+ nextUtf8Codepoint(glyph);
1302
+ char buf[5] = {};
1303
+ const int bytes = static_cast<int>(glyph - glyphStart);
1304
+ std::memcpy(buf, glyphStart, bytes);
1305
+ gea::platform::display::Display::drawText(buf, penX, penY, color, scale);
1306
+ penX += glyphWidth;
1307
+ }
1308
+ }
1309
+ }
1310
+
1311
+ lineStart += line.consumedBytes;
1312
+ penY += lineAdvance;
1313
+ }
1314
+ }
1315
+
1316
+ // Bitmap-font nowrap path — fixed-cell analogue of drawRasterizedSingleLine.
1317
+ // Like drawBitmapWrapped, it treats each CODEPOINT as one fixed-width cell:
1318
+ // that is what `measureBitmap` charges for, so counting bytes here put the
1319
+ // truncation, the ellipsis budget and the alignment offset in different units
1320
+ // from the layout that placed the text.
1321
+ static void drawBitmapSingleLine(const char *text, int x, int y, int maxWidth, std::uint16_t color, float scale, int textAlign, int containerWidth, int lineHeight, bool ellipsis, int clipX0, int clipY0, int clipX1, int clipY1)
1322
+ {
1323
+ (void)lineHeight;
1324
+ if (scale < 0.1f) scale = 1.0f;
1325
+ int glyphWidth = static_cast<int>(kBitmapFontWidth * scale + 0.5f);
1326
+ int glyphHeight = static_cast<int>(kBitmapFontHeight * scale + 0.5f);
1327
+ if (glyphWidth < 1) glyphWidth = 1;
1328
+ if (glyphHeight < 1) glyphHeight = 1;
1329
+ const int penY = y;
1330
+ if (penY > clipY1 || penY + glyphHeight - 1 < clipY0) return;
1331
+ if (maxWidth <= 0) maxWidth = 32767;
1332
+
1333
+ int fullChars = 0;
1334
+ for (const char *p = text; *p && *p != '\n';) {
1335
+ nextUtf8Codepoint(p);
1336
+ fullChars++;
1337
+ }
1338
+ const int fullWidth = fullChars * glyphWidth;
1339
+
1340
+ int drawChars = fullChars;
1341
+ bool addEllipsis = false;
1342
+ if (fullWidth > maxWidth) {
1343
+ if (ellipsis) {
1344
+ const int ellipsisWidth = 3 * glyphWidth;
1345
+ const int budget = maxWidth > ellipsisWidth ? maxWidth - ellipsisWidth : 0;
1346
+ drawChars = budget / glyphWidth;
1347
+ addEllipsis = true;
1348
+ } else {
1349
+ drawChars = maxWidth / glyphWidth;
1350
+ if (drawChars < 1) drawChars = 1;
1351
+ }
1352
+ if (drawChars > fullChars) drawChars = fullChars;
1353
+ }
1354
+
1355
+ const int drawnWidth = drawChars * glyphWidth + (addEllipsis ? 3 * glyphWidth : 0);
1356
+ if (drawnWidth <= 0) return;
1357
+ int penX = x + alignedOffset(textAlign, containerWidth, drawnWidth);
1358
+ if (penX > clipX1 || penX + drawnWidth - 1 < clipX0) return;
1359
+ const char *glyph = text;
1360
+ for (int i = 0; i < drawChars && *glyph && *glyph != '\n'; ++i) {
1361
+ const char *glyphStart = glyph;
1362
+ nextUtf8Codepoint(glyph);
1363
+ char b[5] = {};
1364
+ std::memcpy(b, glyphStart, static_cast<std::size_t>(glyph - glyphStart));
1365
+ gea::platform::display::Display::drawText(b, penX, penY, color, scale);
1366
+ penX += glyphWidth;
1367
+ }
1368
+ if (addEllipsis) {
1369
+ for (int i = 0; i < 3; ++i) {
1370
+ char b[2] = { '.', '\0' };
1371
+ gea::platform::display::Display::drawText(b, penX, penY, color, scale);
1372
+ penX += glyphWidth;
1373
+ }
1374
+ }
1375
+ }
1376
+
1377
+ static int alignedOffset(int textAlign, int containerWidth, int lineWidth)
1378
+ {
1379
+ int offset = 0;
1380
+ if (textAlign == 1) offset = (containerWidth - lineWidth) / 2;
1381
+ else if (textAlign == 2) offset = containerWidth - lineWidth;
1382
+ return offset < 0 ? 0 : offset;
1383
+ }
1384
+ };
1385
+
1386
+ } // namespace
1387
+
1388
+ void Tree::setText(int node, const char *text)
1389
+ {
1390
+ auto &perf = refreshPerfStatsMutable();
1391
+ ScopedRefreshStat timer(perf.treeSetTextUs);
1392
+ perf.treeSetTextCalls++;
1393
+ if (node < 0 || node >= nodeCount() || !text) return;
1394
+ Node &target = this->node(node);
1395
+ if (target.text == text) return;
1396
+ perf.treeSetTextChanged++;
1397
+ // Hidden subtree: just store the text. A display:none node paints nothing, so
1398
+ // dirtying it for a text change would churn layout (its zero-size box defeats
1399
+ // the bbox prediction below -> full relayout) and drop the static-backdrop
1400
+ // cache every tick — a hidden ticking label re-baked the rotary's 230k-px
1401
+ // floor gradient (~185ms) on every value change. The display-toggle path
1402
+ // re-records the subtree with the fresh text when it becomes visible.
1403
+ {
1404
+ int guard = 0;
1405
+ for (int a = node; a >= 0 && a < nodeCount() && guard <= nodeCount(); a = this->node(a).parent, ++guard)
1406
+ {
1407
+ if (this->node(a).style.display == 1)
1408
+ {
1409
+ // Same realloc-dangle guard as the visible path below: a node hidden
1410
+ // NOW may still have retained commands from when it was visible.
1411
+ const char *gid_oldBuffer = target.text.c_str();
1412
+ target.text.assign(text);
1413
+ if (target.text.c_str() != gid_oldBuffer) DisplayList::instance().scrubNodeText(gid_oldBuffer);
1414
+ perf.treeSetTextHidden++;
1415
+ return;
1416
+ }
1417
+ }
1418
+ }
1419
+ // Dynamic-leaf text (a ticking fps badge, a clock): mark it STICKY-excluded so
1420
+ // every future backdrop bake skips it, and only drop the existing cache when
1421
+ // this node's pixels are actually baked into it. An excluded ticker updates
1422
+ // through the normal dirty-region replay without ever touching the backdrop.
1423
+ // Sticky on purpose: a decaying cooldown re-baked the ticker in whenever its
1424
+ // text went stable for a few seconds, and the next change invalidated again —
1425
+ // each cycle a full-screen rebake+sync that flashed the static stage at
1426
+ // fps-jitter-random times. The INITIAL set (empty -> value, the mount) is not
1427
+ // a tick — marking it would keep every static label out of the first bake.
1428
+ {
1429
+ auto &st = treeState();
1430
+ if (!target.text.empty())
1431
+ st.nodeBackdropCooldown[node] = 1;
1432
+ #ifndef ESP_PLATFORM
1433
+ {
1434
+ static const bool debugBackdrop = std::getenv("GEA_DEBUG_BACKDROP") != nullptr;
1435
+ if (debugBackdrop)
1436
+ std::printf("[settext] node=%d '%s'->'%s' backdropActive=%d inBackdrop=%d\n",
1437
+ node, target.text.c_str(), text,
1438
+ DisplayList::instance().staticBackdropActive() ? 1 : 0,
1439
+ st.nodeInBackdrop[node] ? 1 : 0);
1440
+ }
1441
+ #endif
1442
+ if (!DisplayList::instance().staticBackdropActive() || st.nodeInBackdrop[node])
1443
+ DisplayList::instance().invalidateStaticBackdrop();
1444
+ }
1445
+ // Glyph-incremental dirty: diff the old text (target.text, not yet overwritten)
1446
+ // against the new text to find the unchanged common prefix/suffix, and remember
1447
+ // the old box height. If the box stays the same height below, only the middle run
1448
+ // differs, so the collector can flush just that run (a ticking counter re-copies
1449
+ // only its changed digits instead of the whole — possibly huge — glyph box).
1450
+ const std::string gid_new(text);
1451
+ const int gid_oldLen = static_cast<int>(target.text.size());
1452
+ const int gid_newLen = static_cast<int>(gid_new.size());
1453
+ int gid_prefix = 0;
1454
+ while (gid_prefix < gid_oldLen && gid_prefix < gid_newLen && target.text[gid_prefix] == gid_new[gid_prefix])
1455
+ gid_prefix++;
1456
+ int gid_suffix = 0;
1457
+ while (gid_suffix < gid_oldLen - gid_prefix && gid_suffix < gid_newLen - gid_prefix &&
1458
+ target.text[gid_oldLen - 1 - gid_suffix] == gid_new[gid_newLen - 1 - gid_suffix])
1459
+ gid_suffix++;
1460
+ const bool gid_singleLine =
1461
+ target.text.find('\n') == std::string::npos && gid_new.find('\n') == std::string::npos;
1462
+ const int gid_oldH = target.layout.height;
1463
+ // Glyph-run widths must be measured independently of the CSS layout box.
1464
+ // measureTextLayoutForNode() intentionally replaces its natural result with an
1465
+ // explicit style width. Using it for substring bounds made every substring of a
1466
+ // fixed-width label appear equally wide. A shrinking update such as
1467
+ // "San Francisco" -> "Lisbon" then dirtied only the new, shorter run (or even a
1468
+ // sliver at the box edge), leaving the old trailing glyphs on the physical panel.
1469
+ const bool gid_canPartial = gid_singleLine && target.style.white_space == 1 &&
1470
+ target.style.text_align == 0 && gid_prefix < gid_newLen;
1471
+ int gid_preW = 0;
1472
+ int gid_rightW = 0;
1473
+ if (gid_canPartial) {
1474
+ const std::string gid_pre = gid_new.substr(0, static_cast<size_t>(gid_prefix));
1475
+ const std::string gid_oldHead = target.text.substr(0, static_cast<size_t>(gid_oldLen - gid_suffix));
1476
+ const std::string gid_newHead = gid_new.substr(0, static_cast<size_t>(gid_newLen - gid_suffix));
1477
+ gid_preW = measureSingleLineTextWidthForNode(target, gid_pre.c_str());
1478
+ const int gid_oldHeadW = measureSingleLineTextWidthForNode(target, gid_oldHead.c_str());
1479
+ const int gid_newHeadW = measureSingleLineTextWidthForNode(target, gid_newHead.c_str());
1480
+ if (gid_oldHeadW == gid_newHeadW) {
1481
+ // The unchanged suffix stays at the same x position, so it does not need
1482
+ // repainting; stop at the end of the changed head.
1483
+ gid_rightW = gid_newHeadW;
1484
+ } else {
1485
+ // The suffix moved, or the new run is shorter. Cover both complete run
1486
+ // extents so all shifted/removed glyph pixels are restored from backdrop.
1487
+ const int gid_oldTextW = measureSingleLineTextWidthForNode(target, target.text.c_str());
1488
+ const int gid_newTextW = measureSingleLineTextWidthForNode(target, gid_new.c_str());
1489
+ gid_rightW = gid_oldTextW > gid_newTextW ? gid_oldTextW : gid_newTextW;
1490
+ }
1491
+ }
1492
+
1493
+ const bool gid_hadLayoutDirty = target.render.layout_dirty != 0;
1494
+ target.render.dirty = 1;
1495
+ target.render.layout_dirty = 1;
1496
+ target.render.non_scroll_dirty = 1;
1497
+ target.render.text_layout_stable = 0;
1498
+ markNodeDisplayCommandsDirty(node);
1499
+ // assign() past capacity reallocates and frees the old buffer, leaving any
1500
+ // retained display command's raw text pointer dangling until the re-record.
1501
+ // Scrub only when the buffer actually moved — in-place reuse (the common
1502
+ // same-or-smaller-length tick) keeps retained commands valid and visible.
1503
+ const char *oldBuffer = target.text.c_str();
1504
+ target.text.assign(text);
1505
+ if (target.text.c_str() != oldBuffer) DisplayList::instance().scrubNodeText(oldBuffer);
1506
+
1507
+ // Predict the new text bbox so AbsoluteLeafRefresh::mode() can skip the
1508
+ // full LayoutEngine::layoutNode pass for content-only text frames.
1509
+ // Absolute-positioned text can safely accept a bbox change because it is
1510
+ // out of flow. In-flow text stays on the fast path only when its measured
1511
+ // layout box is unchanged, so flex/grid siblings and parents cannot move.
1512
+ //
1513
+ // This mirrors TextRenderer::layout's formula exactly, except for the
1514
+ // avail_w sourcing: layout receives avail_w from the parent. We don't have
1515
+ // it here. For absolute natural-width text we use a deliberately large
1516
+ // bound, matching the previous FPS-counter behavior. For in-flow text we
1517
+ // require an explicit style width, including percentages already resolved
1518
+ // by the stylesheet, so wrapping is measured against the same fixed box.
1519
+ if (target.layout.width > 0 && target.layout.height > 0 &&
1520
+ target.parent >= 0 && target.first_child < 0 &&
1521
+ !hasTransformState(target)) {
1522
+ const bool absolute = target.style.position == 1;
1523
+ const bool fixedWidth = target.style.width != kUnset || target.style.width_percent != kUnset;
1524
+ if (absolute || fixedWidth) {
1525
+ const int fixedBoxWidth = target.style.width != kUnset ? target.style.width : target.layout.width;
1526
+ const int content_w = fixedWidth
1527
+ ? fixedBoxWidth - target.style.padding[1] - target.style.padding[3]
1528
+ : 0x4000; // 16384 px — well beyond any panel dimension
1529
+ const TextLayoutMeasure measured = measureTextLayoutForNode(target, target.text.c_str(), content_w);
1530
+ if (absolute) {
1531
+ target.layout.width = measured.width;
1532
+ target.layout.height = measured.height;
1533
+ target.render.text_layout_stable = 1;
1534
+ } else if (measured.width == target.layout.width && measured.height == target.layout.height) {
1535
+ target.render.text_layout_stable = 1;
1536
+ }
1537
+ // Glyph-incremental: single line + left-aligned + a real change after the
1538
+ // common prefix → flush only the changed glyph run. The left edge is the
1539
+ // unchanged prefix's width (pixel-identical, never repainted). The right edge:
1540
+ // if the total width is unchanged the trailing run is pixel-stable too, so stop
1541
+ // at fullWidth-suffixWidth (tightest); if the width changed (proportional digits
1542
+ // shift the tail), cover both the old and new extents so no stale pixels remain.
1543
+ const bool gid_sameHeight = (measured.height == gid_oldH);
1544
+ if (gid_sameHeight && gid_canPartial) {
1545
+ const int gid_originX = target.layout.x + target.style.padding[3];
1546
+ constexpr int kTextDirtyPadPx = 4; // AA / glyph-overhang guard
1547
+ target.render.text_dirty_x0 = static_cast<int16_t>(gid_originX + gid_preW - kTextDirtyPadPx);
1548
+ target.render.text_dirty_x1 = static_cast<int16_t>(gid_originX + gid_rightW + kTextDirtyPadPx);
1549
+ target.render.text_partial_dirty = 1;
1550
+ }
1551
+ }
1552
+ }
1553
+ if (target.render.text_layout_stable) {
1554
+ perf.treeSetTextStable++;
1555
+ // The pre-measure confirmed the box is unchanged: geometry can't move,
1556
+ // so this is paint-only dirt (unless something else already made the
1557
+ // node layout-dirty this frame).
1558
+ if (!gid_hadLayoutDirty)
1559
+ target.render.layout_dirty = 0;
1560
+ }
1561
+ }
1562
+
1563
+ bool TextRenderer::canFragmentInlineRuns(const Node &node)
1564
+ {
1565
+ // A host that measures whole strings (CoreText on the Apple targets) does its
1566
+ // own line breaking; this engine has no way to ask it where line two starts,
1567
+ // so those targets keep flowing each run as one box. The probe is cached: a
1568
+ // target either links the hooks or links the weak no-ops.
1569
+ static int cached = -1;
1570
+ if (cached >= 0) return cached != 0;
1571
+ int w = 0;
1572
+ int h = 0;
1573
+ const int fontId = node.style.font_id;
1574
+ const int fontSize = node.style.font_size > 0 ? node.style.font_size : kBitmapFontHeight;
1575
+ const bool hostMeasures =
1576
+ gea_host_measure_text_with_style("Mg", 32767, fontId, fontSize, node.style.font_weight, node.style.line_height, &w, &h) ||
1577
+ gea_host_measure_text_with_line_height("Mg", 32767, fontId, fontSize, node.style.line_height, &w, &h) ||
1578
+ gea_host_measure_text("Mg", 32767, fontId, fontSize, &w, &h);
1579
+ cached = hostMeasures ? 0 : 1;
1580
+ return cached != 0;
1581
+ }
1582
+
1583
+ InlineFlowMeasure TextRenderer::measureInlineFlow(const Node &node, int firstAvail, int contentWidth, bool atLineStart)
1584
+ {
1585
+ InlineFlowMeasure out;
1586
+ const char *raw = node.text.c_str();
1587
+ if (!raw || !raw[0]) return out;
1588
+ // nowrap is a single line by definition, and an author-sized box wraps within
1589
+ // its own width — neither participates in the block's line boxes.
1590
+ if (node.style.white_space == 1) return out;
1591
+ if (!canFragmentInlineRuns(node)) return out;
1592
+
1593
+ const GlyphAdvanceSource advance = advanceSourceForNode(node);
1594
+ if (!advance.valid || advance.lineAdvance <= 0) return out;
1595
+
1596
+ std::string transformed;
1597
+ const char *text = textWithTransform(raw, node.style.text_transform, transformed);
1598
+ if (!text || !text[0]) return out;
1599
+
1600
+ if (contentWidth < 1) contentWidth = 1;
1601
+ if (firstAvail < 0) firstAvail = 0;
1602
+
1603
+ if (atLineStart) {
1604
+ const int lead = leadingCollapsibleBytes(text);
1605
+ if (lead > 0) {
1606
+ const char *p = text;
1607
+ const char *end = text + lead;
1608
+ int width = 0;
1609
+ while (p < end) width += advance(nextUtf8Codepoint(p));
1610
+ out.firstLineIndentAdjust = -width;
1611
+ }
1612
+ }
1613
+
1614
+ const char *p = text;
1615
+ int lineIndex = 0;
1616
+ while (*p) {
1617
+ const int budget = lineIndex == 0 ? (firstAvail - out.firstLineIndentAdjust) : contentWidth;
1618
+ const WrappedLine line = nextWrappedLine(p, budget < 1 ? 1 : budget, advance);
1619
+ if (line.consumedBytes <= 0) break;
1620
+ const int visible = line.width + (lineIndex == 0 ? out.firstLineIndentAdjust : 0);
1621
+ if (lineIndex == 0) {
1622
+ out.firstLineWidth = visible;
1623
+ out.firstLineForcedSplit = line.hardSplit;
1624
+ }
1625
+ out.lastLineWidth = visible;
1626
+ if (visible > out.maxLineWidth) out.maxLineWidth = visible;
1627
+ p += line.consumedBytes;
1628
+ lineIndex++;
1629
+ }
1630
+ out.lineCount = lineIndex;
1631
+ out.lineAdvance = advance.lineAdvance;
1632
+ return out;
1633
+ }
1634
+
1635
+ void TextRenderer::layout(int id, int avail_w)
1636
+ {
1637
+ Node *n = &Tree::instance().nodes()[id];
1638
+
1639
+ int content_w = avail_w - n->style.padding[1] - n->style.padding[3]
1640
+ - n->style.margin[1] - n->style.margin[3];
1641
+ if (n->style.width != kUnset) content_w = n->style.width - n->style.padding[1] - n->style.padding[3];
1642
+ else if (n->style.width_percent != kUnset && n->layout.width > 0) content_w = n->layout.width - n->style.padding[1] - n->style.padding[3];
1643
+ if (content_w < 0) content_w = 0;
1644
+
1645
+ const TextLayoutMeasure measured = measureTextLayoutForNode(*n, n->text.c_str(), content_w);
1646
+ n->layout.width = measured.width;
1647
+ n->layout.height = measured.height;
1648
+ }
1649
+
1650
+ bool TextRenderer::remeasureContentBox(int id, bool keepBoxWidth)
1651
+ {
1652
+ Node &n = Tree::instance().nodes()[id];
1653
+ if (n.type != NodeType::Text) return false;
1654
+ // A run that continues a line box (inline_indent != 0) has a box its SIBLINGS
1655
+ // determine — its first line is short by the pen it inherited, and where it
1656
+ // ends decides where the next box starts. There is no re-measuring that in
1657
+ // isolation, so the scroll fast path leaves it alone; text_layout_stable stays
1658
+ // 0, so the settle frame's full layout reflows the line properly.
1659
+ if (n.layout.inline_indent != 0) return false;
1660
+ // keepBoxWidth: the box was cross-stretched by the layout engine (a block
1661
+ // span in a column flow fills the parent's content width), so its geometry
1662
+ // is independent of the string — re-wrap the new text within it and update
1663
+ // only the height. Otherwise same content-width sourcing as layout(): an
1664
+ // explicit width re-wraps within the fixed box; natural-width text hugs the
1665
+ // new content (the 0x4000 bound matches setText's bbox predictor).
1666
+ int content_w = 0x4000;
1667
+ if (keepBoxWidth) content_w = n.layout.width;
1668
+ else if (n.style.width != kUnset) content_w = n.style.width - n.style.padding[1] - n.style.padding[3];
1669
+ else if (n.style.width_percent != kUnset && n.layout.width > 0) content_w = n.layout.width - n.style.padding[1] - n.style.padding[3];
1670
+ if (content_w < 0) content_w = 0;
1671
+ const TextLayoutMeasure measured = measureTextLayoutForNode(n, n.text.c_str(), content_w);
1672
+ if (keepBoxWidth) {
1673
+ if (measured.height == n.layout.height) return false;
1674
+ n.layout.height = measured.height;
1675
+ return true;
1676
+ }
1677
+ if (measured.width == n.layout.width && measured.height == n.layout.height) return false;
1678
+ n.layout.width = measured.width;
1679
+ n.layout.height = measured.height;
1680
+ return true;
1681
+ }
1682
+
1683
+ void TextRenderer::drawWrapped(const char *text, int x, int y, int maxWidth, gea::framework::graphics::pixel::native_t color, float scale, int text_align, int containerWidth, int fontId, int textTransform, int lineHeight, int whiteSpace, int textOverflow, int maxHeight, int firstLineIndent)
1684
+ {
1685
+ TextDrawer::drawWrapped(text, x, y, maxWidth, color, scale, text_align, containerWidth, fontId, textTransform, lineHeight, whiteSpace, textOverflow, maxHeight, firstLineIndent);
1686
+ }
1687
+
1688
+ int TextRenderer::measureWidth(const char *text, int fontId, int fontSize, int textTransform)
1689
+ {
1690
+ if (!text || !text[0]) return 0;
1691
+ // 32767 = no horizontal wrapping; we want the full single-line width
1692
+ // that the chosen font would render. Returning that as int16-safe.
1693
+ std::string transformed;
1694
+ const char *measureText = textWithTransform(text, textTransform, transformed);
1695
+ const TextMeasure measured = TextMetrics::measure(measureText, 32767, fontId, fontSize);
1696
+ return measured.width;
1697
+ }
1698
+
1699
+ int TextRenderer::measureHeight(const char *text, int fontId, int fontSize, int textTransform, int lineHeight)
1700
+ {
1701
+ if (!text || !text[0]) return 0;
1702
+ std::string transformed;
1703
+ const char *measureText = textWithTransform(text, textTransform, transformed);
1704
+ const TextMeasure measured = TextMetrics::measure(measureText, 32767, fontId, fontSize, lineHeight);
1705
+ return measured.height;
1706
+ }
1707
+
1708
+ void GEA_TEXT_HOT_SRAM TextRenderer::record(const Node &node, uint8_t parentAlpha)
1709
+ {
1710
+ const Node *n = &node;
1711
+ if (n->type != NodeType::Text || n->text.empty()) return;
1712
+
1713
+ int x = n->layout.x;
1714
+ int y = n->layout.y;
1715
+ int w = n->layout.width;
1716
+ int h = n->layout.height;
1717
+ int tx = x + n->style.padding[3];
1718
+ int ty = y + n->style.padding[0];
1719
+ int tw = w - n->style.padding[1] - n->style.padding[3];
1720
+ if (tw < 0) tw = 0;
1721
+ float textScale = n->style.font_size > 0 ? static_cast<float>(n->style.font_size) / kBitmapFontHeight : 1.0f;
1722
+
1723
+ int bx = x;
1724
+ int by = y;
1725
+ int bw = w;
1726
+ int bh = h;
1727
+ int drawX = tx;
1728
+ int drawY = ty;
1729
+ int drawW = tw;
1730
+ int containerW = tw;
1731
+ int commandLineHeight = n->style.line_height;
1732
+ int transformedX0 = x;
1733
+ int transformedY0 = y;
1734
+ int transformedX1 = x + w - 1;
1735
+ int transformedY1 = y + h - 1;
1736
+ ViewRenderer::transformedBounds(*n, false, &transformedX0, &transformedY0, &transformedX1, &transformedY1);
1737
+ bool transformed =
1738
+ transformedX0 != x ||
1739
+ transformedY0 != y ||
1740
+ transformedX1 != x + w - 1 ||
1741
+ transformedY1 != y + h - 1;
1742
+ if (transformed) {
1743
+ float translateX = 0.0f;
1744
+ float translateY = 0.0f;
1745
+ if (currentTransformChainIsPureTranslate(*n, &translateX, &translateY)) {
1746
+ x = translateCoord(x, translateX);
1747
+ y = translateCoord(y, translateY);
1748
+ tx = translateCoord(tx, translateX);
1749
+ ty = translateCoord(ty, translateY);
1750
+ bx = x;
1751
+ by = y;
1752
+ drawX = tx;
1753
+ drawY = ty;
1754
+ transformed = false;
1755
+ }
1756
+ }
1757
+ std::string transformedText;
1758
+ const char *measureText = textWithTransform(n->text.c_str(), n->style.text_transform, transformedText);
1759
+ #ifdef GEA_EMBEDDED_HAS_GENERATED_FONTS
1760
+ if (transformed && recordProjectedRasterText(*n, parentAlpha, tx, ty, tw)) return;
1761
+ #endif
1762
+ if (transformed && transformedX1 >= transformedX0 && transformedY1 >= transformedY0) {
1763
+ const int projectedW = transformedX1 - transformedX0 + 1;
1764
+ const int projectedH = transformedY1 - transformedY0 + 1;
1765
+ const int contentH = h - n->style.padding[0] - n->style.padding[2];
1766
+ const int centerX = transformedX0 + projectedW / 2;
1767
+ const int centerY = transformedY0 + projectedH / 2;
1768
+ float projectedScaleX = tw > 0 ? static_cast<float>(projectedW) / static_cast<float>(tw) : 1.0f;
1769
+ float projectedScaleY = 1.0f;
1770
+ if (contentH > 0) {
1771
+ projectedScaleY = static_cast<float>(projectedH) / static_cast<float>(contentH);
1772
+ }
1773
+ float projectedScale = projectedScaleX < projectedScaleY ? projectedScaleX : projectedScaleY;
1774
+ projectedScale = clampFloat(projectedScale, 0.35f, 1.35f);
1775
+ textScale *= projectedScale;
1776
+ const int projectedFontSize = static_cast<int>(textScale * kBitmapFontHeight + 0.5f);
1777
+ const int projectedLineHeight = n->style.line_height > 0
1778
+ ? static_cast<int>(static_cast<float>(n->style.line_height) * projectedScale + 0.5f)
1779
+ : 0;
1780
+ commandLineHeight = projectedLineHeight;
1781
+ const TextMeasure projectedMeasure =
1782
+ TextMetrics::measure(measureText, 32767, n->style.font_id, projectedFontSize, projectedLineHeight, n->style.font_weight);
1783
+ drawW = projectedMeasure.width > 0 ? projectedMeasure.width : projectedW;
1784
+ const int drawH = projectedMeasure.height > 0 ? projectedMeasure.height : (contentH > 0 ? contentH : projectedH);
1785
+ containerW = drawW;
1786
+ drawX = centerX - drawW / 2;
1787
+ drawY = centerY - drawH / 2;
1788
+ if (drawY < transformedY0) drawY = transformedY0;
1789
+ const int drawX1 = drawX + drawW - 1;
1790
+ const int drawY1 = drawY + drawH - 1;
1791
+ const int pad = 2;
1792
+ bx = drawX - pad;
1793
+ by = drawY - pad;
1794
+ bw = drawX1 - drawX + 1 + pad * 2;
1795
+ bh = drawY1 - drawY + 1 + pad * 2;
1796
+ #ifdef GEA_EMBEDDED_HAS_GENERATED_FONTS
1797
+ if (n->style.font_id >= 0) {
1798
+ const int commandFontSize = static_cast<int>(textScale * kBitmapFontHeight + 0.5f);
1799
+ int ix0 = 0;
1800
+ int iy0 = 0;
1801
+ int ix1 = -1;
1802
+ int iy1 = -1;
1803
+ if (rasterizedTextInkBounds(measureText,
1804
+ drawW,
1805
+ n->style.text_align,
1806
+ containerW,
1807
+ n->style.font_id,
1808
+ commandFontSize,
1809
+ commandLineHeight,
1810
+ &ix0,
1811
+ &iy0,
1812
+ &ix1,
1813
+ &iy1)) {
1814
+ const int inkPad = 2;
1815
+ bx = drawX + ix0 - inkPad;
1816
+ by = drawY + iy0 - inkPad;
1817
+ bw = ix1 - ix0 + 1 + inkPad * 2;
1818
+ bh = iy1 - iy0 + 1 + inkPad * 2;
1819
+ }
1820
+ }
1821
+ #endif
1822
+ }
1823
+
1824
+ const bool noWrap = n->style.white_space == 1;
1825
+ // Inline continuation (see LayoutBox::inline_indent): line 0 starts at
1826
+ // `drawX + inlineIndent`, every later line at `drawX`. The tight ink/paint
1827
+ // bounds below all assume one origin for the whole run, so an indented run
1828
+ // keeps the full box as its command bound — conservative, and the only cost
1829
+ // is a slightly larger dirty rect for the handful of runs that continue a
1830
+ // line box. A negative indent (the leading-whitespace trim) reaches left of
1831
+ // the box, so widen for it.
1832
+ const int inlineIndent = transformed ? 0 : n->layout.inline_indent;
1833
+ if (inlineIndent < 0) {
1834
+ bx += inlineIndent;
1835
+ bw -= inlineIndent;
1836
+ }
1837
+ if (!transformed && inlineIndent == 0) {
1838
+ const int commandFontSize = static_cast<int>(textScale * kBitmapFontHeight + 0.5f);
1839
+ const TextMeasure paintMeasure =
1840
+ TextMetrics::measure(measureText, noWrap ? 32767 : drawW, n->style.font_id, commandFontSize, commandLineHeight, n->style.font_weight);
1841
+ if (paintMeasure.width > 0 && paintMeasure.height > 0) {
1842
+ // CSS: a flex container's bare text becomes an anonymous flex item, so
1843
+ // align-items centers (or end-aligns) it on the cross axis. This node
1844
+ // draws its own run top-anchored otherwise, which made
1845
+ // `display:flex; align-items:center` on a childless span a no-op — apps
1846
+ // had to fake it with line-height. Row-direction flex only (the cross
1847
+ // axis is vertical there); a child-bearing flex container aligns its
1848
+ // child BOXES through layout as before.
1849
+ if (n->style.display == kDisplayFlex && n->first_child < 0 &&
1850
+ (n->style.align_items == 1 || n->style.align_items == 2) &&
1851
+ usesRowLayout(n->style)) {
1852
+ const int contentH = h - n->style.padding[0] - n->style.padding[2];
1853
+ const int slack = contentH - paintMeasure.height;
1854
+ if (slack > 0) drawY += n->style.align_items == 1 ? slack / 2 : slack;
1855
+ }
1856
+ // nowrap truncates/clips the run to the content box, so the painted
1857
+ // width never exceeds drawW even though the unbounded measure may.
1858
+ int paintWidth = paintMeasure.width;
1859
+ if (noWrap && paintWidth > drawW) paintWidth = drawW;
1860
+ #ifdef GEA_EMBEDDED_HAS_GENERATED_FONTS
1861
+ if (n->style.font_id >= 0) {
1862
+ gea::framework::graphics::RasterizedFont font =
1863
+ gea::framework::graphics::FontRegistry::rasterizedFamily(n->style.font_id, commandFontSize);
1864
+ const int lineAdvance = commandLineHeight > 0 ? commandLineHeight : (font.valid() ? font.lineHeight() : 0);
1865
+ const bool singleLine = font.valid() &&
1866
+ std::strchr(measureText, '\n') == nullptr &&
1867
+ paintMeasure.height <= lineAdvance;
1868
+ // Ink centring moves the whole line box so the font's ink sits centred
1869
+ // in the line advance. That is right for a run that owns its line and
1870
+ // wrong for one that shares it, where the inline flow has already
1871
+ // placed a baseline every box on the line must draw at. See
1872
+ // RenderState::inline_baseline.
1873
+ if (singleLine && !n->render.inline_baseline) {
1874
+ drawY += rasterizedSingleLineInkCenterOffsetY(measureText,
1875
+ n->style.text_align,
1876
+ containerW,
1877
+ n->style.font_id,
1878
+ commandFontSize,
1879
+ commandLineHeight);
1880
+ }
1881
+ }
1882
+ #endif
1883
+ const int xOffset = alignedOffset(n->style.text_align, containerW, paintWidth);
1884
+ int paintX0 = drawX + xOffset;
1885
+ int paintY0 = drawY;
1886
+ int paintX1 = paintX0 + paintWidth - 1;
1887
+ int paintY1 = paintY0 + paintMeasure.height - 1;
1888
+ #ifdef GEA_EMBEDDED_HAS_GENERATED_FONTS
1889
+ if (n->style.font_id >= 0) {
1890
+ int ix0 = 0;
1891
+ int iy0 = 0;
1892
+ int ix1 = -1;
1893
+ int iy1 = -1;
1894
+ if (rasterizedTextInkBounds(measureText,
1895
+ noWrap ? 32767 : drawW,
1896
+ n->style.text_align,
1897
+ containerW,
1898
+ n->style.font_id,
1899
+ commandFontSize,
1900
+ commandLineHeight,
1901
+ &ix0,
1902
+ &iy0,
1903
+ &ix1,
1904
+ &iy1)) {
1905
+ // A nowrap run may be clipped/ellipsized horizontally, so its
1906
+ // unbounded ink X extent is not a valid command bound. Its Y ink
1907
+ // extent is still exact, however, and is essential when CSS
1908
+ // line-height is shorter than the raster font's line height. The
1909
+ // previous line-box bound missed the bottom 4-5 rows of large
1910
+ // compressed text (weather's 20 -> 17 temperature left residue).
1911
+ if (!noWrap) paintX0 = drawX + ix0;
1912
+ paintY0 = drawY + iy0;
1913
+ if (!noWrap) paintX1 = drawX + ix1;
1914
+ paintY1 = drawY + iy1;
1915
+ }
1916
+ }
1917
+ #endif
1918
+ const int pad = 2;
1919
+ bx = paintX0 - pad;
1920
+ by = paintY0 - pad;
1921
+ bw = paintX1 - paintX0 + 1 + pad * 2;
1922
+ bh = paintY1 - paintY0 + 1 + pad * 2;
1923
+ }
1924
+ }
1925
+
1926
+ // TEMPORARY BASELINE INSTRUMENTATION (env-gated) — remove before landing.
1927
+ if (std::getenv("GEA_TEXT_BASELINE_DEBUG") && n->style.font_id >= 0) {
1928
+ const int dbgFontSize = static_cast<int>(textScale * kBitmapFontHeight + 0.5f);
1929
+ gea::framework::graphics::RasterizedFont dbgFont =
1930
+ gea::framework::graphics::FontRegistry::rasterizedFamily(n->style.font_id, dbgFontSize);
1931
+ const int fontLH = dbgFont.valid() ? dbgFont.lineHeight() : -1;
1932
+ const int asc = dbgFont.valid() ? dbgFont.ascender() : -1;
1933
+ const int lineAdv = commandLineHeight > 0 ? commandLineHeight : fontLH;
1934
+ const int lineBoxOff = commandLineHeight > 0 ? (lineAdv - fontLH) / 2 : 0;
1935
+ int inkOff = 0;
1936
+ #ifdef GEA_EMBEDDED_HAS_GENERATED_FONTS
1937
+ const int genFonts = 1;
1938
+ inkOff = rasterizedSingleLineInkCenterOffsetY(measureText, n->style.text_align, containerW,
1939
+ n->style.font_id, dbgFontSize, commandLineHeight);
1940
+ #else
1941
+ const int genFonts = 0;
1942
+ #endif
1943
+ char preview[29];
1944
+ int pi = 0;
1945
+ for (const char *p = n->text.c_str(); *p && pi < 28; ++p)
1946
+ preview[pi++] = (*p == '\n') ? ' ' : *p;
1947
+ preview[pi] = '\0';
1948
+ std::printf("[baseline] gen=%d '%s' font=%d size=%d asc=%d fontLH=%d cssLH=%d "
1949
+ "box=(%d,%d,%dx%d) ty=%d drawY=%d inkOff=%d lineBoxOff=%d baselineY=%d\n",
1950
+ genFonts, preview, n->style.font_id, dbgFontSize, asc, fontLH,
1951
+ n->style.line_height, n->layout.x, n->layout.y, n->layout.width,
1952
+ n->layout.height, ty, drawY, inkOff, lineBoxOff, drawY + lineBoxOff + asc);
1953
+ std::fflush(stdout);
1954
+ }
1955
+
1956
+ const uint8_t effectiveAlpha = combineAlpha(parentAlpha, n->style.text_alpha);
1957
+ if (effectiveAlpha != parentAlpha) appendAlphaCommand(effectiveAlpha, bx, by, bw, bh);
1958
+
1959
+ DisplayCommand *cmd = DisplayList::instance().append();
1960
+ if (!cmd) {
1961
+ if (effectiveAlpha != parentAlpha) appendAlphaCommand(parentAlpha, bx, by, bw, bh);
1962
+ return;
1963
+ }
1964
+ cmd->type = DisplayCommandType::DrawText;
1965
+ cmd->bx = bx; cmd->by = by; cmd->bw = bw; cmd->bh = bh;
1966
+ cmd->text.text = n->text.c_str();
1967
+ cmd->text.x = drawX; cmd->text.y = drawY;
1968
+ cmd->text.maxWidth = drawW;
1969
+ cmd->text.color = n->style.text_color;
1970
+ cmd->text.scale = textScale;
1971
+ cmd->text.align = n->style.text_align;
1972
+ cmd->text.textTransform = n->style.text_transform;
1973
+ cmd->text.lineHeight = commandLineHeight;
1974
+ cmd->text.containerWidth = containerW;
1975
+ cmd->text.fontId = n->style.font_id;
1976
+ cmd->text.whiteSpace = n->style.white_space;
1977
+ cmd->text.textOverflow = n->style.text_overflow;
1978
+ cmd->text.firstLineIndent = static_cast<int16_t>(inlineIndent);
1979
+ {
1980
+ const int contentH = h - n->style.padding[0] - n->style.padding[2];
1981
+ cmd->text.maxHeight = static_cast<int16_t>(contentH > 0 ? (contentH > 32767 ? 32767 : contentH) : 0);
1982
+ }
1983
+
1984
+ // Text decoration — paint a horizontal line on top of the glyph row.
1985
+ // We approximate via font size (no font-metric introspection available
1986
+ // cross-platform): line-through sits a little below the em-box midpoint,
1987
+ // underline sits near the baseline, and thickness scales with the text.
1988
+ // The width matches the measured text width so the line doesn't extend
1989
+ // past the actual glyphs.
1990
+ if (n->style.text_decoration != 0 && !n->text.empty()) {
1991
+ const int fontSize = n->style.font_size > 0 ? n->style.font_size : kBitmapFontHeight;
1992
+ const int lineWidth = TextMetrics::measure(measureText, tw, n->style.font_id, n->style.font_size, 0, n->style.font_weight).width;
1993
+ const int lineHeight = textDecorationThickness(fontSize);
1994
+ const int lineY = textDecorationY(ty, fontSize, lineHeight, n->style.text_decoration);
1995
+ DisplayCommand *deco = DisplayList::instance().append();
1996
+ if (deco) {
1997
+ deco->type = DisplayCommandType::FillRect;
1998
+ deco->bx = x; deco->by = y; deco->bw = w; deco->bh = h;
1999
+ deco->fill.x = tx;
2000
+ deco->fill.y = lineY;
2001
+ deco->fill.w = lineWidth;
2002
+ deco->fill.h = lineHeight;
2003
+ deco->fill.color = n->style.text_color;
2004
+ }
2005
+ }
2006
+
2007
+ if (effectiveAlpha != parentAlpha) appendAlphaCommand(parentAlpha, bx, by, bw, bh);
2008
+ }
2009
+
2010
+ } // namespace gea::embedded::ui