@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/layout.cpp ADDED
@@ -0,0 +1,2025 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #include "internal.h"
3
+ #include "memory.h"
4
+ #include "refresh_perf.h"
5
+
6
+ #include "graphics/font.h"
7
+
8
+ #include <cstdio>
9
+ #include <cstring>
10
+
11
+ namespace gea::embedded::ui {
12
+
13
+ namespace {
14
+
15
+ constexpr int kScratchDepth = 16;
16
+
17
+ struct FlexLine {
18
+ int start = 0;
19
+ int count = 0;
20
+ int mainSize = 0;
21
+ int crossSize = 0;
22
+ };
23
+
24
+ class LayoutScratch {
25
+ public:
26
+ static LayoutScratch &instance()
27
+ {
28
+ static LayoutScratch scratch;
29
+ return scratch;
30
+ }
31
+
32
+ int enter()
33
+ {
34
+ const int current = depth_;
35
+ depth_++;
36
+ return current;
37
+ }
38
+
39
+ void leave()
40
+ {
41
+ if (depth_ > 0) depth_--;
42
+ }
43
+
44
+ int *childrenForDepth(int depth)
45
+ {
46
+ if (depth < 0 || depth >= kScratchDepth) return nullptr;
47
+ if (!children_) children_ = static_cast<int *>(allocate(sizeof(int) * kScratchDepth * kMaxChildren));
48
+ if (!children_) return nullptr;
49
+ return children_ + depth * kMaxChildren;
50
+ }
51
+
52
+ FlexLine *linesForDepth(int depth)
53
+ {
54
+ if (depth < 0 || depth >= kScratchDepth) return nullptr;
55
+ if (!lines_) lines_ = static_cast<FlexLine *>(allocate(sizeof(FlexLine) * kScratchDepth * kMaxFlexLines));
56
+ if (!lines_) return nullptr;
57
+ return lines_ + depth * kMaxFlexLines;
58
+ }
59
+
60
+ private:
61
+ static void *allocate(size_t size)
62
+ {
63
+ return gea::framework::memory::Allocator::allocatePreferSpiram(size);
64
+ }
65
+
66
+ int depth_ = 0;
67
+ int *children_ = nullptr;
68
+ FlexLine *lines_ = nullptr;
69
+ };
70
+
71
+ class ScratchFrame {
72
+ public:
73
+ ScratchFrame()
74
+ : scratch_(LayoutScratch::instance()), depth_(scratch_.enter())
75
+ {
76
+ children_ = scratch_.childrenForDepth(depth_);
77
+ lines_ = scratch_.linesForDepth(depth_);
78
+ }
79
+
80
+ ~ScratchFrame()
81
+ {
82
+ scratch_.leave();
83
+ }
84
+
85
+ bool valid() const
86
+ {
87
+ return depth_ >= 0 && depth_ < kScratchDepth && children_ && lines_;
88
+ }
89
+
90
+ int *children() const { return children_; }
91
+ FlexLine *lines() const { return lines_; }
92
+
93
+ private:
94
+ LayoutScratch &scratch_;
95
+ int depth_ = 0;
96
+ int *children_ = nullptr;
97
+ FlexLine *lines_ = nullptr;
98
+ };
99
+
100
+ int resolvePercentSize(int basis, int percent)
101
+ {
102
+ const long long numerator = static_cast<long long>(basis) * percent;
103
+ return static_cast<int>((numerator + (numerator >= 0 ? 500 : -500)) / 1000);
104
+ }
105
+
106
+ bool hasExplicitWidth(const Node &node)
107
+ {
108
+ return node.style.width != kUnset || node.style.width_percent != kUnset;
109
+ }
110
+
111
+ int16_t clampInt16(int value)
112
+ {
113
+ if (value > 32767) return 32767;
114
+ if (value < -32768) return -32768;
115
+ return static_cast<int16_t>(value);
116
+ }
117
+
118
+ bool hasExplicitHeight(const Node &node)
119
+ {
120
+ return node.style.height != kUnset || node.style.height_percent != kUnset;
121
+ }
122
+
123
+ int resolvedStyleWidth(const Node &node, int basis)
124
+ {
125
+ if (node.style.width != kUnset) return node.style.width;
126
+ if (node.style.width_percent != kUnset) return resolvePercentSize(basis, node.style.width_percent);
127
+ return basis;
128
+ }
129
+
130
+ int resolvedStyleHeight(const Node &node, int basis)
131
+ {
132
+ if (node.style.height != kUnset) return node.style.height;
133
+ if (node.style.height_percent != kUnset) return resolvePercentSize(basis, node.style.height_percent);
134
+ return basis;
135
+ }
136
+
137
+ class FlexLayoutPass {
138
+ public:
139
+ FlexLayoutPass(LayoutEngine &engine, Node &node, int *children, int childCount, bool isRow, int mainAvail, int padWidth, int padHeight, FlexLine *lines, bool inlineRow = false)
140
+ : engine_(engine),
141
+ node_(node),
142
+ children_(children),
143
+ childCount_(childCount),
144
+ isRow_(isRow),
145
+ inlineRow_(inlineRow && isRow),
146
+ mainAvail_(mainAvail),
147
+ padWidth_(padWidth),
148
+ padHeight_(padHeight),
149
+ lines_(lines)
150
+ {
151
+ }
152
+
153
+ void measureChildren()
154
+ {
155
+ for (int i = 0; i < childCount_; i++) {
156
+ const int child = children_[i];
157
+ const int childAvailWidth = isRow_ ? mainAvail_ : padWidth_;
158
+ const int childAvailHeight = isRow_ ? padHeight_ : mainAvail_;
159
+ engine_.layoutNode(child, childAvailWidth, childAvailHeight);
160
+ applyFlexBasis(child);
161
+ }
162
+ }
163
+
164
+ // Flex line packing. An inline formatting context does NOT come through here —
165
+ // layoutInlineFlow owns it — because flex lines cannot express one: their items
166
+ // are atomic, so a text run may neither share a line with its neighbours nor
167
+ // split across two.
168
+ int buildLines()
169
+ {
170
+ int lineStart = 0;
171
+ int lineMain = 0;
172
+ int lineCross = 0;
173
+ int gapCount = 0;
174
+ int lineCount = 0;
175
+ Node *nodes = Tree::instance().nodes();
176
+
177
+ for (int i = 0; i < childCount_; i++) {
178
+ const int child = children_[i];
179
+ Node &childNode = nodes[child];
180
+ const int childMain = isRow_
181
+ ? (childNode.layout.width + childNode.style.margin[1] + childNode.style.margin[3])
182
+ : (childNode.layout.height + childNode.style.margin[0] + childNode.style.margin[2]);
183
+ const int childCross = isRow_
184
+ ? (childNode.layout.height + childNode.style.margin[0] + childNode.style.margin[2])
185
+ : (childNode.layout.width + childNode.style.margin[1] + childNode.style.margin[3]);
186
+
187
+ const int withGap = gapCount > 0 ? node_.style.gap : 0;
188
+ if (node_.style.flex_wrap && lineMain + childMain + withGap > mainAvail_ && gapCount > 0) {
189
+ appendLine(lineCount, lineStart, gapCount, lineMain, lineCross);
190
+ lineStart = i;
191
+ lineMain = childMain;
192
+ lineCross = childCross;
193
+ gapCount = 1;
194
+ } else {
195
+ lineMain += childMain + withGap;
196
+ if (childCross > lineCross) lineCross = childCross;
197
+ gapCount++;
198
+ }
199
+ }
200
+
201
+ if (gapCount > 0) appendLine(lineCount, lineStart, gapCount, lineMain, lineCross);
202
+ return lineCount;
203
+ }
204
+
205
+ // Lays this node's children out as a sequence of LINE BOXES — a real inline
206
+ // formatting context. Flex line packing cannot express one: it treats every
207
+ // item as ATOMIC, so a text run that overflows the space left on a line is
208
+ // pushed whole onto the next one and the line before it ends far short of the
209
+ // right edge (typography's mixed-composition paragraphs lost ~40% of every
210
+ // line to that). CSS instead lets a run START on the line box it inherits,
211
+ // wrap its remainder at the block's left edge, and hand the pen to the next
212
+ // box on its LAST line.
213
+ //
214
+ // One forward walk. Per line box it first SCANS ahead to learn which items
215
+ // share it — and therefore the line's ascent, and so its baseline — then
216
+ // places them. The scans partition the item list, so the pass is linear.
217
+ void layoutInlineFlow(bool autosize)
218
+ {
219
+ Node *nodes = Tree::instance().nodes();
220
+ const int contentW = mainAvail_ < 0 ? 0 : mainAvail_;
221
+ const int contentLeft = node_.style.padding[3];
222
+ const int contentTop = node_.style.padding[0];
223
+ const int gapStyle = node_.style.gap;
224
+
225
+ // CSS drops leading whitespace at the start of a LINE BOX. This block opens
226
+ // one only when it is not itself an inline box that its parent may have
227
+ // placed part-way along a line: `<p>…baseline.<span> Inline emphasis</span>…`
228
+ // runs its own flow inside the span, and the space that separates it from
229
+ // the text before it is content, not indentation.
230
+ const bool blockOpensItsFirstLine = !LayoutEngine::isInlineLevelNode(node_);
231
+ int i = 0;
232
+ int lineTop = contentTop;
233
+ int flowBottom = contentTop;
234
+ int maxLineWidth = 0;
235
+ // Carried across a wrapped run: the pen its last line ended at, that
236
+ // line's already-fixed baseline, and the ascent/descent it contributes.
237
+ int penStart = 0;
238
+ bool continuing = false;
239
+ int continuedBaseline = 0;
240
+ int inheritedAscent = 0;
241
+ int inheritedDescent = 0;
242
+
243
+ while (i < childCount_) {
244
+ // A line box that opens as the tail of a wrapped run already has content
245
+ // even if no further item joins it.
246
+ const bool lineIsContinuation = continuing;
247
+ int pen = penStart;
248
+ int lineAscent = inheritedAscent;
249
+ int lineDescent = inheritedDescent;
250
+ int j = i;
251
+ int wrapIdx = -1;
252
+ int wrapSpans = 0;
253
+ int wrapAdvance = 0;
254
+ int wrapLastWidth = 0;
255
+
256
+ for (; j < childCount_; j++) {
257
+ const int child = children_[j];
258
+ Node &cn = nodes[child];
259
+ const int marginL = cn.style.margin[3];
260
+ const int marginR = cn.style.margin[1];
261
+ const int gap = pen > 0 ? gapStyle : 0;
262
+
263
+ // The run this item contributes to the line: itself when it IS a text
264
+ // run, or the one inside a transparent <span> wrapper.
265
+ const int innerRun = isFragmentableRun(cn) ? -1 : transparentInlineRun(cn);
266
+ Node &subject = innerRun >= 0 ? nodes[innerRun] : cn;
267
+ if (isFragmentableRun(subject)) {
268
+ const int padH = subject.style.padding[1] + subject.style.padding[3];
269
+ const int padV = subject.style.padding[0] + subject.style.padding[2];
270
+ // Budgets are TEXT widths: the run's own padding is part of its box,
271
+ // not of the line it can fill.
272
+ const int rest = contentW - marginL - marginR - padH;
273
+ const int firstAvail = rest - pen - gap;
274
+ const bool atLineStart = pen == 0 && (j > 0 || blockOpensItsFirstLine);
275
+ const InlineFlowMeasure m =
276
+ TextRenderer::measureInlineFlow(subject, firstAvail, rest, atLineStart);
277
+ // Without real line metrics childFirstBaseline reports the box's
278
+ // bottom edge, which is only a baseline for a ONE-line box. Such a
279
+ // run keeps flowing whole, exactly as before.
280
+ const bool haveLineMetrics =
281
+ m.lineAdvance > 0 &&
282
+ childFirstBaseline(subject) <= subject.style.padding[0] + m.lineAdvance;
283
+ if (m.lineCount > 0 && haveLineMetrics) {
284
+ // Its first WORD does not fit what is left: the run starts the
285
+ // next line box rather than overflowing it or being cut open.
286
+ if (pen > 0 && (m.firstLineWidth > firstAvail || m.firstLineForcedSplit)) break;
287
+ const int boxH = m.lineCount * m.lineAdvance + padV;
288
+ const bool wraps = m.lineCount > 1;
289
+ const int boxW = wraps ? rest + padH : m.firstLineWidth + padH;
290
+ const int indent =
291
+ (wraps ? pen + gap : 0) + m.firstLineIndentAdjust;
292
+ subject.layout.height = clampInt16(boxH);
293
+ subject.layout.width = clampInt16(boxW);
294
+ subject.layout.inline_indent = clampInt16(indent);
295
+ if (innerRun >= 0) {
296
+ // The wrapper is transparent: it takes the run's box exactly, and
297
+ // the run sits at its origin, so childFirstBaseline's recursion
298
+ // through the wrapper still lands on the run's own baseline.
299
+ subject.layout.x = 0;
300
+ subject.layout.y = 0;
301
+ cn.layout.height = clampInt16(boxH);
302
+ cn.layout.width = clampInt16(boxW);
303
+ cn.layout.inline_indent = clampInt16(indent);
304
+ }
305
+ if (wraps) {
306
+ const int ascent = cn.style.margin[0] + childFirstBaseline(cn);
307
+ const int descent = runLineDescent(subject, m.lineAdvance);
308
+ if (ascent > lineAscent) lineAscent = ascent;
309
+ if (descent > lineDescent) lineDescent = descent;
310
+ pen += gap + marginL + m.firstLineWidth + marginR + padH;
311
+ if (m.maxLineWidth + padH > maxLineWidth) maxLineWidth = m.maxLineWidth + padH;
312
+ wrapIdx = j;
313
+ wrapSpans = m.lineCount;
314
+ wrapAdvance = m.lineAdvance;
315
+ wrapLastWidth = m.lastLineWidth + padH;
316
+ j++;
317
+ break; // the run closes this line box
318
+ }
319
+ }
320
+ } else {
321
+ cn.layout.inline_indent = 0;
322
+ }
323
+
324
+ const int itemMain = cn.layout.width + marginL + marginR;
325
+ if (pen > 0 && pen + gap + itemMain > contentW) break;
326
+ const int ascent = cn.style.margin[0] + childFirstBaseline(cn);
327
+ const int descent = cn.layout.height + cn.style.margin[2] - childFirstBaseline(cn);
328
+ if (ascent > lineAscent) lineAscent = ascent;
329
+ if (descent > lineDescent) lineDescent = descent;
330
+ pen += gap + itemMain;
331
+ }
332
+
333
+ if (pen > maxLineWidth) maxLineWidth = pen;
334
+
335
+ const int baseline = continuing ? continuedBaseline : lineTop + lineAscent;
336
+ lineTop = baseline - lineAscent;
337
+ int lineCross = lineAscent + lineDescent;
338
+ if (lineCross < 0) lineCross = 0;
339
+ // The one case the flex path's expandCrossSizes is observable here: a
340
+ // lone line box in a block with a definite height fills it, so
341
+ // `align-self: center/end` on an inline child has room to work.
342
+ if (i == 0 && j >= childCount_ && wrapIdx < 0 && hasExplicitHeight(node_) &&
343
+ padHeight_ > lineCross)
344
+ lineCross = padHeight_;
345
+
346
+ placeLineItems(nodes, i, j, contentLeft, contentW, lineTop, lineCross, baseline, penStart,
347
+ !lineIsContinuation);
348
+
349
+ if (baseline + lineDescent > flowBottom) flowBottom = baseline + lineDescent;
350
+ if (lineTop + lineCross > flowBottom) flowBottom = lineTop + lineCross;
351
+
352
+ if (wrapIdx >= 0) {
353
+ Node &run = nodes[children_[wrapIdx]];
354
+ const int runBaseline = run.layout.y + childFirstBaseline(run);
355
+ continuedBaseline = runBaseline + (wrapSpans - 1) * wrapAdvance;
356
+ inheritedAscent = run.style.margin[0] + childFirstBaseline(run);
357
+ inheritedDescent = runLineDescent(run, wrapAdvance);
358
+ penStart = run.style.margin[3] + wrapLastWidth + run.style.margin[1];
359
+ continuing = true;
360
+ if (continuedBaseline + inheritedDescent > flowBottom)
361
+ flowBottom = continuedBaseline + inheritedDescent;
362
+ if (penStart > maxLineWidth) maxLineWidth = penStart;
363
+ } else {
364
+ lineTop = baseline + lineDescent + gapStyle;
365
+ penStart = 0;
366
+ continuing = false;
367
+ inheritedAscent = 0;
368
+ inheritedDescent = 0;
369
+ }
370
+
371
+ // A line box that took no item and inherited no run tail would spin. The
372
+ // scan only produces that for an item wider than the whole box, so place
373
+ // it anyway. A continuation line legitimately ends empty — its content is
374
+ // the run's last line — and the item that did not fit opens the next one.
375
+ if (j == i && !lineIsContinuation) j = i + 1;
376
+ i = j;
377
+ }
378
+
379
+ if (!autosize) return;
380
+ // Same rules as autosizeParent: a scroll container keeps the size it was
381
+ // given on its scrolling axis so its overflow becomes scroll range.
382
+ const int flowHeight = flowBottom - contentTop;
383
+ const bool keepScrollHeight = scrollsOverflowY(node_.style) && node_.layout.height > 0;
384
+ const bool keepScrollWidth = scrollsOverflowX(node_.style) && node_.layout.width > 0;
385
+ if (!hasExplicitHeight(node_) && !keepScrollHeight) {
386
+ const int height = (flowHeight < 0 ? 0 : flowHeight) + node_.style.padding[0] + node_.style.padding[2];
387
+ node_.layout.height = clampInt16(engine_.clampSize(height, node_.style.min_height, node_.style.max_height));
388
+ }
389
+ if (!hasExplicitWidth(node_) && !keepScrollWidth) {
390
+ const int width = maxLineWidth + node_.style.padding[1] + node_.style.padding[3];
391
+ node_.layout.width = clampInt16(engine_.clampSize(width, node_.style.min_width, node_.style.max_width));
392
+ }
393
+ }
394
+
395
+ // A text run whose line breaking this engine owns, and which therefore flows
396
+ // into the block's line boxes instead of occupying one whole. An author-sized
397
+ // or nowrap run keeps its own box.
398
+ static bool isFragmentableRun(const Node &n)
399
+ {
400
+ return n.type == NodeType::Text && !n.text.empty() && n.style.white_space != 1 &&
401
+ n.style.width == kUnset && n.style.width_percent == kUnset;
402
+ }
403
+
404
+ // True when nothing about `n`'s BOX is visible — no background, border, shadow,
405
+ // transform or blur. Such a wrapper can take whatever geometry inline flow finds
406
+ // convenient, because only its content is ever painted.
407
+ static bool paintsNoBox(const Node &n)
408
+ {
409
+ if (n.style.has_bg || n.style.border_width > 0 || hasSideBorder(n.style)) return false;
410
+ #if GEA_EMBEDDED_RARE_STYLE_INLINE
411
+ const RareStyle &r = rstyle(n.style);
412
+ if (r.transform_rotate || r.transform_rotate_x || r.transform_rotate_y ||
413
+ r.transform_translate_x || r.transform_translate_y || r.transform_translate_z ||
414
+ r.transform_translate_x_percent || r.transform_translate_y_percent ||
415
+ r.transform_scale_x != 1000 || r.transform_scale_y != 1000 || r.perspective ||
416
+ r.box_shadow_alpha || r.filter_blur_radius)
417
+ return false;
418
+ #else
419
+ // No rare-style record at all: no transform, shadow, gradient or filter was
420
+ // ever set on this node.
421
+ if (n.style.rare_style >= 0) return false;
422
+ #endif
423
+ return true;
424
+ }
425
+
426
+ // A <span> that only wraps text is TRANSPARENT to inline flow: CSS breaks lines
427
+ // inside it exactly as if its content sat directly in the paragraph, which is
428
+ // why `<p>… <span>score value</span> …</p>` may put "score" on one line and
429
+ // "value" on the next. Returns that inner run, or -1 when the wrapper has a box
430
+ // a reader could see, or holds anything other than one plain text run.
431
+ int transparentInlineRun(const Node &wrapper) const
432
+ {
433
+ if (wrapper.type != NodeType::View) return -1;
434
+ if (!paintsNoBox(wrapper)) return -1;
435
+ if (wrapper.style.padding[0] || wrapper.style.padding[1] || wrapper.style.padding[2] ||
436
+ wrapper.style.padding[3])
437
+ return -1;
438
+ if (hasExplicitWidth(wrapper) || hasExplicitHeight(wrapper)) return -1;
439
+ if (wrapper.style.min_width > 0 || wrapper.style.min_height > 0) return -1;
440
+ if (wrapper.style.max_width != kUnset || wrapper.style.max_height != kUnset) return -1;
441
+ if (wrapper.style.overflow_x || wrapper.style.overflow_y) return -1;
442
+ if (wrapper.style.align_self >= 0 || wrapper.style.flex > 0 ||
443
+ wrapper.style.flex_basis != kUnset)
444
+ return -1;
445
+ const Node *nodes = Tree::instance().nodes();
446
+ int run = -1;
447
+ for (int c = wrapper.first_child; c >= 0; c = nodes[c].next_sibling) {
448
+ const Node &child = nodes[c];
449
+ if (isDisplayNone(child.style) || child.style.position == 1) continue;
450
+ if (run >= 0) return -1; // more than one in-flow child
451
+ if (child.type != NodeType::Text) return -1;
452
+ if (child.style.margin[0] || child.style.margin[1] || child.style.margin[2] ||
453
+ child.style.margin[3])
454
+ return -1;
455
+ if (!isFragmentableRun(child)) return -1;
456
+ run = c;
457
+ }
458
+ return run;
459
+ }
460
+
461
+ // Distance from ONE of a run's line baselines to the bottom of that line box,
462
+ // including the run's own bottom padding/margin (which only the last line
463
+ // actually carries — the others are flush, so this is the taller, safe value).
464
+ int runLineDescent(const Node &n, int lineAdvance) const
465
+ {
466
+ const int ascender = childFirstBaseline(n) - n.style.padding[0];
467
+ const int descent = lineAdvance - ascender + n.style.padding[2] + n.style.margin[2];
468
+ return descent < 0 ? 0 : descent;
469
+ }
470
+
471
+ void placeLineItems(Node *nodes, int from, int to, int contentLeft, int contentW, int lineTop,
472
+ int lineCross, int baseline, int penStart, bool ownsLineStart)
473
+ {
474
+ const bool soleRun =
475
+ ownsLineStart && (to - from) == 1 && nodes[children_[from]].type == NodeType::Text;
476
+ // Anything sharing this line box is placed on its shared baseline, and must
477
+ // be DRAWN there — see RenderState::inline_baseline. A run that has the line
478
+ // to itself keeps the renderer's ink centring.
479
+ const bool sharesLine = (to - from) > 1 || !ownsLineStart;
480
+ int pen = penStart;
481
+ for (int k = from; k < to; k++) {
482
+ const int child = children_[k];
483
+ Node &cn = nodes[child];
484
+ const int marginL = cn.style.margin[3];
485
+ const int marginR = cn.style.margin[1];
486
+ const int gap = pen > 0 ? node_.style.gap : 0;
487
+
488
+ if (cn.layout.inline_indent > 0) {
489
+ // A wrapped continuation keeps a full-width box at the block's left
490
+ // edge; its indent is what carries the pen it started from.
491
+ cn.layout.x = clampInt16(contentLeft + marginL);
492
+ } else {
493
+ cn.layout.x = clampInt16(contentLeft + pen + gap + marginL);
494
+ }
495
+ pen += gap + marginL + cn.layout.width + marginR;
496
+
497
+ if (soleRun && !hasExplicitWidth(cn)) {
498
+ // text-align needs a box as wide as the line box to align inside.
499
+ const int full = contentW - marginL - marginR;
500
+ if (full > cn.layout.width) cn.layout.width = clampInt16(full);
501
+ }
502
+
503
+ int y = baseline - childFirstBaseline(cn);
504
+ const int align = crossAlignFor(cn);
505
+ if (align != 5) {
506
+ const int crossBefore = cn.style.margin[0];
507
+ const int crossAfter = cn.style.margin[2];
508
+ const int crossTotal = cn.layout.height + crossBefore + crossAfter;
509
+ y = lineTop + crossBefore;
510
+ if (align == 1) y += (lineCross - crossTotal) / 2;
511
+ else if (align == 2) y += lineCross - crossTotal;
512
+ else if (align == 0 && !hasExplicitHeight(cn)) {
513
+ cn.layout.height = clampInt16(lineCross - crossBefore - crossAfter);
514
+ engine_.repositionChildren(child);
515
+ }
516
+ }
517
+ cn.layout.y = clampInt16(y);
518
+ cn.render.inline_baseline = sharesLine ? 1 : 0;
519
+ // An inline wrapper (<span>text</span>) contributes its CHILD's glyphs to
520
+ // this line box, so the flag has to reach the node that actually draws.
521
+ if (cn.type == NodeType::View) {
522
+ for (int c = cn.first_child; c >= 0; c = nodes[c].next_sibling)
523
+ if (nodes[c].type == NodeType::Text) nodes[c].render.inline_baseline = sharesLine ? 1 : 0;
524
+ }
525
+ }
526
+ }
527
+
528
+ void expandCrossSizes(int lineCount, bool onlyIfDefinite)
529
+ {
530
+ const bool hasDefiniteCross = isRow_ ? hasExplicitHeight(node_) : hasExplicitWidth(node_);
531
+ if (onlyIfDefinite && !hasDefiniteCross) return;
532
+
533
+ const int crossAvail = isRow_ ? padHeight_ : padWidth_;
534
+ if (lineCount == 1) {
535
+ lines_[0].crossSize = crossAvail;
536
+ } else if (lineCount > 1) {
537
+ int totalLineCross = 0;
538
+ for (int i = 0; i < lineCount; i++) totalLineCross += lines_[i].crossSize;
539
+ const int extra = crossAvail - totalLineCross - (lineCount - 1) * node_.style.gap;
540
+ if (extra > 0) {
541
+ const int perLine = extra / lineCount;
542
+ for (int i = 0; i < lineCount; i++) lines_[i].crossSize += perLine;
543
+ }
544
+ }
545
+ }
546
+
547
+ void positionLines(int lineCount)
548
+ {
549
+ Node *nodes = Tree::instance().nodes();
550
+ int crossOffset = isRow_ ? node_.style.padding[0] : node_.style.padding[3];
551
+
552
+ // Free main-axis space is measured against the node's FINAL padded main size
553
+ // (set by autosizeParent before this runs), NOT the available space it was
554
+ // offered. An auto-sized box shrinks to its content, so it has zero free
555
+ // space — distributing `mainAvail_ - content` here would, e.g., center a
556
+ // label using the parent's full width and then leave it stranded once the
557
+ // box shrinks to fit. Reading layout.{width,height} also gives the correct
558
+ // free space when a flex item was GROWN past its content by its parent.
559
+ const int mainBox = isRow_
560
+ ? (node_.layout.width - node_.style.padding[1] - node_.style.padding[3])
561
+ : (node_.layout.height - node_.style.padding[0] - node_.style.padding[2]);
562
+ const int mainContentBox = mainBox < 0 ? 0 : mainBox;
563
+
564
+ for (int lineIndex = 0; lineIndex < lineCount; lineIndex++) {
565
+ FlexLine &line = lines_[lineIndex];
566
+ int remaining = mainContentBox - line.mainSize;
567
+
568
+ const int totalGrow = totalFlexGrowForLine(line, nodes);
569
+ if (remaining > 0 && totalGrow > 0) {
570
+ growFlexChildren(line, nodes, totalGrow, remaining);
571
+ remaining = 0;
572
+ } else if (remaining < 0) {
573
+ // A container that scrolls along the main axis lets overflowing content
574
+ // stay at its natural size and become scroll range instead of being
575
+ // flex-shrunk to fit. Without this, a scrollable column (typography
576
+ // specimen page) compresses every section into the viewport —
577
+ // scroll_content_height never exceeds height and the page can't scroll.
578
+ // (CSS floors shrink at min-content, which for stacked text is its
579
+ // natural size; this engine has no min-content plumbing, so the scroll
580
+ // container skips main-axis shrink entirely — the pre-flex-shrink
581
+ // behavior for scrollable boxes.)
582
+ const bool mainAxisScrolls =
583
+ isRow_ ? scrollsOverflowX(node_.style) : scrollsOverflowY(node_.style);
584
+ if (!mainAxisScrolls) {
585
+ const int totalShrink = totalFlexShrinkForLine(line, nodes);
586
+ if (totalShrink > 0) {
587
+ shrinkFlexChildren(line, nodes, totalShrink, remaining);
588
+ remaining = 0;
589
+ }
590
+ }
591
+ } else if (totalGrow > 0) {
592
+ // Free space is exactly zero, so no resize call runs — but the
593
+ // flex items were zeroed for measurement (applyFlexBasis) and no
594
+ // longer reposition there; give the still-zeroed ones their one
595
+ // subtree layout at the final (zero) size.
596
+ for (int i = 0; i < line.count; i++) {
597
+ const int child = children_[line.start + i];
598
+ Node &childNode = nodes[child];
599
+ if (childNode.style.flex <= 0) continue;
600
+ const int mainSize = isRow_ ? childNode.layout.width : childNode.layout.height;
601
+ if (mainSize == 0) engine_.repositionChildren(child);
602
+ }
603
+ }
604
+ if (remaining < 0 && node_.style.justify_content != 1 && node_.style.justify_content != 2) remaining = 0;
605
+
606
+ int mainOffset = isRow_ ? node_.style.padding[3] : node_.style.padding[0];
607
+ int gapSpace = 0;
608
+ applyJustifyContent(line, remaining, &mainOffset, &gapSpace);
609
+ positionLineChildren(line, nodes, mainOffset, crossOffset, gapSpace);
610
+ crossOffset += line.crossSize + node_.style.gap;
611
+ }
612
+ }
613
+
614
+ void autosizeParent(int lineCount)
615
+ {
616
+ // A scroll container keeps the size its parent already gave it (flex grow,
617
+ // stretch, or a definite parent box in `layout.{height,width}` from
618
+ // prepareOwnSize) instead of auto-growing to its content on the scrolling
619
+ // axis. Otherwise scroll_content_{height,width} == layout.{height,width},
620
+ // scrollMax is 0, and the container never scrolls. This matches CSS:
621
+ // overflow:scroll/auto clips/scrolls its overflow, it does not expand to
622
+ // fit content. Guarded on a positive assigned size so an unsized scroll
623
+ // container still autosizes as before.
624
+ const bool keepScrollHeight = scrollsOverflowY(node_.style) && node_.layout.height > 0;
625
+ const bool keepScrollWidth = scrollsOverflowX(node_.style) && node_.layout.width > 0;
626
+
627
+ if (!hasExplicitHeight(node_) && !keepScrollHeight) {
628
+ const int height = (isRow_ ? totalCrossSize(lineCount) : maxMainSize(lineCount)) + node_.style.padding[0] + node_.style.padding[2];
629
+ node_.layout.height = engine_.clampSize(height, node_.style.min_height, node_.style.max_height);
630
+ }
631
+
632
+ if (!hasExplicitWidth(node_) && !keepScrollWidth) {
633
+ const int width = (isRow_ ? maxMainSize(lineCount) : totalCrossSize(lineCount)) + node_.style.padding[1] + node_.style.padding[3];
634
+ node_.layout.width = engine_.clampSize(width, node_.style.min_width, node_.style.max_width);
635
+ }
636
+ }
637
+
638
+ private:
639
+ void applyFlexBasis(int child)
640
+ {
641
+ Node &childNode = Tree::instance().nodes()[child];
642
+ // A definite flex-basis (e.g. `flex: 0 0 26px`) sets the item's main-axis
643
+ // size directly, overriding the size measured from content/fill. flex-grow
644
+ // and flex-shrink then resize from this basis in positionLines, and a
645
+ // flex:0 0 item stays exactly at its basis. This is what makes the weather
646
+ // forecast's `.hour`/`.day` cards 26/40px wide instead of stretching to fill
647
+ // the row. An explicit width/height still wins.
648
+ if (childNode.style.flex_basis != kUnset) {
649
+ if (isRow_) {
650
+ if (hasExplicitWidth(childNode)) return;
651
+ const int basis = clampFlexMainSize(childNode, childNode.style.flex_basis);
652
+ if (childNode.layout.width != basis) {
653
+ childNode.layout.width = basis;
654
+ engine_.repositionChildren(child);
655
+ }
656
+ } else {
657
+ if (hasExplicitHeight(childNode)) return;
658
+ const int basis = clampFlexMainSize(childNode, childNode.style.flex_basis);
659
+ if (childNode.layout.height != basis) {
660
+ childNode.layout.height = basis;
661
+ engine_.repositionChildren(child);
662
+ }
663
+ }
664
+ return;
665
+ }
666
+ if (childNode.style.flex <= 0) return;
667
+ if (isRow_) {
668
+ if (hasExplicitWidth(childNode)) return;
669
+ if (childNode.layout.width == 0) return;
670
+ childNode.layout.width = 0;
671
+ } else {
672
+ if (hasExplicitHeight(childNode)) return;
673
+ if (childNode.layout.height == 0) return;
674
+ childNode.layout.height = 0;
675
+ }
676
+ // No repositionChildren here: the zeroed main size exists only for
677
+ // buildLines' measurement, and growFlexChildren repositions the item
678
+ // at its grown size moments later — recursively re-laying the subtree
679
+ // at width/height 0 in between was the biggest source of redundant
680
+ // layout work on nested-flex trees. The one case where no grow follows
681
+ // (free space exactly 0) is compensated in positionLines.
682
+ }
683
+
684
+ void appendLine(int &lineCount, int start, int count, int mainSize, int crossSize)
685
+ {
686
+ if (lineCount >= kMaxFlexLines) return;
687
+ lines_[lineCount].start = start;
688
+ lines_[lineCount].count = count;
689
+ lines_[lineCount].mainSize = mainSize;
690
+ lines_[lineCount].crossSize = crossSize;
691
+ lineCount++;
692
+ }
693
+
694
+ int totalFlexGrowForLine(const FlexLine &line, Node *nodes) const
695
+ {
696
+ int totalFlex = 0;
697
+ for (int i = 0; i < line.count; i++) {
698
+ totalFlex += nodes[children_[line.start + i]].style.flex;
699
+ }
700
+ return totalFlex;
701
+ }
702
+
703
+ int childMainSize(const Node &childNode) const
704
+ {
705
+ return isRow_ ? childNode.layout.width : childNode.layout.height;
706
+ }
707
+
708
+ // A text leaf's height IS its wrapped content height: the renderer draws
709
+ // every wrapped line regardless of layout.height, so compressing it on a
710
+ // column's main axis just makes the following sibling overlap the glyphs
711
+ // (CSS floors flex shrink at the item's automatic minimum size — for text,
712
+ // its min-content height). Treat column-axis text as non-shrinkable; the
713
+ // deficit redistributes to shrinkable siblings or becomes overflow.
714
+ bool childMainSizeIsShrinkable(const Node &childNode) const
715
+ {
716
+ if (childNode.style.flex_shrink <= 0) return false;
717
+ if (!isRow_ && childNode.type == NodeType::Text) return false;
718
+ return true;
719
+ }
720
+
721
+ int totalFlexShrinkForLine(const FlexLine &line, Node *nodes) const
722
+ {
723
+ int totalShrink = 0;
724
+ for (int i = 0; i < line.count; i++) {
725
+ const Node &childNode = nodes[children_[line.start + i]];
726
+ if (!childMainSizeIsShrinkable(childNode)) continue;
727
+ const int basis = childMainSize(childNode);
728
+ if (basis <= 0) continue;
729
+ totalShrink += childNode.style.flex_shrink * basis;
730
+ }
731
+ return totalShrink;
732
+ }
733
+
734
+ void growFlexChildren(const FlexLine &line, Node *nodes, int totalGrow, int delta)
735
+ {
736
+ if (totalGrow <= 0 || delta <= 0) return;
737
+ int applied = 0;
738
+ int lastGrowChild = -1;
739
+
740
+ for (int i = 0; i < line.count; i++) {
741
+ const int child = children_[line.start + i];
742
+ Node &childNode = nodes[child];
743
+ if (childNode.style.flex <= 0) continue;
744
+ lastGrowChild = child;
745
+ const int change = (delta * childNode.style.flex) / totalGrow;
746
+ applied += applyFlexMainSizeDelta(child, childNode, change);
747
+ }
748
+
749
+ const int remainder = delta - applied;
750
+ if (remainder > 0 && lastGrowChild >= 0) {
751
+ Node &childNode = nodes[lastGrowChild];
752
+ applyFlexMainSizeDelta(lastGrowChild, childNode, remainder);
753
+ }
754
+ }
755
+
756
+ void shrinkFlexChildren(const FlexLine &line, Node *nodes, int totalShrink, int delta)
757
+ {
758
+ if (totalShrink <= 0 || delta >= 0) return;
759
+ const int magnitude = -delta;
760
+ int applied = 0;
761
+ int lastShrinkChild = -1;
762
+
763
+ for (int i = 0; i < line.count; i++) {
764
+ const int child = children_[line.start + i];
765
+ Node &childNode = nodes[child];
766
+ if (!childMainSizeIsShrinkable(childNode)) continue;
767
+ const int basis = childMainSize(childNode);
768
+ if (basis <= 0) continue;
769
+ lastShrinkChild = child;
770
+ const int change = (magnitude * childNode.style.flex_shrink * basis) / totalShrink;
771
+ applied += applyFlexMainSizeDelta(child, childNode, -change);
772
+ }
773
+
774
+ const int remainder = magnitude - applied;
775
+ if (remainder > 0 && lastShrinkChild >= 0) {
776
+ Node &childNode = nodes[lastShrinkChild];
777
+ applyFlexMainSizeDelta(lastShrinkChild, childNode, -remainder);
778
+ }
779
+ }
780
+
781
+ // CSS `min-width: auto` / `min-height: auto` — a flex item's AUTOMATIC MINIMUM
782
+ // SIZE: an item may not be flex-shrunk below what its own in-flow content needs.
783
+ // The engine already honours this for text leaves (see childMainSizeIsShrinkable);
784
+ // a container has to be measured, because a line's whole deficit lands on however
785
+ // few items are shrinkable. On the temperature dial the face column overflows by
786
+ // ~49px and its fan pill (`height: 8.125vmin`) was the ONLY shrinkable item, so it
787
+ // absorbed all of it, clamped to zero, and laid out 112x0 — the pill, its dot and
788
+ // its label recorded no commands at all. CSS overflows the container instead.
789
+ // Applies exactly where CSS applies it: no explicit min on that axis (an explicit
790
+ // one already floors clampSize), and overflow visible on the main axis — a
791
+ // scroll/hidden box really does have a zero automatic minimum.
792
+ int automaticMinimumMainSize(const Node &childNode) const
793
+ {
794
+ const int explicitMin = isRow_ ? childNode.style.min_width : childNode.style.min_height;
795
+ if (explicitMin > 0) return 0;
796
+ if (isRow_ ? childNode.style.overflow_x : childNode.style.overflow_y) return 0;
797
+ if (childNode.first_child < 0) return 0;
798
+ const Node *nodes = Tree::instance().nodes();
799
+ int extent = 0;
800
+ for (int c = childNode.first_child; c >= 0; c = nodes[c].next_sibling) {
801
+ const Node &grand = nodes[c];
802
+ if (isDisplayNone(grand.style) || grand.style.position == 1) continue;
803
+ // layout.{x,y} are still parent-relative here: resolveAbsoluteCoords runs
804
+ // after the whole layout pass.
805
+ const int end = isRow_
806
+ ? grand.layout.x + grand.layout.width + grand.style.margin[1]
807
+ : grand.layout.y + grand.layout.height + grand.style.margin[2];
808
+ if (end > extent) extent = end;
809
+ }
810
+ if (extent <= 0) return 0;
811
+ extent += isRow_ ? childNode.style.padding[1] : childNode.style.padding[2];
812
+ return extent;
813
+ }
814
+
815
+ int applyFlexMainSizeDelta(int child, Node &childNode, int delta)
816
+ {
817
+ if (delta == 0) return 0;
818
+ const int before = isRow_ ? childNode.layout.width : childNode.layout.height;
819
+ int after = before + delta;
820
+ after = clampFlexMainSize(childNode, after);
821
+ if (delta < 0) {
822
+ // Floor the shrink at the automatic minimum size, and never let that floor
823
+ // GROW an item that was already smaller than its content.
824
+ const int autoMin = automaticMinimumMainSize(childNode);
825
+ const int minAllowed = autoMin < before ? autoMin : before;
826
+ if (after < minAllowed) after = minAllowed;
827
+ }
828
+ if (after == before) return 0;
829
+ if (isRow_) childNode.layout.width = after;
830
+ else childNode.layout.height = after;
831
+ engine_.repositionChildren(child);
832
+ return delta > 0 ? after - before : before - after;
833
+ }
834
+
835
+ int clampFlexMainSize(const Node &childNode, int size) const
836
+ {
837
+ const int minSize = isRow_ ? childNode.style.min_width : childNode.style.min_height;
838
+ const int maxSize = isRow_ ? childNode.style.max_width : childNode.style.max_height;
839
+ const int clamped = engine_.clampSize(size, minSize, maxSize);
840
+ return clamped < 0 ? 0 : clamped;
841
+ }
842
+
843
+ void applyJustifyContent(const FlexLine &line, int remaining, int *mainOffset, int *gapSpace) const
844
+ {
845
+ switch (node_.style.justify_content) {
846
+ case 0:
847
+ break;
848
+ case 1:
849
+ *mainOffset += remaining / 2;
850
+ break;
851
+ case 2:
852
+ *mainOffset += remaining;
853
+ break;
854
+ case 3:
855
+ if (line.count > 1) *gapSpace = remaining / (line.count - 1);
856
+ break;
857
+ case 4:
858
+ if (line.count > 0) {
859
+ const int space = remaining / line.count;
860
+ *mainOffset += space / 2;
861
+ *gapSpace = space;
862
+ }
863
+ break;
864
+ }
865
+ }
866
+
867
+ void positionLineChildren(const FlexLine &line, Node *nodes, int mainOffset, int crossOffset, int gapSpace)
868
+ {
869
+ // First baselines of this line's baseline-aligned children (rows only):
870
+ // every such child's baseline lands on the line's max baseline, matching
871
+ // CSS `align-items: baseline` (a 12px range label shares the 14px
872
+ // condition's baseline instead of top-aligning).
873
+ int lineMaxBaseline = 0;
874
+ if (isRow_) {
875
+ for (int i = 0; i < line.count; i++) {
876
+ Node &probe = nodes[children_[line.start + i]];
877
+ if (crossAlignFor(probe) != 5) continue;
878
+ const int baseline = probe.style.margin[0] + childFirstBaseline(probe);
879
+ if (baseline > lineMaxBaseline) lineMaxBaseline = baseline;
880
+ }
881
+ }
882
+
883
+ for (int i = 0; i < line.count; i++) {
884
+ const int child = children_[line.start + i];
885
+ Node &childNode = nodes[child];
886
+
887
+ const int mainMarginBefore = isRow_ ? childNode.style.margin[3] : childNode.style.margin[0];
888
+ const int mainMarginAfter = isRow_ ? childNode.style.margin[1] : childNode.style.margin[2];
889
+ const int crossMarginBefore = isRow_ ? childNode.style.margin[0] : childNode.style.margin[3];
890
+ const int crossMarginAfter = isRow_ ? childNode.style.margin[2] : childNode.style.margin[1];
891
+ const int crossSize = isRow_ ? childNode.layout.height : childNode.layout.width;
892
+ const int crossTotal = crossSize + crossMarginBefore + crossMarginAfter;
893
+
894
+ mainOffset += mainMarginBefore;
895
+ int crossPosition = crossOffset + crossMarginBefore;
896
+ positionCrossAxisChild(child, childNode, line.crossSize, crossMarginBefore, crossMarginAfter, crossTotal, &crossPosition, lineMaxBaseline);
897
+
898
+ if (isRow_) {
899
+ childNode.layout.x = mainOffset;
900
+ childNode.layout.y = crossPosition;
901
+ } else {
902
+ childNode.layout.x = crossPosition;
903
+ childNode.layout.y = mainOffset;
904
+ }
905
+
906
+ const int mainSize = isRow_ ? childNode.layout.width : childNode.layout.height;
907
+ mainOffset += mainSize + mainMarginAfter + node_.style.gap + gapSpace;
908
+ // Flex items own their boxes; nothing here shares a line box.
909
+ childNode.render.inline_baseline = 0;
910
+ }
911
+ }
912
+
913
+ // Cross-axis alignment in force for one item. `align-self` always wins.
914
+ // Otherwise an INLINE formatting row aligns on the shared baseline — that is
915
+ // what an inline formatting context does, and `align-items` has no effect on
916
+ // a block container, so the parent's value is not consulted there. A real
917
+ // flex container keeps reading `align-items`.
918
+ int crossAlignFor(const Node &childNode) const
919
+ {
920
+ if (childNode.style.align_self >= 0) return childNode.style.align_self;
921
+ return inlineRow_ ? 5 : node_.style.align_items;
922
+ }
923
+
924
+ void positionCrossAxisChild(int child, Node &childNode, int lineCrossSize, int crossMarginBefore, int crossMarginAfter, int crossTotal, int *crossPosition, int lineMaxBaseline)
925
+ {
926
+ const int align = crossAlignFor(childNode);
927
+ switch (align) {
928
+ case 0:
929
+ if (isRow_) {
930
+ if (!hasExplicitHeight(childNode)) {
931
+ childNode.layout.height = lineCrossSize - crossMarginBefore - crossMarginAfter;
932
+ engine_.repositionChildren(child);
933
+ }
934
+ } else if (!hasExplicitWidth(childNode)) {
935
+ childNode.layout.width = lineCrossSize - crossMarginBefore - crossMarginAfter;
936
+ engine_.repositionChildren(child);
937
+ }
938
+ break;
939
+ case 1:
940
+ *crossPosition += (lineCrossSize - crossTotal) / 2;
941
+ break;
942
+ case 2:
943
+ *crossPosition += lineCrossSize - crossTotal;
944
+ break;
945
+ case 5:
946
+ // align-items/align-self: baseline (rows). Columns fall back to start,
947
+ // matching CSS, where baseline alignment only applies across an inline axis.
948
+ if (isRow_) {
949
+ const int shift = lineMaxBaseline - (crossMarginBefore + childFirstBaseline(childNode));
950
+ if (shift > 0) *crossPosition += shift;
951
+ }
952
+ break;
953
+ }
954
+ }
955
+
956
+ // First-baseline of a flex child, measured from its border-box top. Text
957
+ // leaves use the resolved atlas font's ascender — the glyph rasterizer
958
+ // places runs at `top + ascender - bearingY`, so this matches the drawn
959
+ // pixels exactly. Anything without measurable text synthesizes its baseline
960
+ // from the bottom margin edge, as CSS does for replaced/empty boxes.
961
+ int childFirstBaseline(const Node &childNode) const
962
+ {
963
+ if (childNode.type == NodeType::Text && childNode.style.font_id >= 0) {
964
+ const int fontSize = childNode.style.font_size > 0 ? childNode.style.font_size : 16;
965
+ const gea::framework::graphics::RasterizedFont font =
966
+ gea::framework::graphics::FontRegistry::rasterizedFamily(childNode.style.font_id, fontSize);
967
+ if (font.valid()) {
968
+ // CSS half-leading: when line-height exceeds the font's own line box the
969
+ // extra room is split above and below it, so the glyphs — and the
970
+ // baseline with them — sit that much lower. TextDrawer applies exactly
971
+ // this offset when it paints (`lineBoxOffset`), and a baseline that
972
+ // ignores it is wrong by half the difference. That went unnoticed while
973
+ // every run occupied its own line; once runs of different FONTS share
974
+ // one, each carries a different font line height and they visibly
975
+ // stagger (typography's ", a" riding above the Inter and Oswald spans
976
+ // around it).
977
+ const int lineAdvance =
978
+ childNode.style.line_height > 0 ? childNode.style.line_height : font.lineHeight();
979
+ const int halfLeading =
980
+ childNode.style.line_height > 0 ? (lineAdvance - font.lineHeight()) / 2 : 0;
981
+ return childNode.style.padding[0] + halfLeading + font.ascender();
982
+ }
983
+ }
984
+ // An inline wrapper (a <span> around text) carries no text of its own, so
985
+ // CSS takes the baseline of its FIRST in-flow line box. Its children were
986
+ // already positioned by measureChildren, and layout.y is still parent-
987
+ // relative at this point, so the child's own offset inside the wrapper is
988
+ // exactly its baseline's distance from the wrapper's top. Without this a
989
+ // span-wrapped run reported its bottom margin edge as its baseline and
990
+ // dropped below every bare text run beside it.
991
+ if (childNode.type == NodeType::View && childNode.first_child >= 0) {
992
+ const Node *nodes = Tree::instance().nodes();
993
+ for (int c = childNode.first_child; c >= 0; c = nodes[c].next_sibling) {
994
+ const Node &inner = nodes[c];
995
+ if (isDisplayNone(inner.style) || inner.style.position == 1) continue;
996
+ return inner.layout.y + childFirstBaseline(inner);
997
+ }
998
+ }
999
+ return childNode.layout.height + childNode.style.margin[2];
1000
+ }
1001
+
1002
+ int totalCrossSize(int lineCount) const
1003
+ {
1004
+ int total = 0;
1005
+ for (int i = 0; i < lineCount; i++) total += lines_[i].crossSize + (i > 0 ? node_.style.gap : 0);
1006
+ return total;
1007
+ }
1008
+
1009
+ int maxMainSize(int lineCount) const
1010
+ {
1011
+ int max = 0;
1012
+ for (int i = 0; i < lineCount; i++) {
1013
+ if (lines_[i].mainSize > max) max = lines_[i].mainSize;
1014
+ }
1015
+ return max;
1016
+ }
1017
+
1018
+ LayoutEngine &engine_;
1019
+ Node &node_;
1020
+ int *children_ = nullptr;
1021
+ int childCount_ = 0;
1022
+ bool isRow_ = false;
1023
+ // True when this row is a synthesized INLINE FORMATTING context (a block
1024
+ // whose in-flow children are all inline-level), not a declared flex row.
1025
+ bool inlineRow_ = false;
1026
+ int mainAvail_ = 0;
1027
+ int padWidth_ = 0;
1028
+ int padHeight_ = 0;
1029
+ FlexLine *lines_ = nullptr;
1030
+ };
1031
+
1032
+ // CSS inline-level classification. Browsers flow inline-level boxes (text,
1033
+ // replaced <img>, and inline elements like <span>/<a>/<em>) horizontally on a
1034
+ // line inside a block; gea has no separate inline formatting context, so a plain
1035
+ // block whose in-flow children are ALL inline-level is laid out as a flex row
1036
+ // (see LayoutNodePass::resolveRowDirection) to match that. A child the app gave
1037
+ // display:flex/grid is its own formatting context, not inline.
1038
+ static bool isInlineLevelTag(const char *tag)
1039
+ {
1040
+ return std::strcmp(tag, "span") == 0 || std::strcmp(tag, "a") == 0 || std::strcmp(tag, "b") == 0 ||
1041
+ std::strcmp(tag, "i") == 0 || std::strcmp(tag, "em") == 0 || std::strcmp(tag, "strong") == 0 ||
1042
+ std::strcmp(tag, "small") == 0 || std::strcmp(tag, "label") == 0 || std::strcmp(tag, "code") == 0 ||
1043
+ std::strcmp(tag, "u") == 0 || std::strcmp(tag, "sub") == 0 || std::strcmp(tag, "sup") == 0 ||
1044
+ std::strcmp(tag, "mark") == 0;
1045
+ }
1046
+
1047
+ class LayoutNodePass {
1048
+ public:
1049
+ LayoutNodePass(LayoutEngine &engine, int id, int availWidth, int availHeight)
1050
+ : engine_(engine), id_(id), availWidth_(availWidth), availHeight_(availHeight), nodes_(Tree::instance().nodes()), node_(nodes_[id])
1051
+ {
1052
+ }
1053
+
1054
+ void run()
1055
+ {
1056
+ if (isDisplayNone(node_.style)) return;
1057
+ prepareOwnSize();
1058
+
1059
+ if (node_.type == NodeType::Text) {
1060
+ const std::int64_t __tmT0 = refreshPerfNowUs();
1061
+ TextRenderer::layout(id_, availWidth_);
1062
+ refreshPerfStatsMutable().treeLayoutTextUs += refreshPerfNowUs() - __tmT0;
1063
+ return;
1064
+ }
1065
+
1066
+ if (node_.type == NodeType::Image && node_.image_id >= 0) {
1067
+ ImageRenderer::layout(id_);
1068
+ return;
1069
+ }
1070
+
1071
+ if (node_.type == NodeType::View && std::strcmp(tagFromId(node_.tag_id), "input") == 0) {
1072
+ InputRenderer::layout(id_, availWidth_);
1073
+ return;
1074
+ }
1075
+
1076
+ const int padWidth = paddedWidth();
1077
+ const int padHeight = paddedHeight();
1078
+ const bool inlineRow = resolveInlineFormattingRow();
1079
+ const bool isRow = inlineRow || resolveRowDirection();
1080
+ const int mainAvail = isRow ? padWidth : padHeight;
1081
+
1082
+ ScratchFrame scratch;
1083
+ if (!scratch.valid()) return;
1084
+
1085
+ const int childCount = engine_.collectChildren(id_, scratch.children(), kMaxChildren, true);
1086
+ if (childCount == 0) {
1087
+ autosizeEmptyNode();
1088
+ positionAbsoluteChildren();
1089
+ applyRelativeOffsets();
1090
+ applyVirtualListContentHeight();
1091
+ return;
1092
+ }
1093
+
1094
+ if (isDisplayGrid(node_.style)) {
1095
+ layoutGridChildren(scratch.children(), childCount, padWidth, padHeight, true);
1096
+ updateScrollContentSize();
1097
+ positionAbsoluteChildren();
1098
+ applyRelativeOffsets();
1099
+ applyVirtualListContentHeight();
1100
+ return;
1101
+ }
1102
+
1103
+ FlexLayoutPass flex(engine_, node_, scratch.children(), childCount, isRow, mainAvail, padWidth, padHeight, scratch.lines(), inlineRow);
1104
+ flex.measureChildren();
1105
+ if (inlineRow) {
1106
+ // An inline formatting context flows line boxes, not flex lines — see
1107
+ // FlexLayoutPass::layoutInlineFlow.
1108
+ flex.layoutInlineFlow(true);
1109
+ } else {
1110
+ const int lineCount = flex.buildLines();
1111
+ flex.expandCrossSizes(lineCount, true);
1112
+ // Finalize this node's own size BEFORE positioning its children: positionLines
1113
+ // measures free main-axis space against the node's final padded box, so an
1114
+ // auto-sized box must shrink to content first (otherwise children are placed
1115
+ // against the larger available space and stranded after the shrink).
1116
+ flex.autosizeParent(lineCount);
1117
+ flex.positionLines(lineCount);
1118
+ }
1119
+ updateScrollContentSize();
1120
+ positionAbsoluteChildren();
1121
+ applyRelativeOffsets();
1122
+ applyVirtualListContentHeight();
1123
+ }
1124
+
1125
+ void repositionChildren()
1126
+ {
1127
+ if (node_.type == NodeType::Text || node_.type == NodeType::Image) return;
1128
+
1129
+ const int padWidth = paddedWidth();
1130
+ const int padHeight = paddedHeight();
1131
+ const bool inlineRow = resolveInlineFormattingRow();
1132
+ const bool isRow = inlineRow || resolveRowDirection();
1133
+ const int mainAvail = isRow ? padWidth : padHeight;
1134
+
1135
+ ScratchFrame scratch;
1136
+ if (!scratch.valid()) return;
1137
+
1138
+ const int childCount = engine_.collectChildren(id_, scratch.children(), kMaxChildren, true);
1139
+ if (childCount == 0) {
1140
+ positionAbsoluteChildren();
1141
+ return;
1142
+ }
1143
+
1144
+ if (isDisplayGrid(node_.style)) {
1145
+ layoutGridChildren(scratch.children(), childCount, padWidth, padHeight, false);
1146
+ positionAbsoluteChildren();
1147
+ applyRelativeOffsets();
1148
+ return;
1149
+ }
1150
+
1151
+ FlexLayoutPass flex(engine_, node_, scratch.children(), childCount, isRow, mainAvail, padWidth, padHeight, scratch.lines(), inlineRow);
1152
+ flex.measureChildren();
1153
+ if (inlineRow) {
1154
+ flex.layoutInlineFlow(false);
1155
+ } else {
1156
+ const int lineCount = flex.buildLines();
1157
+ flex.expandCrossSizes(lineCount, false);
1158
+ flex.positionLines(lineCount);
1159
+ }
1160
+ positionAbsoluteChildren();
1161
+ applyRelativeOffsets();
1162
+ }
1163
+
1164
+ private:
1165
+ // Direction for FlexLayoutPass. Explicit flex-direction / display:flex win
1166
+ // (usesRowLayout). Otherwise a plain block whose in-flow children are all
1167
+ // inline-level flows them on a row (CSS inline formatting); a block with any
1168
+ // block-level in-flow child stacks them (column), as a browser would.
1169
+ bool resolveRowDirection() const
1170
+ {
1171
+ if (usesRowLayout(node_.style)) return true;
1172
+ return resolveInlineFormattingRow();
1173
+ }
1174
+
1175
+ // True when the row direction is SYNTHESIZED from inline-level children —
1176
+ // gea's stand-in for an inline formatting context — rather than declared by
1177
+ // display:flex / flex-direction. Such a row behaves like a run of line boxes
1178
+ // (wraps, never flex-shrinks, aligns on the shared baseline), which is what
1179
+ // FlexLayoutPass's `inlineRow` flag switches on.
1180
+ bool resolveInlineFormattingRow() const
1181
+ {
1182
+ if (usesRowLayout(node_.style)) return false;
1183
+ if (node_.style.flex_direction_explicit || node_.style.display != kDisplayBlock) return false;
1184
+ bool anyInFlow = false;
1185
+ for (int c = node_.first_child; c >= 0; c = nodes_[c].next_sibling) {
1186
+ const Node &child = nodes_[c];
1187
+ if (child.style.display == kDisplayNone || child.style.position == 1) continue; // none / absolute
1188
+ if (!LayoutEngine::isInlineLevelNode(child)) return false;
1189
+ anyInFlow = true;
1190
+ }
1191
+ return anyInFlow;
1192
+ }
1193
+
1194
+ int explicitGridColumnCount(int childCount) const
1195
+ {
1196
+ if (rstyle(node_.style).grid_column_count > 0) return rstyle(node_.style).grid_column_count;
1197
+ return childCount > 0 ? 1 : 0;
1198
+ }
1199
+
1200
+ int explicitGridRowCount(int childCount, int columnCount) const
1201
+ {
1202
+ if (rstyle(node_.style).grid_row_count > 0) return rstyle(node_.style).grid_row_count;
1203
+ if (columnCount <= 0) return 0;
1204
+ int rows = (childCount + columnCount - 1) / columnCount;
1205
+ if (rows > kMaxGridLayoutTracks) rows = kMaxGridLayoutTracks;
1206
+ return rows;
1207
+ }
1208
+
1209
+ void measureGridChildren(int *children, int childCount, int padWidth, int padHeight)
1210
+ {
1211
+ for (int i = 0; i < childCount; ++i) {
1212
+ (void)padHeight;
1213
+ engine_.layoutNode(children[i], padWidth, 0);
1214
+ }
1215
+ }
1216
+
1217
+ void computeAutoTrackSizes(int *children,
1218
+ int childCount,
1219
+ int columnCount,
1220
+ int rowCount,
1221
+ int *autoColumnSizes,
1222
+ int *autoRowSizes)
1223
+ {
1224
+ for (int i = 0; i < kMaxGridLayoutTracks; ++i) {
1225
+ autoColumnSizes[i] = 0;
1226
+ autoRowSizes[i] = 0;
1227
+ }
1228
+ for (int i = 0; i < childCount; ++i) {
1229
+ const int column = columnCount > 0 ? i % columnCount : 0;
1230
+ const int row = columnCount > 0 ? i / columnCount : 0;
1231
+ if (column >= columnCount || row >= rowCount) continue;
1232
+ const Node &childNode = nodes_[children[i]];
1233
+ const int childWidth = childNode.layout.width + childNode.style.margin[1] + childNode.style.margin[3];
1234
+ const int childHeight = childNode.layout.height + childNode.style.margin[0] + childNode.style.margin[2];
1235
+ if (childWidth > autoColumnSizes[column]) autoColumnSizes[column] = childWidth;
1236
+ if (childHeight > autoRowSizes[row]) autoRowSizes[row] = childHeight;
1237
+ }
1238
+ }
1239
+
1240
+ void computeTrackSizes(int count,
1241
+ const int8_t *types,
1242
+ const int16_t *values,
1243
+ const int *autoSizes,
1244
+ int available,
1245
+ int *outSizes)
1246
+ {
1247
+ int fixedTotal = 0;
1248
+ int totalFr = 0;
1249
+ for (int i = 0; i < count; ++i) {
1250
+ outSizes[i] = 0;
1251
+ if (types[i] == 1) {
1252
+ outSizes[i] = values[i];
1253
+ fixedTotal += outSizes[i];
1254
+ } else if (types[i] == 2) {
1255
+ totalFr += values[i] > 0 ? values[i] : 1;
1256
+ } else {
1257
+ outSizes[i] = autoSizes ? autoSizes[i] : 0;
1258
+ fixedTotal += outSizes[i];
1259
+ }
1260
+ }
1261
+
1262
+ const int gapTotal = count > 1 ? (count - 1) * node_.style.gap : 0;
1263
+ int remaining = available - fixedTotal - gapTotal;
1264
+ if (remaining < 0) remaining = 0;
1265
+
1266
+ int assignedFr = 0;
1267
+ for (int i = 0; i < count; ++i) {
1268
+ if (types[i] != 2) continue;
1269
+ const int fr = values[i] > 0 ? values[i] : 1;
1270
+ int size = totalFr > 0 ? remaining * fr / totalFr : 0;
1271
+ outSizes[i] = size;
1272
+ assignedFr += size;
1273
+ }
1274
+ if (totalFr > 0 && assignedFr < remaining) {
1275
+ for (int i = count - 1; i >= 0; --i) {
1276
+ if (types[i] == 2) {
1277
+ outSizes[i] += remaining - assignedFr;
1278
+ break;
1279
+ }
1280
+ }
1281
+ }
1282
+ }
1283
+
1284
+ int gridTrackTotalSize(int count, const int *sizes) const
1285
+ {
1286
+ int total = 0;
1287
+ for (int i = 0; i < count; ++i) total += sizes[i] + (i > 0 ? node_.style.gap : 0);
1288
+ return total;
1289
+ }
1290
+
1291
+ int gridContentOffset(int available, int total, int alignment, int paddingBefore) const
1292
+ {
1293
+ int free = available - total;
1294
+ if (free < 0 && alignment != 1 && alignment != 2) free = 0;
1295
+ if (alignment == 1) return paddingBefore + free / 2;
1296
+ if (alignment == 2) return paddingBefore + free;
1297
+ return paddingBefore;
1298
+ }
1299
+
1300
+ void stretchGridChild(int child, Node &childNode, int cellWidth, int cellHeight, int alignX, int alignY)
1301
+ {
1302
+ bool resized = false;
1303
+ const int availableWidth = cellWidth - childNode.style.margin[1] - childNode.style.margin[3];
1304
+ const int availableHeight = cellHeight - childNode.style.margin[0] - childNode.style.margin[2];
1305
+ const int width = engine_.clampSize(availableWidth < 0 ? 0 : availableWidth, childNode.style.min_width, childNode.style.max_width);
1306
+ const int height = engine_.clampSize(availableHeight < 0 ? 0 : availableHeight, childNode.style.min_height, childNode.style.max_height);
1307
+ if (alignX == 0 && !hasExplicitWidth(childNode) && childNode.layout.width != width) {
1308
+ childNode.layout.width = width;
1309
+ resized = true;
1310
+ }
1311
+ if (alignY == 0 && !hasExplicitHeight(childNode) && childNode.layout.height != height) {
1312
+ childNode.layout.height = height;
1313
+ resized = true;
1314
+ }
1315
+ if (resized) engine_.repositionChildren(child);
1316
+ }
1317
+
1318
+ void layoutGridChildren(int *children, int childCount, int padWidth, int padHeight, bool allowAutosizeParent)
1319
+ {
1320
+ if (childCount <= 0) return;
1321
+ int columnCount = explicitGridColumnCount(childCount);
1322
+ if (columnCount <= 0) return;
1323
+ if (columnCount > kMaxGridLayoutTracks) columnCount = kMaxGridLayoutTracks;
1324
+ int rowCount = explicitGridRowCount(childCount, columnCount);
1325
+ if (rowCount <= 0) return;
1326
+ if (rowCount > kMaxGridLayoutTracks) rowCount = kMaxGridLayoutTracks;
1327
+
1328
+ measureGridChildren(children, childCount, padWidth, padHeight);
1329
+
1330
+ int8_t columnTypes[kMaxGridLayoutTracks] = {0};
1331
+ int8_t rowTypes[kMaxGridLayoutTracks] = {0};
1332
+ int16_t columnValues[kMaxGridLayoutTracks] = {0};
1333
+ int16_t rowValues[kMaxGridLayoutTracks] = {0};
1334
+ for (int i = 0; i < columnCount; ++i) {
1335
+ columnTypes[i] = i < rstyle(node_.style).grid_column_count ? rstyle(node_.style).grid_column_type[i] : 0;
1336
+ columnValues[i] = i < rstyle(node_.style).grid_column_count ? rstyle(node_.style).grid_column_value[i] : 0;
1337
+ }
1338
+ for (int i = 0; i < rowCount; ++i) {
1339
+ rowTypes[i] = i < rstyle(node_.style).grid_row_count ? rstyle(node_.style).grid_row_type[i] : 0;
1340
+ rowValues[i] = i < rstyle(node_.style).grid_row_count ? rstyle(node_.style).grid_row_value[i] : 0;
1341
+ }
1342
+
1343
+ int autoColumns[kMaxGridLayoutTracks] = {0};
1344
+ int autoRows[kMaxGridLayoutTracks] = {0};
1345
+ computeAutoTrackSizes(children, childCount, columnCount, rowCount, autoColumns, autoRows);
1346
+
1347
+ int columnSizes[kMaxGridLayoutTracks] = {0};
1348
+ int rowSizes[kMaxGridLayoutTracks] = {0};
1349
+ computeTrackSizes(columnCount, columnTypes, columnValues, autoColumns, padWidth, columnSizes);
1350
+ computeTrackSizes(rowCount, rowTypes, rowValues, autoRows, padHeight, rowSizes);
1351
+ if (rstyle(node_.style).grid_column_count == 0 && columnCount == 1) columnSizes[0] = padWidth;
1352
+
1353
+ if (allowAutosizeParent && !hasExplicitWidth(node_)) {
1354
+ int width = node_.style.padding[1] + node_.style.padding[3];
1355
+ for (int i = 0; i < columnCount; ++i) width += columnSizes[i] + (i > 0 ? node_.style.gap : 0);
1356
+ node_.layout.width = engine_.clampSize(width, node_.style.min_width, node_.style.max_width);
1357
+ }
1358
+ if (allowAutosizeParent && !hasExplicitHeight(node_)) {
1359
+ int height = node_.style.padding[0] + node_.style.padding[2];
1360
+ for (int i = 0; i < rowCount; ++i) height += rowSizes[i] + (i > 0 ? node_.style.gap : 0);
1361
+ node_.layout.height = engine_.clampSize(height, node_.style.min_height, node_.style.max_height);
1362
+ }
1363
+
1364
+ int rowY[kMaxGridLayoutTracks] = {0};
1365
+ int columnX[kMaxGridLayoutTracks] = {0};
1366
+ const int columnTotal = gridTrackTotalSize(columnCount, columnSizes);
1367
+ const int rowTotal = gridTrackTotalSize(rowCount, rowSizes);
1368
+ columnX[0] = gridContentOffset(padWidth, columnTotal, node_.style.justify_content, node_.style.padding[3]);
1369
+ for (int i = 1; i < columnCount; ++i) columnX[i] = columnX[i - 1] + columnSizes[i - 1] + node_.style.gap;
1370
+ // A single implicit row (no grid-template-rows) is positioned by align-items,
1371
+ // not align-content, so place-items:center can vertically center a lone child
1372
+ // when the container is taller than its content (e.g. a position:absolute
1373
+ // inset:0 face). Without this the child pins to the top (align-content
1374
+ // defaults to start). Mirrors the single implicit column filling width above.
1375
+ const int rowBlockAlign = (rstyle(node_.style).grid_row_count == 0 && rowCount == 1)
1376
+ ? node_.style.align_items
1377
+ : node_.style.align_content;
1378
+ rowY[0] = gridContentOffset(padHeight, rowTotal, rowBlockAlign, node_.style.padding[0]);
1379
+ for (int i = 1; i < rowCount; ++i) rowY[i] = rowY[i - 1] + rowSizes[i - 1] + node_.style.gap;
1380
+
1381
+ for (int i = 0; i < childCount; ++i) {
1382
+ const int column = i % columnCount;
1383
+ const int row = i / columnCount;
1384
+ if (row >= rowCount) break;
1385
+ const int child = children[i];
1386
+ Node &childNode = nodes_[child];
1387
+ const int cellWidth = columnSizes[column];
1388
+ const int cellHeight = rowSizes[row];
1389
+ engine_.layoutNode(child, cellWidth, cellHeight);
1390
+
1391
+ const int alignX = childNode.style.align_self >= 0 ? childNode.style.align_self : node_.style.justify_items;
1392
+ const int alignY = childNode.style.align_self >= 0 ? childNode.style.align_self : node_.style.align_items;
1393
+ stretchGridChild(child, childNode, cellWidth, cellHeight, alignX, alignY);
1394
+
1395
+ int x = columnX[column] + childNode.style.margin[3];
1396
+ int y = rowY[row] + childNode.style.margin[0];
1397
+ const int freeX = cellWidth - childNode.layout.width - childNode.style.margin[1] - childNode.style.margin[3];
1398
+ const int freeY = cellHeight - childNode.layout.height - childNode.style.margin[0] - childNode.style.margin[2];
1399
+ if (alignX == 1 && freeX > 0) x += freeX / 2;
1400
+ else if (alignX == 2 && freeX > 0) x += freeX;
1401
+ if (alignY == 1 && freeY > 0) y += freeY / 2;
1402
+ else if (alignY == 2 && freeY > 0) y += freeY;
1403
+ childNode.layout.x = x;
1404
+ childNode.layout.y = y;
1405
+ }
1406
+ }
1407
+
1408
+ void prepareOwnSize()
1409
+ {
1410
+ int contentWidth = resolvedStyleWidth(node_, availWidth_);
1411
+ int contentHeight = resolvedStyleHeight(node_, availHeight_);
1412
+ if (!hasExplicitWidth(node_)) {
1413
+ contentWidth -= node_.style.margin[1] + node_.style.margin[3];
1414
+ }
1415
+ if (!hasExplicitHeight(node_)) {
1416
+ contentHeight -= node_.style.margin[0] + node_.style.margin[2];
1417
+ }
1418
+ contentWidth = engine_.clampSize(contentWidth, node_.style.min_width, node_.style.max_width);
1419
+ contentHeight = engine_.clampSize(contentHeight, node_.style.min_height, node_.style.max_height);
1420
+
1421
+ node_.layout.width = contentWidth;
1422
+ node_.layout.height = contentHeight;
1423
+ }
1424
+
1425
+ int paddedWidth() const
1426
+ {
1427
+ int width = node_.layout.width - node_.style.padding[1] - node_.style.padding[3];
1428
+ return width < 0 ? 0 : width;
1429
+ }
1430
+
1431
+ int paddedHeight() const
1432
+ {
1433
+ int height = node_.layout.height - node_.style.padding[0] - node_.style.padding[2];
1434
+ return height < 0 ? 0 : height;
1435
+ }
1436
+
1437
+ void autosizeEmptyNode()
1438
+ {
1439
+ if (!hasExplicitWidth(node_)) node_.layout.width = node_.style.padding[1] + node_.style.padding[3];
1440
+ if (!hasExplicitHeight(node_)) node_.layout.height = node_.style.padding[0] + node_.style.padding[2];
1441
+ node_.layout.width = engine_.clampSize(node_.layout.width, node_.style.min_width, node_.style.max_width);
1442
+ node_.layout.height = engine_.clampSize(node_.layout.height, node_.style.min_height, node_.style.max_height);
1443
+ // A <virtual-list>'s scroll geometry is owned by
1444
+ // applyVirtualListContentHeight() (invoked right after this in the
1445
+ // empty-node branch). Its recycled slot pool is entirely
1446
+ // position:absolute, so collectChildren() returns 0 and a scrollable
1447
+ // virtual-list lands here — resetting scroll_y/scroll_content_height
1448
+ // would wipe the scroll position on every relayout the moment the store
1449
+ // rewrites its slots.
1450
+ if (node_.type != NodeType::VirtualList) {
1451
+ node_.layout.scroll_content_width = node_.layout.width;
1452
+ node_.layout.scroll_content_height = node_.layout.height;
1453
+ node_.layout.scroll_x = 0;
1454
+ node_.layout.scroll_y = 0;
1455
+ }
1456
+ }
1457
+
1458
+ void updateScrollContentSize()
1459
+ {
1460
+ // A <virtual-list>'s scroll geometry is owned by
1461
+ // applyVirtualListContentHeight() (scroll_content_height = itemCount *
1462
+ // rowHeight). Its real children are the recycled, position:absolute slot
1463
+ // pool, which this children-bottom walk skips — so running here would
1464
+ // collapse scroll_content_height to the node height, force maxScroll to
1465
+ // 0, and clamp scroll_y back to 0 on every relayout (wiping the scroll
1466
+ // position the moment the store rewrites its slots).
1467
+ if (node_.type == NodeType::VirtualList) return;
1468
+ int contentWidth = node_.layout.width;
1469
+ int contentHeight = node_.layout.height;
1470
+ for (int child = node_.first_child; child >= 0; child = nodes_[child].next_sibling) {
1471
+ Node &childNode = nodes_[child];
1472
+ if (isDisplayNone(childNode.style) || childNode.style.position == 1) continue;
1473
+ const int right = childNode.layout.x + childNode.layout.width + childNode.style.margin[1] + node_.style.padding[1];
1474
+ if (right > contentWidth) contentWidth = right;
1475
+ const int bottom = childNode.layout.y + childNode.layout.height + childNode.style.margin[2] + node_.style.padding[2];
1476
+ if (bottom > contentHeight) contentHeight = bottom;
1477
+ }
1478
+ node_.layout.scroll_content_width = contentWidth;
1479
+ node_.layout.scroll_content_height = contentHeight;
1480
+
1481
+ int maxScrollX = node_.layout.scroll_content_width - node_.layout.width;
1482
+ if (maxScrollX < 0) maxScrollX = 0;
1483
+ if (!scrollsOverflowX(node_.style)) {
1484
+ node_.layout.scroll_x = 0;
1485
+ } else {
1486
+ if (node_.layout.scroll_x < 0) node_.layout.scroll_x = 0;
1487
+ if (node_.layout.scroll_x > maxScrollX) node_.layout.scroll_x = maxScrollX;
1488
+ }
1489
+
1490
+ int maxScroll = node_.layout.scroll_content_height - node_.layout.height;
1491
+ if (maxScroll < 0) maxScroll = 0;
1492
+ if (!scrollsOverflowY(node_.style)) {
1493
+ node_.layout.scroll_y = 0;
1494
+ } else {
1495
+ if (node_.layout.scroll_y < 0) node_.layout.scroll_y = 0;
1496
+ if (node_.layout.scroll_y > maxScroll) node_.layout.scroll_y = maxScroll;
1497
+ }
1498
+ }
1499
+
1500
+ // A <virtual-list> only materializes a small pool of real child slot nodes
1501
+ // but scrolls over a virtual content height of itemCount * rowHeight. The
1502
+ // row height comes from the first slot's resolved CSS height, so the app
1503
+ // controls it purely through the template's stylesheet.
1504
+ void applyVirtualListContentHeight()
1505
+ {
1506
+ if (node_.type != NodeType::VirtualList) return;
1507
+ int rowHeight = 0;
1508
+ for (int child = node_.first_child; child >= 0; child = nodes_[child].next_sibling) {
1509
+ if (isDisplayNone(nodes_[child].style)) continue;
1510
+ rowHeight = nodes_[child].layout.height;
1511
+ break;
1512
+ }
1513
+ int content = VirtualListRenderer::virtualContentHeight(id_, rowHeight);
1514
+ if (content < node_.layout.height) content = node_.layout.height;
1515
+ node_.layout.scroll_content_width = node_.layout.width;
1516
+ node_.layout.scroll_content_height = content;
1517
+ node_.layout.scroll_x = 0;
1518
+ int maxScroll = node_.layout.scroll_content_height - node_.layout.height;
1519
+ if (maxScroll < 0) maxScroll = 0;
1520
+ if (node_.layout.scroll_y < 0) node_.layout.scroll_y = 0;
1521
+ if (node_.layout.scroll_y > maxScroll) node_.layout.scroll_y = maxScroll;
1522
+ }
1523
+
1524
+ void positionAbsoluteChildren()
1525
+ {
1526
+ for (int child = node_.first_child; child >= 0; child = nodes_[child].next_sibling) {
1527
+ Node &childNode = nodes_[child];
1528
+ if (isDisplayNone(childNode.style) || childNode.style.position != 1) continue;
1529
+
1530
+ const int childAvailWidth = node_.layout.width;
1531
+ const int childAvailHeight = node_.layout.height;
1532
+ engine_.layoutNode(child, childAvailWidth, childAvailHeight);
1533
+ stretchAbsoluteChild(child, childNode, childAvailWidth, childAvailHeight);
1534
+ positionAbsoluteChild(childNode);
1535
+ }
1536
+ }
1537
+
1538
+ void stretchAbsoluteChild(int child, Node &childNode, int childAvailWidth, int childAvailHeight)
1539
+ {
1540
+ bool resized = false;
1541
+ if (!hasExplicitWidth(childNode) &&
1542
+ hasPositionOffset(childNode, 3) &&
1543
+ hasPositionOffset(childNode, 1)) {
1544
+ int width = childAvailWidth - resolvedPositionOffset(childNode, 3) - resolvedPositionOffset(childNode, 1) -
1545
+ childNode.style.margin[1] - childNode.style.margin[3];
1546
+ if (width < 0) width = 0;
1547
+ width = engine_.clampSize(width, childNode.style.min_width, childNode.style.max_width);
1548
+ if (childNode.layout.width != width) {
1549
+ childNode.layout.width = width;
1550
+ resized = true;
1551
+ }
1552
+ }
1553
+
1554
+ if (!hasExplicitHeight(childNode) &&
1555
+ hasPositionOffset(childNode, 0) &&
1556
+ hasPositionOffset(childNode, 2)) {
1557
+ int height = childAvailHeight - resolvedPositionOffset(childNode, 0) - resolvedPositionOffset(childNode, 2) -
1558
+ childNode.style.margin[0] - childNode.style.margin[2];
1559
+ if (height < 0) height = 0;
1560
+ height = engine_.clampSize(height, childNode.style.min_height, childNode.style.max_height);
1561
+ if (childNode.layout.height != height) {
1562
+ childNode.layout.height = height;
1563
+ resized = true;
1564
+ }
1565
+ }
1566
+
1567
+ if (resized) engine_.repositionChildren(child);
1568
+ }
1569
+
1570
+ void positionAbsoluteChild(Node &childNode)
1571
+ {
1572
+ if (hasPositionOffset(childNode, 3))
1573
+ childNode.layout.x = resolvedPositionOffset(childNode, 3);
1574
+ else if (hasPositionOffset(childNode, 1))
1575
+ childNode.layout.x = node_.layout.width - childNode.layout.width - resolvedPositionOffset(childNode, 1);
1576
+ else
1577
+ childNode.layout.x = alignedAbsoluteChildPosition(childNode, true);
1578
+
1579
+ if (hasPositionOffset(childNode, 0))
1580
+ childNode.layout.y = resolvedPositionOffset(childNode, 0);
1581
+ else if (hasPositionOffset(childNode, 2))
1582
+ childNode.layout.y = node_.layout.height - childNode.layout.height - resolvedPositionOffset(childNode, 2);
1583
+ else
1584
+ childNode.layout.y = alignedAbsoluteChildPosition(childNode, false);
1585
+ }
1586
+
1587
+ int alignedAbsoluteChildPosition(const Node &childNode, bool horizontal) const
1588
+ {
1589
+ const bool row = usesRowLayout(node_.style);
1590
+ const int crossAlign = childNode.style.align_self >= 0 ? childNode.style.align_self : node_.style.align_items;
1591
+ const int align = horizontal
1592
+ ? (row ? node_.style.justify_content : crossAlign)
1593
+ : (row ? crossAlign : node_.style.justify_content);
1594
+ const int parentSize = horizontal ? node_.layout.width : node_.layout.height;
1595
+ const int childSize = horizontal ? childNode.layout.width : childNode.layout.height;
1596
+ const int beforeMargin = horizontal ? childNode.style.margin[3] : childNode.style.margin[0];
1597
+ const int afterMargin = horizontal ? childNode.style.margin[1] : childNode.style.margin[2];
1598
+ int available = parentSize;
1599
+ if (available < 0) available = 0;
1600
+ const int occupied = childSize + beforeMargin + afterMargin;
1601
+ int free = available - occupied;
1602
+ if (free < 0) free = 0;
1603
+
1604
+ int position = beforeMargin;
1605
+ if (align == 1) position += free / 2;
1606
+ else if (align == 2) position += free;
1607
+ return position;
1608
+ }
1609
+
1610
+ void applyRelativeOffsets()
1611
+ {
1612
+ for (int child = node_.first_child; child >= 0; child = nodes_[child].next_sibling) {
1613
+ Node &childNode = nodes_[child];
1614
+ if (childNode.style.position != 2) continue;
1615
+ if (hasPositionOffset(childNode, 0))
1616
+ childNode.layout.y += resolvedRelativePositionOffset(childNode, 0);
1617
+ else if (hasPositionOffset(childNode, 2))
1618
+ childNode.layout.y -= resolvedRelativePositionOffset(childNode, 2);
1619
+ if (hasPositionOffset(childNode, 3))
1620
+ childNode.layout.x += resolvedRelativePositionOffset(childNode, 3);
1621
+ else if (hasPositionOffset(childNode, 1))
1622
+ childNode.layout.x -= resolvedRelativePositionOffset(childNode, 1);
1623
+ }
1624
+ }
1625
+
1626
+ bool hasPositionOffset(const Node &node, int side) const
1627
+ {
1628
+ return node.style.pos_offsets[side] != kUnset || node.style.pos_offset_percent[side] != kUnset;
1629
+ }
1630
+
1631
+ int resolvedPositionOffset(const Node &node, int side) const
1632
+ {
1633
+ return resolvedPositionOffsetWithBasis(node, side, (side == 0 || side == 2) ? node_.layout.height : node_.layout.width);
1634
+ }
1635
+
1636
+ int resolvedRelativePositionOffset(const Node &node, int side) const
1637
+ {
1638
+ int basis = (side == 0 || side == 2) ? node_.layout.height : node_.layout.width;
1639
+ if (isDisplayGrid(node_.style)) {
1640
+ basis = (side == 0 || side == 2) ? node.layout.height : node.layout.width;
1641
+ }
1642
+ return resolvedPositionOffsetWithBasis(node, side, basis);
1643
+ }
1644
+
1645
+ int resolvedPositionOffsetWithBasis(const Node &node, int side, int percentBasis) const
1646
+ {
1647
+ int offset = node.style.pos_offsets[side] != kUnset ? node.style.pos_offsets[side] : 0;
1648
+ const int percent = node.style.pos_offset_percent[side];
1649
+ if (percent != kUnset) {
1650
+ const int numerator = percentBasis * percent;
1651
+ offset += (numerator + (numerator >= 0 ? 500 : -500)) / 1000;
1652
+ }
1653
+ return offset;
1654
+ }
1655
+
1656
+ LayoutEngine &engine_;
1657
+ int id_ = 0;
1658
+ int availWidth_ = 0;
1659
+ int availHeight_ = 0;
1660
+ Node *nodes_ = nullptr;
1661
+ Node &node_;
1662
+ };
1663
+
1664
+ bool establishesAbsoluteContainingBlock(const Node &node)
1665
+ {
1666
+ return node.style.position == 1 || node.style.position == 2;
1667
+ }
1668
+
1669
+ int containingBlockForAbsoluteNode(int node, int root, Node *nodes)
1670
+ {
1671
+ for (int cursor = nodes[node].parent; cursor >= 0; cursor = nodes[cursor].parent) {
1672
+ if (establishesAbsoluteContainingBlock(nodes[cursor])) return cursor;
1673
+ }
1674
+ return root;
1675
+ }
1676
+
1677
+ bool hasPositionOffsetValue(const Node &node, int side)
1678
+ {
1679
+ return node.style.pos_offsets[side] != kUnset || node.style.pos_offset_percent[side] != kUnset;
1680
+ }
1681
+
1682
+ int resolvedPositionOffsetForBasis(const Node &node, int side, int percentBasis)
1683
+ {
1684
+ int offset = node.style.pos_offsets[side] != kUnset ? node.style.pos_offsets[side] : 0;
1685
+ const int percent = node.style.pos_offset_percent[side];
1686
+ if (percent != kUnset) {
1687
+ const int numerator = percentBasis * percent;
1688
+ offset += (numerator + (numerator >= 0 ? 500 : -500)) / 1000;
1689
+ }
1690
+ return offset;
1691
+ }
1692
+
1693
+ void offsetFromAncestorToNode(int ancestor, int node, Node *nodes, int *outX, int *outY)
1694
+ {
1695
+ int x = 0;
1696
+ int y = 0;
1697
+ for (int cursor = node; cursor >= 0 && cursor != ancestor; cursor = nodes[cursor].parent) {
1698
+ const Node &current = nodes[cursor];
1699
+ x += current.layout.x;
1700
+ y += current.layout.y;
1701
+ if (scrollsOverflowX(current.style)) x -= current.layout.scroll_x;
1702
+ if (scrollsOverflowY(current.style)) y -= current.layout.scroll_y;
1703
+ }
1704
+ *outX = x;
1705
+ *outY = y;
1706
+ }
1707
+
1708
+ void stretchAbsoluteNodeToContainingBlock(int node, int containingWidth, int containingHeight, Node *nodes)
1709
+ {
1710
+ Node &absolute = nodes[node];
1711
+ bool resized = false;
1712
+ if (!hasExplicitWidth(absolute) &&
1713
+ hasPositionOffsetValue(absolute, 3) &&
1714
+ hasPositionOffsetValue(absolute, 1)) {
1715
+ int width = containingWidth -
1716
+ resolvedPositionOffsetForBasis(absolute, 3, containingWidth) -
1717
+ resolvedPositionOffsetForBasis(absolute, 1, containingWidth) -
1718
+ absolute.style.margin[1] - absolute.style.margin[3];
1719
+ if (width < 0) width = 0;
1720
+ width = LayoutEngine::instance().clampSize(width, absolute.style.min_width, absolute.style.max_width);
1721
+ if (absolute.layout.width != width) {
1722
+ absolute.layout.width = width;
1723
+ resized = true;
1724
+ }
1725
+ }
1726
+
1727
+ if (!hasExplicitHeight(absolute) &&
1728
+ hasPositionOffsetValue(absolute, 0) &&
1729
+ hasPositionOffsetValue(absolute, 2)) {
1730
+ int height = containingHeight -
1731
+ resolvedPositionOffsetForBasis(absolute, 0, containingHeight) -
1732
+ resolvedPositionOffsetForBasis(absolute, 2, containingHeight) -
1733
+ absolute.style.margin[0] - absolute.style.margin[2];
1734
+ if (height < 0) height = 0;
1735
+ height = LayoutEngine::instance().clampSize(height, absolute.style.min_height, absolute.style.max_height);
1736
+ if (absolute.layout.height != height) {
1737
+ absolute.layout.height = height;
1738
+ resized = true;
1739
+ }
1740
+ }
1741
+
1742
+ if (resized) LayoutEngine::instance().repositionChildren(node);
1743
+ }
1744
+
1745
+ void positionAbsoluteNodeInContainingBlock(int node, int containing, Node *nodes)
1746
+ {
1747
+ Node &absolute = nodes[node];
1748
+ const Node &containingNode = nodes[containing];
1749
+ const int parent = absolute.parent;
1750
+ if (parent < 0) return;
1751
+
1752
+ stretchAbsoluteNodeToContainingBlock(node, containingNode.layout.width, containingNode.layout.height, nodes);
1753
+
1754
+ int parentOffsetX = 0;
1755
+ int parentOffsetY = 0;
1756
+ offsetFromAncestorToNode(containing, parent, nodes, &parentOffsetX, &parentOffsetY);
1757
+
1758
+ int containingX = absolute.layout.x + parentOffsetX;
1759
+ if (hasPositionOffsetValue(absolute, 3))
1760
+ containingX = resolvedPositionOffsetForBasis(absolute, 3, containingNode.layout.width);
1761
+ else if (hasPositionOffsetValue(absolute, 1))
1762
+ containingX = containingNode.layout.width - absolute.layout.width -
1763
+ resolvedPositionOffsetForBasis(absolute, 1, containingNode.layout.width);
1764
+
1765
+ int containingY = absolute.layout.y + parentOffsetY;
1766
+ if (hasPositionOffsetValue(absolute, 0))
1767
+ containingY = resolvedPositionOffsetForBasis(absolute, 0, containingNode.layout.height);
1768
+ else if (hasPositionOffsetValue(absolute, 2))
1769
+ containingY = containingNode.layout.height - absolute.layout.height -
1770
+ resolvedPositionOffsetForBasis(absolute, 2, containingNode.layout.height);
1771
+
1772
+ absolute.layout.x = containingX - parentOffsetX;
1773
+ absolute.layout.y = containingY - parentOffsetY;
1774
+ }
1775
+
1776
+ void resolveAbsoluteContainingBlocks(int root)
1777
+ {
1778
+ Node *nodes = Tree::instance().nodes();
1779
+ const int nodeCount = Tree::instance().nodeCount();
1780
+ for (int node = 0; node < nodeCount; ++node) {
1781
+ if (isDisplayNone(nodes[node].style) || nodes[node].style.position != 1 || nodes[node].parent < 0) continue;
1782
+ const int containing = containingBlockForAbsoluteNode(node, root, nodes);
1783
+ if (containing < 0) continue;
1784
+ positionAbsoluteNodeInContainingBlock(node, containing, nodes);
1785
+ }
1786
+ }
1787
+
1788
+ } // namespace
1789
+
1790
+ LayoutEngine &LayoutEngine::instance()
1791
+ {
1792
+ static LayoutEngine engine;
1793
+ return engine;
1794
+ }
1795
+
1796
+ bool LayoutEngine::isInlineLevelNode(const Node &n)
1797
+ {
1798
+ if (n.style.display == kDisplayFlex || n.style.display == kDisplayGrid || n.style.display == kDisplayNone)
1799
+ return false;
1800
+ // An explicit `display:block` makes even an inline-level tag (a <span>) — or a
1801
+ // Text/Image node — a BLOCK-LEVEL box, so it stacks vertically among siblings
1802
+ // instead of flowing into an inline row. Browsers do this; gea must too (e.g.
1803
+ // the weather city list's .city-name/.city-detail spans set display:block to
1804
+ // stack the name over the region). Without an explicit display, fall back to
1805
+ // the tag's intrinsic inline-ness.
1806
+ if (n.style.display == kDisplayBlock && n.style.display_explicit) return false;
1807
+ // In Gea's native layout model, vertical margins on inline-level wrappers are
1808
+ // used as an authoring signal that the wrapper occupies its own line. Keep
1809
+ // default spans inline, but do not merge title/score spans with margin-bottom
1810
+ // into one row.
1811
+ if (n.style.margin[0] != 0 || n.style.margin[2] != 0) return false;
1812
+ if (n.type == NodeType::Text || n.type == NodeType::Image) return true;
1813
+ return isInlineLevelTag(tagFromId(n.tag_id));
1814
+ }
1815
+
1816
+ int LayoutEngine::clampSize(int size, int minSize, int maxSize) const
1817
+ {
1818
+ if (minSize > 0 && size < minSize) size = minSize;
1819
+ if (maxSize != kUnset && size > maxSize) size = maxSize;
1820
+ return size;
1821
+ }
1822
+
1823
+ int LayoutEngine::collectChildren(int parent, int *out, int max, bool skipAbs) const
1824
+ {
1825
+ int n = 0;
1826
+ Node *nodes = Tree::instance().nodes();
1827
+ for (int child = nodes[parent].first_child; child >= 0; child = nodes[child].next_sibling) {
1828
+ if (isDisplayNone(nodes[child].style)) continue;
1829
+ if (skipAbs && nodes[child].style.position == 1) continue;
1830
+ if (n < max) out[n++] = child;
1831
+ }
1832
+ return n;
1833
+ }
1834
+
1835
+ namespace {
1836
+ // Intra-pass memo serial (see LayoutBox::memo_pass). 0 is never a valid pass
1837
+ // so zero-initialized nodes can't produce a stale hit.
1838
+ std::uint32_t gLayoutPassSerial = 1;
1839
+ } // namespace
1840
+
1841
+ void LayoutEngine::beginLayoutPass()
1842
+ {
1843
+ if (++gLayoutPassSerial == 0) gLayoutPassSerial = 1;
1844
+ }
1845
+
1846
+ void LayoutEngine::layoutNode(int id, int avail_w, int avail_h)
1847
+ {
1848
+ Node &node = Tree::instance().nodes()[id];
1849
+ const bool memoizable = avail_w >= INT16_MIN && avail_w <= INT16_MAX &&
1850
+ avail_h >= INT16_MIN && avail_h <= INT16_MAX;
1851
+ if (memoizable) {
1852
+ if (node.layout.memo_pass == gLayoutPassSerial &&
1853
+ node.layout.memo_avail_w == avail_w &&
1854
+ node.layout.memo_avail_h == avail_h) {
1855
+ refreshPerfStatsMutable().treeLayoutMemoHits++;
1856
+ return;
1857
+ }
1858
+ if (node.layout.memo2_pass == gLayoutPassSerial &&
1859
+ node.layout.memo2_avail_w == avail_w &&
1860
+ node.layout.memo2_avail_h == avail_h &&
1861
+ node.layout.memo2_result_w == node.layout.width &&
1862
+ node.layout.memo2_result_h == node.layout.height) {
1863
+ // Promote the hit to the MRU slot.
1864
+ std::swap(node.layout.memo_avail_w, node.layout.memo2_avail_w);
1865
+ std::swap(node.layout.memo_avail_h, node.layout.memo2_avail_h);
1866
+ std::swap(node.layout.memo_result_w, node.layout.memo2_result_w);
1867
+ std::swap(node.layout.memo_result_h, node.layout.memo2_result_h);
1868
+ std::swap(node.layout.memo_pass, node.layout.memo2_pass);
1869
+ refreshPerfStatsMutable().treeLayoutMemoHits++;
1870
+ return;
1871
+ }
1872
+ }
1873
+ refreshPerfStatsMutable().treeLayoutNodeCalls++;
1874
+ LayoutNodePass(*this, id, avail_w, avail_h).run();
1875
+ node.layout.memo2_avail_w = node.layout.memo_avail_w;
1876
+ node.layout.memo2_avail_h = node.layout.memo_avail_h;
1877
+ node.layout.memo2_result_w = node.layout.memo_result_w;
1878
+ node.layout.memo2_result_h = node.layout.memo_result_h;
1879
+ node.layout.memo2_pass = node.layout.memo_pass;
1880
+ if (memoizable) {
1881
+ node.layout.memo_avail_w = static_cast<std::int16_t>(avail_w);
1882
+ node.layout.memo_avail_h = static_cast<std::int16_t>(avail_h);
1883
+ node.layout.memo_result_w = node.layout.width;
1884
+ node.layout.memo_result_h = node.layout.height;
1885
+ node.layout.memo_pass = gLayoutPassSerial;
1886
+ } else {
1887
+ node.layout.memo_pass = 0;
1888
+ }
1889
+ }
1890
+
1891
+ void LayoutEngine::repositionChildren(int id)
1892
+ {
1893
+ refreshPerfStatsMutable().treeLayoutRepositionCalls++;
1894
+ Node *node = &Tree::instance().nodes()[id];
1895
+ LayoutNodePass(*this, id, node->layout.width, node->layout.height).repositionChildren();
1896
+ }
1897
+
1898
+ bool LayoutEngine::layoutNodeScoped(int scope, int treeRoot)
1899
+ {
1900
+ Tree &tree = Tree::instance();
1901
+ Node *nodes = tree.nodes();
1902
+ const int nodeCount = tree.nodeCount();
1903
+ if (scope < 0 || scope >= nodeCount) return false;
1904
+ Node &a = nodes[scope];
1905
+ if (a.layout.memo_pass == 0) {
1906
+ refreshPerfStatsMutable().treeScopedRejectReason = 2;
1907
+ refreshPerfStatsMutable().treeScopedRejectNode = scope;
1908
+ return false;
1909
+ }
1910
+
1911
+ auto inScope = [&](int node) {
1912
+ for (int c = node; c >= 0 && c < nodeCount; c = nodes[c].parent) {
1913
+ if (c == scope) return true;
1914
+ }
1915
+ return false;
1916
+ };
1917
+
1918
+ // Absolute descendants positioned against a containing block OUTSIDE the
1919
+ // scope mix coordinate spaces (the global containing-block pass runs in
1920
+ // pre-resolve relative space) — those trees must take the full path.
1921
+ for (int i = 0; i < nodeCount; ++i) {
1922
+ const Node &n = nodes[i];
1923
+ if (n.parent < 0 || n.style.position != 1 || isDisplayNone(n.style)) continue;
1924
+ if (!inScope(i)) continue;
1925
+ const int containing = containingBlockForAbsoluteNode(i, treeRoot, nodes);
1926
+ if (containing >= 0 && !inScope(containing)) {
1927
+ refreshPerfStatsMutable().treeScopedRejectReason = 3;
1928
+ refreshPerfStatsMutable().treeScopedRejectNode = i;
1929
+ return false;
1930
+ }
1931
+ }
1932
+
1933
+ const int prevX = a.layout.x;
1934
+ const int prevY = a.layout.y;
1935
+ const int prevW = a.layout.width;
1936
+ const int prevH = a.layout.height;
1937
+ beginLayoutPass();
1938
+ layoutNode(scope, a.layout.memo_avail_w, a.layout.memo_avail_h);
1939
+ const bool widthChanged = a.layout.width != prevW;
1940
+ const bool heightChanged = a.layout.height != prevH;
1941
+ if (widthChanged || heightChanged) {
1942
+ // layoutNode() derives an auto-sized scope from its content. Restore an
1943
+ // axis only when the parent genuinely owns that axis (stretch, grid,
1944
+ // flex-grow/basis) or the scope has an explicit size. Otherwise the new
1945
+ // intrinsic size must propagate through the parent: reject this scope so
1946
+ // refresh() retries at a stable ancestor. Treating every changed axis as
1947
+ // parent-owned kept a city chip at its placeholder width when "--" became
1948
+ // "13°", forcing flex-shrink to turn the shorter "Berlin" into "Ber…".
1949
+ bool parentOwnsWidth = hasExplicitWidth(a);
1950
+ bool parentOwnsHeight = hasExplicitHeight(a);
1951
+ if (a.parent >= 0 && a.parent < nodeCount) {
1952
+ const Node &parent = nodes[a.parent];
1953
+ if (isDisplayGrid(parent.style)) {
1954
+ const int alignX = a.style.align_self >= 0 ? a.style.align_self : parent.style.justify_items;
1955
+ const int alignY = a.style.align_self >= 0 ? a.style.align_self : parent.style.align_items;
1956
+ parentOwnsWidth = parentOwnsWidth || alignX == 0;
1957
+ parentOwnsHeight = parentOwnsHeight || alignY == 0;
1958
+ } else {
1959
+ const bool row = usesRowLayout(parent.style);
1960
+ const bool parentOwnsMain = a.style.flex > 0 || a.style.flex_basis != kUnset;
1961
+ const int crossAlign = a.style.align_self >= 0 ? a.style.align_self : parent.style.align_items;
1962
+ const bool parentOwnsCross = crossAlign == 0;
1963
+ parentOwnsWidth = parentOwnsWidth || (row ? parentOwnsMain : parentOwnsCross);
1964
+ parentOwnsHeight = parentOwnsHeight || (row ? parentOwnsCross : parentOwnsMain);
1965
+ }
1966
+ }
1967
+ if ((widthChanged && !parentOwnsWidth) || (heightChanged && !parentOwnsHeight)) {
1968
+ refreshPerfStatsMutable().treeScopedRejectReason = 4;
1969
+ refreshPerfStatsMutable().treeScopedRejectNode = scope;
1970
+ return false;
1971
+ }
1972
+
1973
+ // A parent-owned box cannot be reproduced by laying only the child's
1974
+ // subtree. Put those dimensions back and position its descendants inside
1975
+ // the same box exactly as the omitted parent pass would.
1976
+ a.layout.width = static_cast<std::int16_t>(prevW);
1977
+ a.layout.height = static_cast<std::int16_t>(prevH);
1978
+ repositionChildren(scope);
1979
+ }
1980
+ a.layout.x = prevX;
1981
+ a.layout.y = prevY;
1982
+
1983
+ // Scoped equivalent of the root containing-block pass (both the node and
1984
+ // its containing block are inside the scope, in the same relative space).
1985
+ for (int i = 0; i < nodeCount; ++i) {
1986
+ if (isDisplayNone(nodes[i].style) || nodes[i].style.position != 1 || nodes[i].parent < 0) continue;
1987
+ if (!inScope(i) || i == scope) continue;
1988
+ const int containing = containingBlockForAbsoluteNode(i, scope, nodes);
1989
+ if (containing < 0) continue;
1990
+ positionAbsoluteNodeInContainingBlock(i, containing, nodes);
1991
+ }
1992
+
1993
+ int childParentX = a.layout.x;
1994
+ int childParentY = a.layout.y;
1995
+ if (a.style.overflow == 2) {
1996
+ if (scrollsOverflowX(a.style)) childParentX -= a.layout.scroll_x;
1997
+ if (scrollsOverflowY(a.style)) childParentY -= a.layout.scroll_y;
1998
+ }
1999
+ for (int child = a.first_child; child >= 0; child = nodes[child].next_sibling) {
2000
+ resolveAbsoluteCoords(child, childParentX, childParentY);
2001
+ }
2002
+ return true;
2003
+ }
2004
+
2005
+ void LayoutEngine::resolveAbsoluteCoords(int id, int parent_x, int parent_y)
2006
+ {
2007
+ Node *nodes = Tree::instance().nodes();
2008
+ Node *node = &nodes[id];
2009
+ if (node->parent < 0) resolveAbsoluteContainingBlocks(id);
2010
+ node->layout.x += parent_x;
2011
+ node->layout.y += parent_y;
2012
+
2013
+ int childParentX = node->layout.x;
2014
+ int childParentY = node->layout.y;
2015
+ if (node->style.overflow == 2) {
2016
+ if (scrollsOverflowX(node->style)) childParentX -= node->layout.scroll_x;
2017
+ if (scrollsOverflowY(node->style)) childParentY -= node->layout.scroll_y;
2018
+ }
2019
+
2020
+ for (int child = node->first_child; child >= 0; child = nodes[child].next_sibling) {
2021
+ resolveAbsoluteCoords(child, childParentX, childParentY);
2022
+ }
2023
+ }
2024
+
2025
+ } // namespace gea::embedded::ui