@geastack/engine 0.1.5 → 0.1.7

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 (45) hide show
  1. package/README.md +70 -0
  2. package/canvas.cpp +86 -30
  3. package/css/animation.h +64 -0
  4. package/css/declarative.h +6 -0
  5. package/css/engine.h +25 -1
  6. package/image_store.cpp +136 -33
  7. package/package.json +2 -2
  8. package/ui/CSS_FEATURES.md +261 -0
  9. package/ui/absolute_leaf_refresh.cpp +42 -39
  10. package/ui/core.cpp +32 -1
  11. package/ui/css_atom.cpp +6 -0
  12. package/ui/css_atom.h +2 -0
  13. package/ui/css_features.h +282 -0
  14. package/ui/display_invalidation.cpp +29 -0
  15. package/ui/flex_balance.h +73 -0
  16. package/ui/image_node.cpp +33 -28
  17. package/ui/input.cpp +88 -38
  18. package/ui/input_render.cpp +17 -13
  19. package/ui/internal.h +51 -5
  20. package/ui/layout.cpp +2601 -441
  21. package/ui/layout_snapshot.cpp +49 -6
  22. package/ui/node_features.h +18 -0
  23. package/ui/node_lifecycle.cpp +204 -71
  24. package/ui/node_lifecycle.h +1 -0
  25. package/ui/node_model.h +930 -70
  26. package/ui/node_text.h +82 -0
  27. package/ui/render.cpp +793 -352
  28. package/ui/renderer_features.h +19 -0
  29. package/ui/root_scroll_refresh.cpp +46 -24
  30. package/ui/style.cpp +4155 -1073
  31. package/ui/style.h +143 -6
  32. package/ui/style_values.h +16 -0
  33. package/ui/text.cpp +401 -106
  34. package/ui/tree_events.cpp +138 -95
  35. package/ui/tree_events.h +28 -19
  36. package/ui/tree_inspection.h +15 -0
  37. package/ui/tree_internal.h +19 -0
  38. package/ui/tree_nodes.cpp +38 -4
  39. package/ui/tree_render.cpp +119 -40
  40. package/ui/tree_scroll_mirror.cpp +26 -0
  41. package/ui/tree_state.cpp +261 -114
  42. package/ui/tree_state.h +121 -16
  43. package/ui/tree_style.cpp +609 -82
  44. package/ui/view.cpp +720 -299
  45. package/ui/virtual_keyboard.cpp +10 -3
package/ui/layout.cpp CHANGED
@@ -1,24 +1,107 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  #include "internal.h"
3
+ #include "flex_balance.h"
3
4
  #include "memory.h"
5
+ #include "tree_state.h"
4
6
  #include "refresh_perf.h"
5
7
 
6
8
  #include "graphics/font.h"
7
9
 
8
10
  #include <cstdio>
11
+ #include <climits>
9
12
  #include <cstring>
13
+ #include <algorithm>
14
+ #include <cmath>
15
+ #include <vector>
10
16
 
11
17
  namespace gea::embedded::ui {
12
18
 
19
+ bool isCollapsedFlexItem(const Node &node)
20
+ {
21
+ return node.style.visibility == 2 && node.parent >= 0 &&
22
+ !isOutOfFlowPosition(node.style.position) && Tree::instance().nodes()[node.parent].style.display == kDisplayFlex;
23
+ }
24
+
25
+ bool isCollapsedFlexSubtree(const Node &node)
26
+ {
27
+ const Node *nodes = Tree::instance().nodes();
28
+ for (const Node *current = &node; current; current = current->parent >= 0 ? &nodes[current->parent] : nullptr)
29
+ if (isCollapsedFlexItem(*current)) return true;
30
+ return false;
31
+ }
32
+
13
33
  namespace {
14
34
 
15
35
  constexpr int kScratchDepth = 16;
16
36
 
37
+ int formattingEdgeNode(const Node *nodes, int id, bool last);
38
+
39
+ bool isLineBreak(const Node &node)
40
+ {
41
+ return node.type == NodeType::View && std::strcmp(tagFromId(node.tag_id), "br") == 0;
42
+ }
43
+
44
+
45
+ bool suppressAnonymousWhitespace(const Node *nodes, int parent, int child)
46
+ {
47
+ const Node &text = nodes[child];
48
+ if (!isAnonymousTextNode(text)) return false;
49
+ if (text.text.empty()) return true;
50
+ if ((text.style.white_space != 0 && text.style.white_space != 1) || text.text.find_first_not_of(" \t\r\n\f") != std::string::npos) return false;
51
+ if (nodes[parent].style.display == kDisplayFlex || isDisplayGrid(nodes[parent].style)) return true;
52
+ // Whitespace at a line boundary or between block boxes creates no line.
53
+ // Preserve the text node itself and spaces between inline siblings.
54
+ auto adjacentInline = [&](int sibling, bool forward) {
55
+ while (sibling >= 0 && (isDisplayNone(nodes[sibling].style) || isOutOfFlowPosition(nodes[sibling].style.position) ||
56
+ (isAnonymousTextNode(nodes[sibling]) && (nodes[sibling].style.white_space == 0 || nodes[sibling].style.white_space == 1) &&
57
+ nodes[sibling].text.find_first_not_of(" \t\r\n\f") == std::string::npos)))
58
+ sibling = forward ? nodes[sibling].next_sibling : nodes[sibling].prev_sibling;
59
+ if (sibling >= 0) sibling = formattingEdgeNode(nodes, sibling, !forward);
60
+ return sibling >= 0 && !isLineBreak(nodes[sibling]) && LayoutEngine::isInlineLevelNode(nodes[sibling]);
61
+ };
62
+ return !adjacentInline(text.prev_sibling, false) || !adjacentInline(text.next_sibling, true);
63
+ }
64
+
65
+ // An inline wrapper shares its parent's line. Find a definite line boundary
66
+ // through preceding siblings and inline ancestors before measuring its first
67
+ // text run; padding does not turn leading collapsible whitespace into content.
68
+ bool startsFormattingLine(const Node *nodes, int id)
69
+ {
70
+ while (LayoutEngine::isCssInlineLevelBox(nodes[id]) && LayoutEngine::isInlineLevelNode(nodes[id])) {
71
+ for (int sibling = nodes[id].prev_sibling; sibling >= 0; sibling = nodes[sibling].prev_sibling) {
72
+ const Node &previous = nodes[sibling];
73
+ if (isDisplayNone(previous.style) || isOutOfFlowPosition(previous.style.position) || previous.style.float_side)
74
+ continue;
75
+ if (isAnonymousTextNode(previous) &&
76
+ (previous.style.white_space == 0 || previous.style.white_space == 1 || previous.style.white_space == 4) &&
77
+ previous.text.find_first_not_of(" \t\r\n\f") == std::string::npos) continue;
78
+ const int edge = formattingEdgeNode(nodes, sibling, true);
79
+ if (edge < 0) continue;
80
+ return isLineBreak(nodes[edge]) || !LayoutEngine::isInlineLevelNode(nodes[edge]);
81
+ }
82
+ id = nodes[id].parent;
83
+ if (id < 0) return true;
84
+ }
85
+ return true;
86
+ }
87
+
17
88
  struct FlexLine {
18
89
  int start = 0;
19
90
  int count = 0;
20
91
  int mainSize = 0;
21
92
  int crossSize = 0;
93
+ int strutSize = 0;
94
+ };
95
+
96
+ struct InlineFlowExtent { int width, height; int firstLineHeight = 0; };
97
+
98
+ struct FirstLineFragmentCandidate {
99
+ int node = -1;
100
+ int x = 0;
101
+ int width = 0;
102
+ int height = 0;
103
+ int itemIndex = -1;
104
+ int trailingSpace = 0;
22
105
  };
23
106
 
24
107
  class LayoutScratch {
@@ -103,9 +186,84 @@ int resolvePercentSize(int basis, int percent)
103
186
  return static_cast<int>((numerator + (numerator >= 0 ? 500 : -500)) / 1000);
104
187
  }
105
188
 
189
+ // Probe the existing formatting algorithms without rewriting authored style.
190
+ // A stack of constraints keeps nested measurements finite and allocates no
191
+ // per-node storage; a final phase supplies the selected used border-box size.
192
+ struct IntrinsicSizeScope;
193
+ IntrinsicSizeScope *gIntrinsicSizeScope = nullptr;
194
+ struct IntrinsicSizeScope {
195
+ const Node &node;
196
+ bool horizontal;
197
+ int constraint; // 1=min-content, 2=max-content, 0=final used size
198
+ int borderSize = 0;
199
+ IntrinsicSizeScope *previous;
200
+ IntrinsicSizeScope(const Node &n, int mode, bool axis = true) : node(n), horizontal(axis), constraint(mode), previous(gIntrinsicSizeScope) { gIntrinsicSizeScope = this; }
201
+ ~IntrinsicSizeScope() { gIntrinsicSizeScope = previous; }
202
+ };
203
+ IntrinsicSizeScope *intrinsicSizeScope(const Node &node, bool horizontal)
204
+ {
205
+ for (auto *scope = gIntrinsicSizeScope; scope; scope = scope->previous)
206
+ if (&scope->node == &node && scope->horizontal == horizontal) return scope;
207
+ return nullptr;
208
+ }
209
+ int intrinsicSizeConstraint(const Node &node, bool horizontal)
210
+ {
211
+ if (!gIntrinsicSizeScope) return 0;
212
+ const Node *current = &node;
213
+ for (;;) {
214
+ if (auto *scope = intrinsicSizeScope(*current, horizontal)) return scope->constraint;
215
+ const int expression = horizontal ? current->style.width_expression : current->style.height_expression;
216
+ if (current->parent < 0 || (horizontal ? current->style.width : current->style.height) != kUnset ||
217
+ (expression >= 0 && !layoutSizeExpressionUsesPercentage(
218
+ static_cast<int>(current - Tree::instance().nodes()), expression))) return 0;
219
+ current = &Tree::instance().nodes()[current->parent];
220
+ }
221
+ }
222
+ int intrinsicWidthConstraint(const Node &node) { return intrinsicSizeConstraint(node, true); }
223
+ // The flex basis replaces the preferred main size for item measurement without
224
+ // changing authored style. An unresolved percentage measures content, even when
225
+ // the item also has a preferred width/height.
226
+ struct FlexBasisScope;
227
+ FlexBasisScope *gFlexBasisScope = nullptr;
228
+ struct FlexBasisScope {
229
+ const Node &node;
230
+ bool horizontal;
231
+ int value;
232
+ FlexBasisScope *previous;
233
+ FlexBasisScope(const Node &n, bool h, int v) : node(n), horizontal(h), value(v), previous(gFlexBasisScope) { gFlexBasisScope = this; }
234
+ ~FlexBasisScope() { gFlexBasisScope = previous; }
235
+ };
236
+ const FlexBasisScope *flexBasisScope(const Node &node, bool horizontal)
237
+ {
238
+ for (auto *scope = gFlexBasisScope; scope; scope = scope->previous)
239
+ if (&scope->node == &node && scope->horizontal == horizontal) return scope;
240
+ return nullptr;
241
+ }
242
+ bool hasFlexBasis(const Node &node)
243
+ {
244
+ return node.style.flex_basis != kUnset || rstyle(node.style).flex_basis_expression >= 0;
245
+ }
246
+
106
247
  bool hasExplicitWidth(const Node &node)
107
248
  {
108
- return node.style.width != kUnset || node.style.width_percent != kUnset;
249
+ if (const auto *basis = flexBasisScope(node, true)) return basis->value != kUnset;
250
+ if (const auto *scope = intrinsicSizeScope(node, true); scope && scope->constraint == 0) return true;
251
+ if (isIntrinsicSizeExpression(node.style.width_expression)) {
252
+ const auto *scope = intrinsicSizeScope(node, true);
253
+ return scope && scope->constraint == 0;
254
+ }
255
+ if (node.style.width != kUnset) return true;
256
+ if (intrinsicWidthConstraint(node)) return false;
257
+ return node.style.width_expression >= 0 || node.style.width_percent != kUnset;
258
+ }
259
+
260
+ int clampLayoutSize(const Node &node, int size, bool horizontal)
261
+ {
262
+ const auto *scope = intrinsicSizeScope(node, horizontal);
263
+ // The property's intrinsic size is measured first; its author's min/max
264
+ // constraints apply to the final used size, after resolving box edges.
265
+ if (scope && scope->constraint) return std::max(boxInsets(node.style, horizontal), size);
266
+ return clampBorderBoxSize(node.style, size, horizontal);
109
267
  }
110
268
 
111
269
  int16_t clampInt16(int value)
@@ -115,13 +273,40 @@ int16_t clampInt16(int value)
115
273
  return static_cast<int16_t>(value);
116
274
  }
117
275
 
276
+ bool percentageHeightDependsOnIntrinsicSize(const Node &node)
277
+ {
278
+ if (isOutOfFlowPosition(node.style.position)) return false;
279
+ const Node *current = &node;
280
+ while (current->parent >= 0) {
281
+ const Node &parent = Tree::instance().nodes()[current->parent];
282
+ if (isIntrinsicSizeExpression(parent.style.height_expression)) return true;
283
+ if (parent.style.height != kUnset || isOutOfFlowPosition(parent.style.position)) return false;
284
+ if (parent.style.height_expression >= 0 &&
285
+ !layoutSizeExpressionUsesPercentage(current->parent, parent.style.height_expression)) return false;
286
+ current = &parent;
287
+ }
288
+ return false;
289
+ }
290
+
118
291
  bool hasExplicitHeight(const Node &node)
119
292
  {
120
- return node.style.height != kUnset || node.style.height_percent != kUnset;
293
+ if (const auto *basis = flexBasisScope(node, false)) return basis->value != kUnset;
294
+ if (const auto *scope = intrinsicSizeScope(node, false); scope && scope->constraint == 0) return true;
295
+ if (node.style.height != kUnset) return true;
296
+ if (intrinsicSizeConstraint(node, false)) return false;
297
+ if (node.style.height_expression < 0 && node.style.height_percent == kUnset) return false;
298
+ if (!percentageHeightDependsOnIntrinsicSize(node)) return true;
299
+ return node.style.height_percent == kUnset &&
300
+ !layoutSizeExpressionUsesPercentage(static_cast<int>(&node - Tree::instance().nodes()), node.style.height_expression);
121
301
  }
122
302
 
123
303
  int resolvedStyleWidth(const Node &node, int basis)
124
304
  {
305
+ if (const auto *scope = flexBasisScope(node, true)) return scope->value == kUnset ? basis : scope->value;
306
+ if (const auto *scope = intrinsicSizeScope(node, true); scope && scope->constraint == 0)
307
+ return std::max(0, scope->borderSize - (node.style.box_sizing == 0 ? boxInsets(node.style, true) : 0));
308
+ if (!hasExplicitWidth(node)) return basis;
309
+ if (node.style.width_expression >= 0) return resolveLayoutSizeExpression(static_cast<int>(&node - Tree::instance().nodes()), node.style.width_expression, true);
125
310
  if (node.style.width != kUnset) return node.style.width;
126
311
  if (node.style.width_percent != kUnset) return resolvePercentSize(basis, node.style.width_percent);
127
312
  return basis;
@@ -129,44 +314,301 @@ int resolvedStyleWidth(const Node &node, int basis)
129
314
 
130
315
  int resolvedStyleHeight(const Node &node, int basis)
131
316
  {
317
+ if (const auto *scope = flexBasisScope(node, false)) return scope->value == kUnset ? basis : scope->value;
318
+ if (const auto *scope = intrinsicSizeScope(node, false); scope && scope->constraint == 0)
319
+ return std::max(0, scope->borderSize - (node.style.box_sizing == 0 ? boxInsets(node.style, false) : 0));
320
+ if (!hasExplicitHeight(node)) return basis;
321
+ if (node.style.height_expression >= 0) return resolveLayoutSizeExpression(static_cast<int>(&node - Tree::instance().nodes()), node.style.height_expression, false);
132
322
  if (node.style.height != kUnset) return node.style.height;
133
- if (node.style.height_percent != kUnset) return resolvePercentSize(basis, node.style.height_percent);
323
+ if (node.style.height_percent != kUnset && !percentageHeightDependsOnIntrinsicSize(node))
324
+ return resolvePercentSize(basis, node.style.height_percent);
134
325
  return basis;
135
326
  }
136
327
 
328
+ int writingMode(const Node &node)
329
+ {
330
+ const Node *current = &node;
331
+ while (current->style.writing_mode < 0 && current->parent >= 0)
332
+ current = &Tree::instance().nodes()[current->parent];
333
+ return current->style.writing_mode < 0 ? 0 : current->style.writing_mode;
334
+ }
335
+
336
+ bool rightToLeft(const Node &node)
337
+ {
338
+ const Node *current = &node;
339
+ while (current->style.direction < 0 && current->parent >= 0)
340
+ current = &Tree::instance().nodes()[current->parent];
341
+ return current->style.direction == 1;
342
+ }
343
+
344
+ struct GridAxisPlacement {
345
+ int start = kUnset, end = kUnset, span = 1;
346
+ };
347
+
348
+ GridAxisPlacement gridAxisPlacement(int start, int end, int explicitTracks, bool absolute)
349
+ {
350
+ GridAxisPlacement p;
351
+ const bool startSpan = start >= kGridLineSpan, endSpan = end >= kGridLineSpan;
352
+ p.span = std::min(kMaxGridLayoutTracks, startSpan ? start - kGridLineSpan : endSpan ? end - kGridLineSpan : 1);
353
+ auto line = [explicitTracks](int n) { return n > 0 ? n - 1 : explicitTracks + 1 + n; };
354
+ if (start && !startSpan) p.start = line(start);
355
+ if (end && !endSpan) p.end = line(end);
356
+ if (p.start != kUnset && p.end != kUnset) {
357
+ if (p.start > p.end) std::swap(p.start, p.end);
358
+ if (p.start == p.end) p.end = kUnset;
359
+ }
360
+ if (p.start != kUnset && (endSpan || !absolute) && p.end == kUnset) p.end = p.start + p.span;
361
+ if (p.end != kUnset && (startSpan || !absolute) && p.start == kUnset) p.start = p.end - p.span;
362
+ if (p.start != kUnset && p.end != kUnset) p.span = std::min(kMaxGridLayoutTracks, p.end - p.start);
363
+ return p;
364
+ }
365
+
366
+ bool gridAxisReversed(const Node &parent, bool horizontal)
367
+ {
368
+ const int mode = writingMode(parent);
369
+ const bool inlineAxis = horizontal == (mode == 0);
370
+ return inlineAxis ? rightToLeft(parent) != (mode == 4) : mode == 2 || mode == 3;
371
+ }
372
+
373
+ bool flexRowDirection(const ComputedStyle &style);
374
+
375
+ double preferredRatio(const Node &node)
376
+ {
377
+ float ratio = 0;
378
+ const int bits = (GEA_CSS_ASPECT_RATIO ? rstyle(node.style).aspect_ratio : 0);
379
+ std::memcpy(&ratio, &bits, sizeof(ratio));
380
+ if (!std::isfinite(ratio)) return 0;
381
+ if (ratio < 0 && node.type == NodeType::Image && node.image_id >= 0) return 0;
382
+ return std::abs(static_cast<double>(ratio));
383
+ }
384
+
385
+ int ratioTransferredSize(const Node &node, int crossBorderSize, bool horizontal)
386
+ {
387
+ const double ratio = preferredRatio(node);
388
+ if (ratio <= 0) return 0;
389
+ const int crossEdges = node.style.box_sizing ? 0 : boxInsets(node.style, !horizontal);
390
+ const int mainEdges = node.style.box_sizing ? 0 : boxInsets(node.style, horizontal);
391
+ const double value = std::max(0, crossBorderSize - crossEdges) * (horizontal ? ratio : 1 / ratio) + mainEdges;
392
+ return static_cast<int>(std::min(32767.0, std::round(value)));
393
+ }
394
+
395
+ bool definiteFlexCrossSize(const Node &parent, const Node &child, bool row)
396
+ {
397
+ const int alignment = child.style.align_self >= 0 ? child.style.align_self : parent.style.align_items;
398
+ const int margins = row ? 5 : 10;
399
+ return parent.style.flex_wrap == 0 && alignment == 0 && !(child.style.margin_auto & margins) &&
400
+ (row ? hasExplicitHeight(parent) : hasExplicitWidth(parent));
401
+ }
402
+
403
+ void applyPreferredRatio(Node &node, int availableWidth, int availableHeight)
404
+ {
405
+ if (!preferredRatio(node) || (node.type != NodeType::View && node.type != NodeType::Image)) return;
406
+ if (node.type != NodeType::Image && LayoutEngine::isInlineLevelNode(node)) return;
407
+ bool width = hasExplicitWidth(node), height = hasExplicitHeight(node);
408
+ if (width && height) return;
409
+ const Node *parent = node.parent >= 0 ? &Tree::instance().nodes()[node.parent] : nullptr;
410
+ const bool flexItem = parent && parent->style.display == kDisplayFlex;
411
+ if (flexItem && !width && !height) {
412
+ const bool row = flexRowDirection(parent->style) != (writingMode(*parent) != 0);
413
+ if (definiteFlexCrossSize(*parent, node, row)) {
414
+ if (row) {
415
+ node.layout.height = clampLayoutSize(node, availableHeight - node.style.margin[0] - node.style.margin[2], false);
416
+ height = true;
417
+ } else {
418
+ node.layout.width = clampLayoutSize(node, availableWidth - node.style.margin[1] - node.style.margin[3], true);
419
+ width = true;
420
+ }
421
+ }
422
+ }
423
+ if (!width && !height) {
424
+ // Normal block flow supplies a definite inline size. Shrink-to-fit
425
+ // contexts keep the intrinsic width measured from their contents.
426
+ if (!flexItem && !node.style.float_side && !isOutOfFlowPosition(node.style.position))
427
+ node.layout.width = clampLayoutSize(node, availableWidth - node.style.margin[1] - node.style.margin[3], true);
428
+ width = true;
429
+ }
430
+ const bool horizontal = !width && height;
431
+ int16_t &target = horizontal ? node.layout.width : node.layout.height;
432
+ const int fromRatio = ratioTransferredSize(node, horizontal ? node.layout.height : node.layout.width, horizontal);
433
+ // Non-scrollable boxes retain a content-based minimum on the automatic axis.
434
+ const bool contentMinimum = node.type != NodeType::Image && (horizontal ? node.style.min_width : node.style.min_height) == kUnset &&
435
+ !isScrollableOverflow(horizontal ? overflowX(node.style) : overflowY(node.style));
436
+ const int result = contentMinimum ? std::max<int>(target, fromRatio) : fromRatio;
437
+ target = clampInt16(clampLayoutSize(node, result, horizontal));
438
+ }
439
+
440
+ int baselineFallbackAlignment(const Node &parent, const Node &child, int alignment, int free, bool horizontal, bool staticPosition)
441
+ {
442
+ // Baseline self-alignment follows the subject's writing mode. Resolving
443
+ // automatic insets uses the fallback edge without overflow safety; actual
444
+ // in-flow self-alignment uses the safe fallback instead (CSS Position 3.5.1).
445
+ if (!staticPosition && free < 0)
446
+ return gridAxisReversed(parent, horizontal) ? 2 : 6;
447
+ const bool last = (alignment & 15) == kAlignLastBaseline;
448
+ return gridAxisReversed(child, horizontal) != last ? 2 : 6;
449
+ }
450
+
451
+ // Self-relative edges use the subject's writing mode, even when it differs
452
+ // from the containing box. Return physical start/end; flex positioning may
453
+ // subsequently express it relative to its reversed cross axis.
454
+ int physicalSelfAlignment(const Node &parent, const Node &child, int alignment, int free, bool horizontal)
455
+ {
456
+ const int keyword = alignment & 15;
457
+ if (keyword != kAlignSelfStart && keyword != kAlignSelfEnd && keyword != kAlignLeft && keyword != kAlignRight) return -1;
458
+ if ((alignment & kAlignSafe) && free < 0) return gridAxisReversed(parent, horizontal) ? 2 : 6;
459
+ if (keyword == kAlignLeft || keyword == kAlignRight) {
460
+ if (horizontal) return keyword == kAlignRight ? 2 : 6;
461
+ // In vertical text, left/right are line-relative and independent of
462
+ // bidi direction. Sideways-lr alone has line-left at physical bottom.
463
+ const int mode = writingMode(parent);
464
+ if (mode != 0) return (mode == 4) != (keyword == kAlignRight) ? 2 : 6;
465
+ return 6;
466
+ }
467
+ return gridAxisReversed(child, horizontal) != (keyword == kAlignSelfEnd) ? 2 : 6;
468
+ }
469
+
470
+ int usedGridAlignment(const Node &parent, const Node &child, int alignment, int free, bool horizontal, bool staticPosition = false)
471
+ {
472
+ const int self = physicalSelfAlignment(parent, child, alignment, free, horizontal);
473
+ if (self >= 0) return self;
474
+ const int keyword = alignment & 15;
475
+ if (keyword == 5 || keyword == kAlignLastBaseline)
476
+ return baselineFallbackAlignment(parent, child, alignment, free, horizontal, staticPosition);
477
+ if (keyword == 0 || keyword == 6) alignment = (alignment & ~15) | kAlignStart;
478
+ else if (keyword == 2) alignment = (alignment & ~15) | kAlignEnd;
479
+ return usedAlignment(alignment, free, gridAxisReversed(parent, horizontal));
480
+ }
481
+
482
+ void gridPhysicalRange(const Node &parent, bool columns, int start, int end, int &offset, int &size)
483
+ {
484
+ const bool horizontal = columns == (writingMode(parent) == 0);
485
+ const int available = (horizontal ? parent.layout.width : parent.layout.height) - boxInsets(parent.style, horizontal);
486
+ offset = boxInset(parent.style, horizontal ? 3 : 0) + (gridAxisReversed(parent, horizontal) ? available - end : start);
487
+ size = std::max(0, end - start);
488
+ }
489
+
490
+ bool flexRowDirection(const ComputedStyle &style)
491
+ {
492
+ return !style.flex_direction_explicit || (style.flex_direction & 1);
493
+ }
494
+
495
+ int resolvedGap(const Node &node, bool rowGap, int width, int height)
496
+ {
497
+ const int length = rowGap ? node.style.row_gap : node.style.column_gap;
498
+ const int percent = rowGap ? node.style.row_gap_percent : node.style.column_gap_percent;
499
+ const bool vertical = writingMode(node) != 0;
500
+ const bool horizontalAxis = rowGap == vertical;
501
+ if (percent != kUnset) {
502
+ // Cyclic percentage gaps have zero used size in an indefinite flex axis.
503
+ if (horizontalAxis ? !hasExplicitWidth(node) : !hasExplicitHeight(node)) return 0;
504
+ return std::max(0, resolvePercentSize(horizontalAxis ? width : height, percent));
505
+ }
506
+ return std::max(0, length == kUnset ? node.style.gap : length);
507
+ }
508
+
509
+ int clampBorderSize(LayoutEngine &engine, const Node &node, int size, bool horizontal)
510
+ {
511
+ return clampLayoutSize(node, size, horizontal);
512
+ }
513
+
137
514
  class FlexLayoutPass {
138
515
  public:
139
- FlexLayoutPass(LayoutEngine &engine, Node &node, int *children, int childCount, bool isRow, int mainAvail, int padWidth, int padHeight, FlexLine *lines, bool inlineRow = false)
516
+ FlexLayoutPass(LayoutEngine &engine, Node &node, int *children, int childCount, bool isRow, int mainAvail, int padWidth, int padHeight, FlexLine *lines, bool inlineRow = false, bool assignedSize = false)
140
517
  : engine_(engine),
141
518
  node_(node),
142
519
  children_(children),
143
520
  childCount_(childCount),
144
521
  isRow_(isRow),
145
522
  inlineRow_(inlineRow && isRow),
523
+ assignedSize_(assignedSize),
146
524
  mainAvail_(mainAvail),
147
525
  padWidth_(padWidth),
148
526
  padHeight_(padHeight),
149
527
  lines_(lines)
150
528
  {
529
+ const bool logicalRow = node.style.display == kDisplayFlex ? flexRowDirection(node.style) : isRow;
530
+ mainGap_ = resolvedGap(node, !logicalRow, padWidth, padHeight);
531
+ crossGap_ = resolvedGap(node, logicalRow, padWidth, padHeight);
532
+ // Most containers fit the shared 32-line storage. Allocate extra lines
533
+ // only for a wrapping container that can actually exceed it.
534
+ if (node.style.display == kDisplayFlex && node.style.flex_wrap && childCount > kMaxFlexLines) {
535
+ extraLines_.resize(childCount);
536
+ lines_ = extraLines_.data();
537
+ }
151
538
  }
152
539
 
153
540
  void measureChildren()
154
541
  {
155
542
  for (int i = 0; i < childCount_; i++) {
156
543
  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);
544
+ int childAvailWidth = isRow_ ? mainAvail_ : padWidth_;
545
+ int childAvailHeight = isRow_ ? padHeight_ : mainAvail_;
546
+ const int count = (GEA_CSS_FLEX_LINE_COUNT ? rstyle(node_.style).flex_line_count : 1);
547
+ const Node &item = Tree::instance().nodes()[child];
548
+ if (node_.style.display == kDisplayFlex && node_.style.flex_wrap && count > 1) {
549
+ // The specified count limits available cross space even for normal
550
+ // wrapping. Percentage cross sizes retain the container's basis.
551
+ const auto available = [&](int size) {
552
+ return static_cast<int>(std::max<std::int64_t>(0, (static_cast<std::int64_t>(size) -
553
+ static_cast<std::int64_t>(count - 1) * crossGap_) / count));
554
+ };
555
+ if (isRow_ && hasExplicitHeight(node_) && !hasExplicitHeight(item)) childAvailHeight = available(childAvailHeight);
556
+ if (!isRow_ && !hasExplicitWidth(item)) childAvailWidth = available(childAvailWidth);
557
+ }
558
+ if (node_.style.display == kDisplayFlex && hasFlexBasis(item)) {
559
+ const int basis = resolveLayoutFlexBasis(child, flexPercentageBasis(), isRow_);
560
+ FlexBasisScope scope(item, isRow_, basis);
561
+ engine_.layoutNode(child, childAvailWidth, childAvailHeight);
562
+ } else {
563
+ engine_.layoutNode(child, childAvailWidth, childAvailHeight);
564
+ }
565
+ if (node_.style.display == kDisplayFlex) {
566
+ applyFlexBasis(child);
567
+ Node &item = Tree::instance().nodes()[child];
568
+ const int floor = automaticMinimumMainSize(item);
569
+ int16_t &main = isRow_ ? item.layout.width : item.layout.height;
570
+ if (main < floor) { main = clampInt16(floor); engine_.repositionChildren(child); }
571
+ }
161
572
  }
162
573
  }
163
574
 
575
+ void layoutLines(bool autosize)
576
+ {
577
+ const int originalWidth = node_.layout.width, originalHeight = node_.layout.height;
578
+ int lineCount = buildLines();
579
+ expandCrossSizes(lineCount, autosize);
580
+ if (autosize) autosizeParent(lineCount);
581
+ positionLines(lineCount);
582
+ if (node_.style.display != kDisplayFlex) return;
583
+ Node *nodes = Tree::instance().nodes();
584
+ bool collapsed = false;
585
+ for (int i = 0; i < childCount_; ++i) collapsed |= isCollapsedFlexItem(nodes[children_[i]]);
586
+ if (!collapsed) return;
587
+
588
+ // Flexbox 9.4: remember the original (including stretched) line size,
589
+ // then restart with zero-main-size struts. Compact the child list only
590
+ // AFTER assigning struts to lines, so allocation, gaps, auto margins,
591
+ // baselines and alignment all operate on the surviving items alone.
592
+ std::vector<int> struts(childCount_, -1);
593
+ for (int line = 0; line < lineCount; ++line)
594
+ for (int i = lines_[line].start; i < lines_[line].start + lines_[line].count; ++i)
595
+ if (isCollapsedFlexItem(nodes[children_[i]])) struts[i] = lines_[line].crossSize;
596
+ node_.layout.width = originalWidth;
597
+ node_.layout.height = originalHeight;
598
+ measureChildren();
599
+ lineCount = buildCollapsedLines(struts);
600
+ expandCrossSizes(lineCount, autosize);
601
+ if (autosize) autosizeParent(lineCount);
602
+ positionLines(lineCount);
603
+ }
604
+
164
605
  // Flex line packing. An inline formatting context does NOT come through here —
165
606
  // layoutInlineFlow owns it — because flex lines cannot express one: their items
166
607
  // are atomic, so a text run may neither share a line with its neighbours nor
167
608
  // split across two.
168
609
  int buildLines()
169
610
  {
611
+ if (node_.style.display == kDisplayFlex && (node_.style.flex_wrap & 4)) return buildBalancedLines();
170
612
  int lineStart = 0;
171
613
  int lineMain = 0;
172
614
  int lineCross = 0;
@@ -184,8 +626,8 @@ public:
184
626
  ? (childNode.layout.height + childNode.style.margin[0] + childNode.style.margin[2])
185
627
  : (childNode.layout.width + childNode.style.margin[1] + childNode.style.margin[3]);
186
628
 
187
- const int withGap = gapCount > 0 ? node_.style.gap : 0;
188
- if (node_.style.flex_wrap && lineMain + childMain + withGap > mainAvail_ && gapCount > 0) {
629
+ const int withGap = gapCount > 0 ? mainGap_ : 0;
630
+ if (node_.style.display == kDisplayFlex && node_.style.flex_wrap && lineMain + childMain + withGap > flexWrapLimit() && gapCount > 0) {
189
631
  appendLine(lineCount, lineStart, gapCount, lineMain, lineCross);
190
632
  lineStart = i;
191
633
  lineMain = childMain;
@@ -214,24 +656,91 @@ public:
214
656
  // One forward walk. Per line box it first SCANS ahead to learn which items
215
657
  // share it — and therefore the line's ascent, and so its baseline — then
216
658
  // places them. The scans partition the item list, so the pass is linear.
217
- void layoutInlineFlow(bool autosize)
659
+ InlineFlowExtent layoutInlineFlow(bool autosize, bool anonymous = false)
218
660
  {
219
661
  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_);
662
+ const int parentId = static_cast<int>(&node_ - nodes);
663
+ int firstLineStyleOwner = -1;
664
+ #if GEA_CSS_FIRST_LINE
665
+ for (int ancestor = parentId; ancestor >= 0; ancestor = nodes[ancestor].parent) {
666
+ const NodeRareData *rare = rareDataFor(ancestor);
667
+ if (rare && rare->firstLineBackground.hasColor) {
668
+ firstLineStyleOwner = ancestor;
669
+ break;
670
+ }
671
+ // Inline boxes carry the rule down their descendants. A block child
672
+ // carries it only when it is the first in-flow formatted child of its
673
+ // parent; following block siblings start after the owner's first line.
674
+ if (!LayoutEngine::isCssInlineLevelBox(nodes[ancestor])) {
675
+ if (isOutOfFlowPosition(nodes[ancestor].style.position) || nodes[ancestor].style.float_side) break;
676
+ const int parent = nodes[ancestor].parent;
677
+ if (parent < 0) break;
678
+ if (nodes[parent].style.display == kDisplayFlex || isDisplayGrid(nodes[parent].style)) break;
679
+ bool firstInFlow = true;
680
+ for (int sibling = nodes[parent].first_child; sibling >= 0 && sibling != ancestor;
681
+ sibling = nodes[sibling].next_sibling) {
682
+ if (!isDisplayNone(nodes[sibling].style) &&
683
+ !isOutOfFlowPosition(nodes[sibling].style.position) &&
684
+ !nodes[sibling].style.float_side &&
685
+ !suppressAnonymousWhitespace(nodes, parent, sibling)) {
686
+ firstInFlow = false;
687
+ break;
688
+ }
689
+ }
690
+ if (!firstInFlow) break;
691
+ }
692
+ }
693
+ #endif
694
+ const bool captureFirstLine = firstLineStyleOwner >= 0;
695
+ #if GEA_CSS_FIRST_LINE
696
+ // Runs that leave this formatting context must not keep an old fragment
697
+ // rectangle. A nested inline flow may write its own first-line fragment
698
+ // later in the same layout pass.
699
+ for (int i = 0; i < childCount_; ++i) {
700
+ const int child = children_[i];
701
+ if (NodeRareData *rare = rareDataFor(child)) rare->firstLineFragment.valid = false;
702
+ const int run = transparentInlineRun(nodes[child]);
703
+ if (run >= 0) if (NodeRareData *rare = rareDataFor(run)) rare->firstLineFragment.valid = false;
704
+ }
705
+ #endif
706
+ std::vector<std::pair<int, int>> staticBoundaries;
707
+ int flowIndex = 0;
708
+ for (int child = node_.first_child; child >= 0; child = nodes[child].next_sibling) {
709
+ if (isDisplayNone(nodes[child].style) || suppressAnonymousWhitespace(nodes, parentId, child)) continue;
710
+ if (isOutOfFlowPosition(nodes[child].style.position)) {
711
+ if (auto *rare = rareDataFor(child)) rare->inlineStaticPosition.valid = false;
712
+ if (LayoutEngine::isCssInlineLevelBox(nodes[child], true))
713
+ staticBoundaries.emplace_back(flowIndex, child);
714
+ continue;
715
+ }
716
+ while (flowIndex < childCount_ && children_[flowIndex] != child) ++flowIndex;
717
+ if (flowIndex < childCount_) ++flowIndex;
718
+ }
719
+ int contentW = mainAvail_ < 0 ? 0 : mainAvail_;
720
+ if (intrinsicWidthConstraint(node_) == 1) {
721
+ int pendingWord = 0;
722
+ for (int i = 0; i < childCount_; ++i) {
723
+ const Node &child = nodes[children_[i]];
724
+ if (isLineBreak(child)) { pendingWord = 0; continue; }
725
+ const int wrappedRun = transparentInlineRun(child);
726
+ if (child.type == NodeType::Text || wrappedRun >= 0) {
727
+ contentW = std::max(contentW, TextRenderer::minContentWidth(wrappedRun >= 0 ? nodes[wrappedRun] : child, &pendingWord));
728
+ } else {
729
+ contentW = std::max(contentW, child.layout.width + child.style.margin[1] + child.style.margin[3]);
730
+ pendingWord = 0;
731
+ }
732
+ }
733
+ }
734
+ const int contentLeft = boxInset(node_.style, 3);
735
+ const int contentTop = boxInset(node_.style, 0);
736
+ const int gapStyle = mainGap_;
737
+
738
+ const bool blockOpensItsFirstLine = startsFormattingLine(nodes, parentId);
231
739
  int i = 0;
232
740
  int lineTop = contentTop;
233
741
  int flowBottom = contentTop;
234
742
  int maxLineWidth = 0;
743
+ int firstLineHeight = 0;
235
744
  // Carried across a wrapped run: the pen its last line ended at, that
236
745
  // line's already-fixed baseline, and the ascent/descent it contributes.
237
746
  int penStart = 0;
@@ -239,6 +748,21 @@ public:
239
748
  int continuedBaseline = 0;
240
749
  int inheritedAscent = 0;
241
750
  int inheritedDescent = 0;
751
+ std::vector<bool> staticCaptured(staticBoundaries.size(), false);
752
+ std::vector<FirstLineFragmentCandidate> firstLineCandidates;
753
+ auto captureStaticBoundary = [&](int boundary, int pen, std::vector<int> &captured,
754
+ bool continuationLine = false) {
755
+ for (std::size_t k = 0; k < staticBoundaries.size(); ++k) {
756
+ if (staticCaptured[k] || staticBoundaries[k].first != boundary) continue;
757
+ staticCaptured[k] = true;
758
+ captured.push_back(staticBoundaries[k].second);
759
+ NodeRareData &rare = ensureRareData(staticBoundaries[k].second);
760
+ rare.inlineStaticPosition.continuationLine =
761
+ continuationLine && LayoutEngine::isCssInlineLevelBox(node_);
762
+ rare.inlineStaticPosition.x = clampInt16(
763
+ (rare.inlineStaticPosition.continuationLine ? 0 : contentLeft) + pen);
764
+ }
765
+ };
242
766
 
243
767
  while (i < childCount_) {
244
768
  // A line box that opens as the tail of a wrapped run already has content
@@ -252,21 +776,33 @@ public:
252
776
  int wrapSpans = 0;
253
777
  int wrapAdvance = 0;
254
778
  int wrapLastWidth = 0;
779
+ std::vector<int> lineStaticChildren;
255
780
 
256
781
  for (; j < childCount_; j++) {
782
+ captureStaticBoundary(j, pen, lineStaticChildren, lineIsContinuation || i > 0);
257
783
  const int child = children_[j];
258
784
  Node &cn = nodes[child];
259
785
  const int marginL = cn.style.margin[3];
260
786
  const int marginR = cn.style.margin[1];
261
787
  const int gap = pen > 0 ? gapStyle : 0;
262
788
 
789
+ if (isLineBreak(cn)) {
790
+ // A BR closes this line even under white-space:nowrap/pre.
791
+ // It contributes its inherited line metrics to an otherwise
792
+ // empty line, but does not create a trailing phantom line.
793
+ lineAscent = std::max(lineAscent, childBaseline(cn));
794
+ lineDescent = std::max(lineDescent, cn.layout.height - childBaseline(cn));
795
+ ++j;
796
+ break;
797
+ }
798
+
263
799
  // The run this item contributes to the line: itself when it IS a text
264
800
  // run, or the one inside a transparent <span> wrapper.
265
801
  const int innerRun = isFragmentableRun(cn) ? -1 : transparentInlineRun(cn);
266
802
  Node &subject = innerRun >= 0 ? nodes[innerRun] : cn;
267
803
  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];
804
+ const int padH = boxInset(subject.style, 1) + boxInset(subject.style, 3);
805
+ const int padV = boxInset(subject.style, 0) + boxInset(subject.style, 2);
270
806
  // Budgets are TEXT widths: the run's own padding is part of its box,
271
807
  // not of the line it can fill.
272
808
  const int rest = contentW - marginL - marginR - padH;
@@ -279,16 +815,22 @@ public:
279
815
  // run keeps flowing whole, exactly as before.
280
816
  const bool haveLineMetrics =
281
817
  m.lineAdvance > 0 &&
282
- childFirstBaseline(subject) <= subject.style.padding[0] + m.lineAdvance;
818
+ childBaseline(subject) <= boxInset(subject.style, 0) + m.lineAdvance;
283
819
  if (m.lineCount > 0 && haveLineMetrics) {
284
820
  // Its first WORD does not fit what is left: the run starts the
285
821
  // next line box rather than overflowing it or being cut open.
286
- if (pen > 0 && (m.firstLineWidth > firstAvail || m.firstLineForcedSplit)) break;
822
+ if (pen > 0 && m.firstLineWidth > firstAvail) break;
287
823
  const int boxH = m.lineCount * m.lineAdvance + padV;
288
824
  const bool wraps = m.lineCount > 1;
289
825
  const int boxW = wraps ? rest + padH : m.firstLineWidth + padH;
290
826
  const int indent =
291
827
  (wraps ? pen + gap : 0) + m.firstLineIndentAdjust;
828
+ const bool firstLineFragment = captureFirstLine && i == 0 && m.firstLineWidth > 0;
829
+ const int fragmentItemX = wraps ? contentLeft + marginL : contentLeft + pen + gap + marginL;
830
+ // The text-command indent compensates for collapsed leading
831
+ // whitespace; that discarded space is not part of the fragment.
832
+ const int firstLineFragmentX = fragmentItemX + (wraps ? pen + gap : 0);
833
+ const int firstLineFragmentWidth = m.firstLineWidth + padH;
292
834
  subject.layout.height = clampInt16(boxH);
293
835
  subject.layout.width = clampInt16(boxW);
294
836
  subject.layout.inline_indent = clampInt16(indent);
@@ -303,7 +845,7 @@ public:
303
845
  cn.layout.inline_indent = clampInt16(indent);
304
846
  }
305
847
  if (wraps) {
306
- const int ascent = cn.style.margin[0] + childFirstBaseline(cn);
848
+ const int ascent = cn.style.margin[0] + childBaseline(cn);
307
849
  const int descent = runLineDescent(subject, m.lineAdvance);
308
850
  if (ascent > lineAscent) lineAscent = ascent;
309
851
  if (descent > lineDescent) lineDescent = descent;
@@ -313,6 +855,10 @@ public:
313
855
  wrapSpans = m.lineCount;
314
856
  wrapAdvance = m.lineAdvance;
315
857
  wrapLastWidth = m.lastLineWidth + padH;
858
+ if (firstLineFragment)
859
+ firstLineCandidates.push_back({innerRun >= 0 ? innerRun : child,
860
+ firstLineFragmentX, firstLineFragmentWidth,
861
+ m.lineAdvance + padV, j, m.firstLineTrailingSpace});
316
862
  j++;
317
863
  break; // the run closes this line box
318
864
  }
@@ -323,40 +869,114 @@ public:
323
869
 
324
870
  const int itemMain = cn.layout.width + marginL + marginR;
325
871
  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);
872
+ if (isFragmentableRun(subject) && captureFirstLine && i == 0) {
873
+ const int padH = boxInset(subject.style, 1) + boxInset(subject.style, 3);
874
+ const int rest = contentW - marginL - marginR - padH;
875
+ const InlineFlowMeasure m = TextRenderer::measureInlineFlow(
876
+ subject, rest - pen - gap, rest, pen == 0 && (j > 0 || blockOpensItsFirstLine));
877
+ if (m.lineCount > 0 && m.firstLineWidth > 0) {
878
+ firstLineCandidates.push_back({innerRun >= 0 ? innerRun : child,
879
+ contentLeft + pen + gap + marginL,
880
+ m.firstLineWidth + padH,
881
+ m.lineAdvance + boxInset(subject.style, 0) + boxInset(subject.style, 2),
882
+ j, m.firstLineTrailingSpace});
883
+ }
884
+ }
885
+ const int ascent = cn.style.margin[0] + childBaseline(cn);
886
+ const int descent = cn.layout.height + cn.style.margin[2] - childBaseline(cn);
328
887
  if (ascent > lineAscent) lineAscent = ascent;
329
888
  if (descent > lineDescent) lineDescent = descent;
330
889
  pen += gap + itemMain;
331
890
  }
891
+ const bool endedWithBreak = j > i && isLineBreak(nodes[children_[j - 1]]);
892
+ const bool trailingWrappedStaticBoundary = j >= childCount_ && !endedWithBreak && wrapIdx >= 0;
893
+ if (j >= childCount_ && !endedWithBreak && !trailingWrappedStaticBoundary)
894
+ captureStaticBoundary(childCount_, pen, lineStaticChildren, lineIsContinuation || i > 0);
332
895
 
333
896
  if (pen > maxLineWidth) maxLineWidth = pen;
334
897
 
335
898
  const int baseline = continuing ? continuedBaseline : lineTop + lineAscent;
336
899
  lineTop = baseline - lineAscent;
900
+ for (int id : lineStaticChildren) {
901
+ auto &position = ensureRareData(id).inlineStaticPosition;
902
+ position.y = clampInt16(lineTop);
903
+ position.valid = true;
904
+ }
337
905
  int lineCross = lineAscent + lineDescent;
338
906
  if (lineCross < 0) lineCross = 0;
907
+ const int actualLineCross = lineCross;
908
+ if (i == 0) firstLineHeight = lineCross;
339
909
  // The one case the flex path's expandCrossSizes is observable here: a
340
910
  // lone line box in a block with a definite height fills it, so
341
911
  // `align-self: center/end` on an inline child has room to work.
342
- if (i == 0 && j >= childCount_ && wrapIdx < 0 && hasExplicitHeight(node_) &&
912
+ if (!anonymous && i == 0 && j >= childCount_ && wrapIdx < 0 && hasExplicitHeight(node_) &&
343
913
  padHeight_ > lineCross)
344
914
  lineCross = padHeight_;
345
915
 
346
916
  placeLineItems(nodes, i, j, contentLeft, contentW, lineTop, lineCross, baseline, penStart,
347
917
  !lineIsContinuation);
918
+ #if GEA_CSS_FIRST_LINE
919
+ if (i == 0 && captureFirstLine) {
920
+ int firstFormattedLineHeight = actualLineCross;
921
+ if (!firstLineCandidates.empty()) firstFormattedLineHeight = 0;
922
+ for (const auto &candidate : firstLineCandidates)
923
+ firstFormattedLineHeight = std::max(firstFormattedLineHeight, candidate.height);
924
+ if (firstLineStyleOwner == parentId) {
925
+ auto &style = ensureRareData(parentId).firstLineBackground;
926
+ if (!style.lineValid) {
927
+ style.lineY = clampInt16(lineTop);
928
+ style.lineHeight = clampInt16(firstFormattedLineHeight);
929
+ style.lineContextNode = static_cast<std::int16_t>(parentId);
930
+ style.lineValid = actualLineCross > 0;
931
+ }
932
+ } else if (firstLineStyleOwner >= 0 && !LayoutEngine::isCssInlineLevelBox(node_)) {
933
+ // A nested inline's local first line may ultimately land on a
934
+ // later owner line. The owner's inline pass chooses that anchor;
935
+ // only an eligible first block child can supply it from below.
936
+ auto &style = ensureRareData(firstLineStyleOwner).firstLineBackground;
937
+ if (!style.lineValid) {
938
+ style.lineY = clampInt16(lineTop);
939
+ style.lineHeight = clampInt16(firstFormattedLineHeight);
940
+ style.lineContextNode = static_cast<std::int16_t>(parentId);
941
+ style.lineValid = actualLineCross > 0;
942
+ }
943
+ }
944
+ for (const auto &candidate : firstLineCandidates) {
945
+ if (candidate.node < 0 || candidate.node >= Tree::instance().nodeCount()) continue;
946
+ auto &fragment = ensureRareData(candidate.node).firstLineFragment;
947
+ fragment.x = clampInt16(candidate.x);
948
+ fragment.y = clampInt16(lineTop);
949
+ // Spaces between inline runs remain part of the background;
950
+ // collapsible spaces at the end of the line do not.
951
+ const bool endsLine = candidate.itemIndex == j - (endedWithBreak ? 2 : 1);
952
+ fragment.width = clampInt16(std::max(0, candidate.width - (endsLine ? candidate.trailingSpace : 0)));
953
+ fragment.height = clampInt16(candidate.height);
954
+ fragment.contextNode = static_cast<std::int16_t>(parentId);
955
+ fragment.valid = fragment.width > 0 && fragment.height > 0;
956
+ }
957
+ }
958
+ #endif
348
959
 
349
960
  if (baseline + lineDescent > flowBottom) flowBottom = baseline + lineDescent;
350
961
  if (lineTop + lineCross > flowBottom) flowBottom = lineTop + lineCross;
351
962
 
352
963
  if (wrapIdx >= 0) {
353
964
  Node &run = nodes[children_[wrapIdx]];
354
- const int runBaseline = run.layout.y + childFirstBaseline(run);
965
+ const int runBaseline = run.layout.y + childBaseline(run);
355
966
  continuedBaseline = runBaseline + (wrapSpans - 1) * wrapAdvance;
356
- inheritedAscent = run.style.margin[0] + childFirstBaseline(run);
967
+ inheritedAscent = run.style.margin[0] + childBaseline(run);
357
968
  inheritedDescent = runLineDescent(run, wrapAdvance);
358
969
  penStart = run.style.margin[3] + wrapLastWidth + run.style.margin[1];
359
970
  continuing = true;
971
+ if (trailingWrappedStaticBoundary) {
972
+ std::vector<int> trailingStaticChildren;
973
+ captureStaticBoundary(childCount_, penStart, trailingStaticChildren, true);
974
+ for (int id : trailingStaticChildren) {
975
+ auto &position = ensureRareData(id).inlineStaticPosition;
976
+ position.y = clampInt16(continuedBaseline - inheritedAscent);
977
+ position.valid = true;
978
+ }
979
+ }
360
980
  if (continuedBaseline + inheritedDescent > flowBottom)
361
981
  flowBottom = continuedBaseline + inheritedDescent;
362
982
  if (penStart > maxLineWidth) maxLineWidth = penStart;
@@ -367,6 +987,15 @@ public:
367
987
  inheritedAscent = 0;
368
988
  inheritedDescent = 0;
369
989
  }
990
+ if (j >= childCount_ && endedWithBreak) {
991
+ std::vector<int> trailingStaticChildren;
992
+ captureStaticBoundary(childCount_, 0, trailingStaticChildren, true);
993
+ for (int id : trailingStaticChildren) {
994
+ auto &position = ensureRareData(id).inlineStaticPosition;
995
+ position.y = clampInt16(lineTop);
996
+ position.valid = true;
997
+ }
998
+ }
370
999
 
371
1000
  // A line box that took no item and inherited no run tail would spin. The
372
1001
  // scan only produces that for an item wider than the whole box, so place
@@ -375,21 +1004,32 @@ public:
375
1004
  if (j == i && !lineIsContinuation) j = i + 1;
376
1005
  i = j;
377
1006
  }
1007
+ if (childCount_ == 0 && !staticBoundaries.empty()) {
1008
+ std::vector<int> emptyStaticChildren;
1009
+ captureStaticBoundary(0, 0, emptyStaticChildren);
1010
+ for (int id : emptyStaticChildren) {
1011
+ auto &position = ensureRareData(id).inlineStaticPosition;
1012
+ position.y = clampInt16(contentTop);
1013
+ position.valid = true;
1014
+ }
1015
+ }
378
1016
 
379
- if (!autosize) return;
1017
+ const InlineFlowExtent extent{maxLineWidth, std::max(0, flowBottom - contentTop), firstLineHeight};
1018
+ if (!autosize) return extent;
380
1019
  // Same rules as autosizeParent: a scroll container keeps the size it was
381
1020
  // given on its scrolling axis so its overflow becomes scroll range.
382
1021
  const int flowHeight = flowBottom - contentTop;
383
1022
  const bool keepScrollHeight = scrollsOverflowY(node_.style) && node_.layout.height > 0;
384
- const bool keepScrollWidth = scrollsOverflowX(node_.style) && node_.layout.width > 0;
1023
+ const bool keepScrollWidth = !intrinsicWidthConstraint(node_) && scrollsOverflowX(node_.style) && node_.layout.width > 0;
385
1024
  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));
1025
+ const int height = (flowHeight < 0 ? 0 : flowHeight) + boxInset(node_.style, 0) + boxInset(node_.style, 2);
1026
+ node_.layout.height = clampInt16(clampLayoutSize(node_, height, false));
388
1027
  }
389
1028
  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));
1029
+ const int width = maxLineWidth + boxInset(node_.style, 1) + boxInset(node_.style, 3);
1030
+ node_.layout.width = clampInt16(clampLayoutSize(node_, width, true));
392
1031
  }
1032
+ return extent;
393
1033
  }
394
1034
 
395
1035
  // A text run whose line breaking this engine owns, and which therefore flows
@@ -397,7 +1037,7 @@ public:
397
1037
  // or nowrap run keeps its own box.
398
1038
  static bool isFragmentableRun(const Node &n)
399
1039
  {
400
- return n.type == NodeType::Text && !n.text.empty() && n.style.white_space != 1 &&
1040
+ return n.type == NodeType::Text && !n.text.empty() && n.style.white_space != 1 && n.style.white_space != 2 &&
401
1041
  n.style.width == kUnset && n.style.width_percent == kUnset;
402
1042
  }
403
1043
 
@@ -409,10 +1049,11 @@ public:
409
1049
  if (n.style.has_bg || n.style.border_width > 0 || hasSideBorder(n.style)) return false;
410
1050
  #if GEA_EMBEDDED_RARE_STYLE_INLINE
411
1051
  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 ||
1052
+ if (r.translate_present || r.transform_present || r.rotate_present || r.scale_present || r.filter_present ||
1053
+ r.transform_rotate || r.transform_rotate_x || r.transform_rotate_y ||
1054
+ composedTranslateX(r) || composedTranslateY(r) || composedTranslateZ(r) ||
1055
+ composedTranslateXPercent(r) || composedTranslateYPercent(r) ||
1056
+ r.transform_scale_x != 1000 || r.transform_scale_y != 1000 || r.transform_scale_z != 1000 || r.perspective ||
416
1057
  r.box_shadow_alpha || r.filter_blur_radius)
417
1058
  return false;
418
1059
  #else
@@ -428,25 +1069,25 @@ public:
428
1069
  // why `<p>… <span>score value</span> …</p>` may put "score" on one line and
429
1070
  // "value" on the next. Returns that inner run, or -1 when the wrapper has a box
430
1071
  // a reader could see, or holds anything other than one plain text run.
431
- int transparentInlineRun(const Node &wrapper) const
1072
+ static int transparentInlineRun(const Node &wrapper)
432
1073
  {
433
1074
  if (wrapper.type != NodeType::View) return -1;
434
1075
  if (!paintsNoBox(wrapper)) return -1;
435
- if (wrapper.style.padding[0] || wrapper.style.padding[1] || wrapper.style.padding[2] ||
436
- wrapper.style.padding[3])
1076
+ if (boxInset(wrapper.style, 0) || boxInset(wrapper.style, 1) || boxInset(wrapper.style, 2) ||
1077
+ boxInset(wrapper.style, 3))
437
1078
  return -1;
438
1079
  if (hasExplicitWidth(wrapper) || hasExplicitHeight(wrapper)) return -1;
439
1080
  if (wrapper.style.min_width > 0 || wrapper.style.min_height > 0) return -1;
440
1081
  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;
1082
+ if (overflowX(wrapper.style) || overflowY(wrapper.style)) return -1;
442
1083
  if (wrapper.style.align_self >= 0 || wrapper.style.flex > 0 ||
443
- wrapper.style.flex_basis != kUnset)
1084
+ hasFlexBasis(wrapper))
444
1085
  return -1;
445
1086
  const Node *nodes = Tree::instance().nodes();
446
1087
  int run = -1;
447
1088
  for (int c = wrapper.first_child; c >= 0; c = nodes[c].next_sibling) {
448
1089
  const Node &child = nodes[c];
449
- if (isDisplayNone(child.style) || child.style.position == 1) continue;
1090
+ if (isDisplayNone(child.style) || isOutOfFlowPosition(child.style.position)) continue;
450
1091
  if (run >= 0) return -1; // more than one in-flow child
451
1092
  if (child.type != NodeType::Text) return -1;
452
1093
  if (child.style.margin[0] || child.style.margin[1] || child.style.margin[2] ||
@@ -463,27 +1104,27 @@ public:
463
1104
  // actually carries — the others are flush, so this is the taller, safe value).
464
1105
  int runLineDescent(const Node &n, int lineAdvance) const
465
1106
  {
466
- const int ascender = childFirstBaseline(n) - n.style.padding[0];
467
- const int descent = lineAdvance - ascender + n.style.padding[2] + n.style.margin[2];
1107
+ const int ascender = childBaseline(n) - boxInset(n.style, 0);
1108
+ const int descent = lineAdvance - ascender + boxInset(n.style, 2) + n.style.margin[2];
468
1109
  return descent < 0 ? 0 : descent;
469
1110
  }
470
1111
 
471
1112
  void placeLineItems(Node *nodes, int from, int to, int contentLeft, int contentW, int lineTop,
472
1113
  int lineCross, int baseline, int penStart, bool ownsLineStart)
473
1114
  {
1115
+ const int contentEnd = to > from && isLineBreak(nodes[children_[to - 1]]) ? to - 1 : to;
474
1116
  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;
1117
+ ownsLineStart && (contentEnd - from) == 1 && nodes[children_[from]].type == NodeType::Text;
1118
+ // Inline layout establishes the text baseline even for a sole run.
1119
+ // Painting must not replace it with an ink-centred baseline depending
1120
+ // on whether the source happens to contain leading whitespace.
480
1121
  int pen = penStart;
481
1122
  for (int k = from; k < to; k++) {
482
1123
  const int child = children_[k];
483
1124
  Node &cn = nodes[child];
484
1125
  const int marginL = cn.style.margin[3];
485
1126
  const int marginR = cn.style.margin[1];
486
- const int gap = pen > 0 ? node_.style.gap : 0;
1127
+ const int gap = pen > 0 ? mainGap_ : 0;
487
1128
 
488
1129
  if (cn.layout.inline_indent > 0) {
489
1130
  // A wrapped continuation keeps a full-width box at the block's left
@@ -494,14 +1135,14 @@ public:
494
1135
  }
495
1136
  pen += gap + marginL + cn.layout.width + marginR;
496
1137
 
497
- if (soleRun && !hasExplicitWidth(cn)) {
1138
+ if (soleRun && cn.type == NodeType::Text && !hasExplicitWidth(cn)) {
498
1139
  // text-align needs a box as wide as the line box to align inside.
499
1140
  const int full = contentW - marginL - marginR;
500
1141
  if (full > cn.layout.width) cn.layout.width = clampInt16(full);
501
1142
  }
502
1143
 
503
- int y = baseline - childFirstBaseline(cn);
504
- const int align = crossAlignFor(cn);
1144
+ int y = baseline - childBaseline(cn);
1145
+ const int align = usedAlignment(crossAlignFor(cn), lineCross - cn.layout.height - cn.style.margin[0] - cn.style.margin[2]);
505
1146
  if (align != 5) {
506
1147
  const int crossBefore = cn.style.margin[0];
507
1148
  const int crossAfter = cn.style.margin[2];
@@ -509,18 +1150,18 @@ public:
509
1150
  y = lineTop + crossBefore;
510
1151
  if (align == 1) y += (lineCross - crossTotal) / 2;
511
1152
  else if (align == 2) y += lineCross - crossTotal;
512
- else if (align == 0 && !hasExplicitHeight(cn)) {
1153
+ else if (align == 0 && !hasExplicitHeight(cn) && !isIntrinsicSizeExpression(cn.style.height_expression)) {
513
1154
  cn.layout.height = clampInt16(lineCross - crossBefore - crossAfter);
514
1155
  engine_.repositionChildren(child);
515
1156
  }
516
1157
  }
517
1158
  cn.layout.y = clampInt16(y);
518
- cn.render.inline_baseline = sharesLine ? 1 : 0;
1159
+ cn.render.inline_baseline = 1;
519
1160
  // An inline wrapper (<span>text</span>) contributes its CHILD's glyphs to
520
1161
  // this line box, so the flag has to reach the node that actually draws.
521
1162
  if (cn.type == NodeType::View) {
522
1163
  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;
1164
+ if (nodes[c].type == NodeType::Text) nodes[c].render.inline_baseline = 1;
524
1165
  }
525
1166
  }
526
1167
  }
@@ -528,18 +1169,28 @@ public:
528
1169
  void expandCrossSizes(int lineCount, bool onlyIfDefinite)
529
1170
  {
530
1171
  const bool hasDefiniteCross = isRow_ ? hasExplicitHeight(node_) : hasExplicitWidth(node_);
531
- if (onlyIfDefinite && !hasDefiniteCross) return;
1172
+ const bool wrappingFlex = node_.style.display == kDisplayFlex && node_.style.flex_wrap;
1173
+ if (onlyIfDefinite && !hasDefiniteCross) {
1174
+ // A single flex line's intrinsic cross size still obeys the
1175
+ // container's min/max cross size (Flexbox 9.4, step 8).
1176
+ if (node_.style.display == kDisplayFlex && lineCount == 1 && !wrappingFlex) {
1177
+ const int insets = boxInsets(node_.style, !isRow_);
1178
+ lines_[0].crossSize = std::max(0, clampLayoutSize(node_, lines_[0].crossSize + insets, !isRow_) - insets);
1179
+ }
1180
+ return;
1181
+ }
532
1182
 
533
1183
  const int crossAvail = isRow_ ? padHeight_ : padWidth_;
534
- if (lineCount == 1) {
1184
+ if (lineCount == 1 && !wrappingFlex) {
535
1185
  lines_[0].crossSize = crossAvail;
536
- } else if (lineCount > 1) {
1186
+ } else if (lineCount > 0 && (!wrappingFlex || node_.style.align_content == 0)) {
537
1187
  int totalLineCross = 0;
538
1188
  for (int i = 0; i < lineCount; i++) totalLineCross += lines_[i].crossSize;
539
- const int extra = crossAvail - totalLineCross - (lineCount - 1) * node_.style.gap;
1189
+ const int extra = crossAvail - totalLineCross - (lineCount - 1) * crossGap_;
540
1190
  if (extra > 0) {
541
- const int perLine = extra / lineCount;
542
- for (int i = 0; i < lineCount; i++) lines_[i].crossSize += perLine;
1191
+ // Distribute the integer remainder cumulatively so no pixel is lost.
1192
+ for (int i = 0; i < lineCount; i++)
1193
+ lines_[i].crossSize += extra * (i + 1) / lineCount - extra * i / lineCount;
543
1194
  }
544
1195
  }
545
1196
  }
@@ -547,7 +1198,9 @@ public:
547
1198
  void positionLines(int lineCount)
548
1199
  {
549
1200
  Node *nodes = Tree::instance().nodes();
550
- int crossOffset = isRow_ ? node_.style.padding[0] : node_.style.padding[3];
1201
+ const bool wrappingFlex = node_.style.display == kDisplayFlex && node_.style.flex_wrap;
1202
+ const bool definiteCross = isRow_ ? hasExplicitHeight(node_) : hasExplicitWidth(node_);
1203
+ bool ratioCrossChanged = false;
551
1204
 
552
1205
  // Free main-axis space is measured against the node's FINAL padded main size
553
1206
  // (set by autosizeParent before this runs), NOT the available space it was
@@ -557,8 +1210,8 @@ public:
557
1210
  // box shrinks to fit. Reading layout.{width,height} also gives the correct
558
1211
  // free space when a flex item was GROWN past its content by its parent.
559
1212
  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]);
1213
+ ? (node_.layout.width - boxInset(node_.style, 1) - boxInset(node_.style, 3))
1214
+ : (node_.layout.height - boxInset(node_.style, 0) - boxInset(node_.style, 2));
562
1215
  const int mainContentBox = mainBox < 0 ? 0 : mainBox;
563
1216
 
564
1217
  for (int lineIndex = 0; lineIndex < lineCount; lineIndex++) {
@@ -601,13 +1254,72 @@ public:
601
1254
  if (mainSize == 0) engine_.repositionChildren(child);
602
1255
  }
603
1256
  }
604
- if (remaining < 0 && node_.style.justify_content != 1 && node_.style.justify_content != 2) remaining = 0;
1257
+ bool hasRatio = false;
1258
+ int measuredCross = 0;
1259
+ for (int i = 0; i < line.count; ++i) {
1260
+ const Node &child = nodes[children_[line.start + i]];
1261
+ hasRatio |= preferredRatio(child) > 0;
1262
+ measuredCross = std::max(measuredCross, isRow_ ? child.layout.height + child.style.margin[0] + child.style.margin[2]
1263
+ : child.layout.width + child.style.margin[1] + child.style.margin[3]);
1264
+ }
1265
+ if (node_.style.display == kDisplayFlex && hasRatio && !definiteCross) {
1266
+ line.crossSize = std::max(line.strutSize, baselineCrossSize(line.start, line.count, measuredCross));
1267
+ ratioCrossChanged = true;
1268
+ }
1269
+ }
1270
+ // Resolve all flexed sizes before cross-axis placement: a changed ratio
1271
+ // height affects following lines and reversed line order as well.
1272
+ if (ratioCrossChanged) {
1273
+ expandCrossSizes(lineCount, true);
1274
+ int16_t &cross = isRow_ ? node_.layout.height : node_.layout.width;
1275
+ cross = clampInt16(clampLayoutSize(node_, totalCrossSize(lineCount) + boxInsets(node_.style, !isRow_), !isRow_));
1276
+ }
1277
+ int crossOffset = boxInset(node_.style, isRow_ ? 0 : 3);
1278
+ const int crossBox = (isRow_ ? node_.layout.height : node_.layout.width) - boxInsets(node_.style, !isRow_);
1279
+ const int crossFree = crossBox - totalCrossSize(lineCount);
1280
+ for (int lineIndex = 0; lineIndex < lineCount; ++lineIndex) {
1281
+ FlexLine &line = lines_[lineIndex];
1282
+ int occupied = std::max(0, line.count - 1) * mainGap_;
1283
+ for (int i = 0; i < line.count; ++i) {
1284
+ const Node &child = nodes[children_[line.start + i]];
1285
+ occupied += isRow_ ? child.layout.width + child.style.margin[1] + child.style.margin[3]
1286
+ : child.layout.height + child.style.margin[0] + child.style.margin[2];
1287
+ }
1288
+ int remaining = mainContentBox - occupied;
1289
+ const int mainAlignment = usedAlignment(node_.style.justify_content, remaining, node_.style.flex_direction_explicit && node_.style.flex_direction >= 2);
1290
+ if (remaining < 0 && mainAlignment != 1 && mainAlignment != 2) remaining = 0;
1291
+
1292
+ int mainOffset = isRow_ ? boxInset(node_.style, 3) : boxInset(node_.style, 0);
1293
+ int autoCount = 0;
1294
+ for (int i = 0; i < line.count; ++i) {
1295
+ const auto mask = nodes[children_[line.start + i]].style.margin_auto;
1296
+ autoCount += isRow_ ? !!(mask & 2) + !!(mask & 8) : !!(mask & 1) + !!(mask & 4);
1297
+ }
1298
+ const int autoSpace = autoCount && remaining > 0 ? remaining : 0;
1299
+ if (!isDistributedAlignment(node_.style.justify_content))
1300
+ applyJustifyContent(autoSpace ? 0 : remaining, &mainOffset);
1301
+ const int lineOffset = wrappingFlex ? crossAlignmentOffset(lineIndex, lineCount, crossFree) : 0;
1302
+ positionLineChildren(line, nodes, mainOffset, crossOffset + lineOffset, autoSpace, autoCount, autoSpace ? 0 : remaining);
1303
+ crossOffset += line.crossSize + crossGap_;
1304
+ }
1305
+ }
605
1306
 
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;
1307
+ int crossAlignmentOffset(int index, int count, int free) const
1308
+ {
1309
+ #if GEA_CSS_FLEX_WRAP
1310
+ const bool wrapReversed = (node_.style.flex_wrap & 3) == 2;
1311
+ #else
1312
+ constexpr bool wrapReversed = false;
1313
+ #endif
1314
+ // A wrapping container is multi-line even when only one line is occupied.
1315
+ // Distributed alignments fall back to start/center for overflowing lines.
1316
+ switch (usedAlignment(node_.style.align_content, free, wrapReversed)) {
1317
+ case 1: return free / 2;
1318
+ case 2: return free;
1319
+ case 3:
1320
+ case 4:
1321
+ case kAlignSpaceEvenly: return distributedAlignmentOffset(node_.style.align_content, free, index, count);
1322
+ default: return 0;
611
1323
  }
612
1324
  }
613
1325
 
@@ -622,47 +1334,134 @@ public:
622
1334
  // fit content. Guarded on a positive assigned size so an unsized scroll
623
1335
  // container still autosizes as before.
624
1336
  const bool keepScrollHeight = scrollsOverflowY(node_.style) && node_.layout.height > 0;
625
- const bool keepScrollWidth = scrollsOverflowX(node_.style) && node_.layout.width > 0;
1337
+ const bool keepScrollWidth = !intrinsicWidthConstraint(node_) && scrollsOverflowX(node_.style) && node_.layout.width > 0;
626
1338
 
627
1339
  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);
1340
+ const int height = (isRow_ ? totalCrossSize(lineCount) : maxMainSize(lineCount)) + boxInset(node_.style, 0) + boxInset(node_.style, 2);
1341
+ node_.layout.height = clampLayoutSize(node_, height, false);
630
1342
  }
631
1343
 
632
1344
  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);
1345
+ const int width = (isRow_ ? maxMainSize(lineCount) : totalCrossSize(lineCount)) + boxInset(node_.style, 1) + boxInset(node_.style, 3);
1346
+ node_.layout.width = clampLayoutSize(node_, width, true);
635
1347
  }
636
1348
  }
637
1349
 
638
1350
  private:
639
- void applyFlexBasis(int child)
1351
+ int flexWrapLimit() const
640
1352
  {
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
- }
1353
+ const bool blockAxis = isRow_ == (writingMode(node_) != 0);
1354
+ if (!blockAxis || assignedSize_ || (isRow_ ? hasExplicitWidth(node_) : hasExplicitHeight(node_))) return mainAvail_;
1355
+ // An automatic block main size grows to fit its items. min-height is
1356
+ // a floor, not a wrapping constraint; only a maximum bounds packing.
1357
+ if ((isRow_ ? node_.style.max_width : node_.style.max_height) == kUnset) return INT_MAX;
1358
+ return std::max(0, clampLayoutSize(node_, INT16_MAX, isRow_) - boxInsets(node_.style, isRow_));
1359
+ }
1360
+
1361
+ int buildCollapsedLines(const std::vector<int> &struts)
1362
+ {
1363
+ Node *nodes = Tree::instance().nodes();
1364
+ std::vector<int> balancedEnds;
1365
+ if (node_.style.flex_wrap & 4) {
1366
+ std::vector<int> sizes;
1367
+ int total = 0;
1368
+ for (int i = 0; i < childCount_; ++i) {
1369
+ if (struts[i] >= 0) continue;
1370
+ const Node &child = nodes[children_[i]];
1371
+ const int size = isRow_ ? child.layout.width + child.style.margin[1] + child.style.margin[3]
1372
+ : child.layout.height + child.style.margin[0] + child.style.margin[2];
1373
+ total += std::max(0, size) + (sizes.empty() ? 0 : mainGap_);
1374
+ sizes.push_back(size);
1375
+ }
1376
+ const int available = std::min(total, flexWrapLimit());
1377
+ balancedEnds = balancedFlexLineEnds(sizes, available, mainGap_, (GEA_CSS_FLEX_LINE_COUNT ? rstyle(node_.style).flex_line_count : 1));
1378
+ }
1379
+ int lineCount = 0, start = 0, written = 0, main = 0, cross = 0, strut = 0;
1380
+ auto finish = [&] {
1381
+ appendLine(lineCount, start, written - start, main, std::max(cross, strut));
1382
+ lines_[lineCount - 1].strutSize = strut;
1383
+ start = written; main = cross = strut = 0;
1384
+ };
1385
+ for (int i = 0; i < childCount_; ++i) {
1386
+ const int id = children_[i];
1387
+ Node &child = nodes[id];
1388
+ if (struts[i] >= 0) {
1389
+ strut = std::max(strut, struts[i]);
1390
+ // The strut belongs to the line, not to a rendered child box.
1391
+ child.layout.x = child.layout.y = child.layout.width = child.layout.height = 0;
1392
+ continue;
1393
+ }
1394
+ const int childMain = isRow_ ? child.layout.width + child.style.margin[1] + child.style.margin[3]
1395
+ : child.layout.height + child.style.margin[0] + child.style.margin[2];
1396
+ const int childCross = isRow_ ? child.layout.height + child.style.margin[0] + child.style.margin[2]
1397
+ : child.layout.width + child.style.margin[1] + child.style.margin[3];
1398
+ const bool wrap = !balancedEnds.empty() ? written == balancedEnds[lineCount]
1399
+ : node_.style.flex_wrap && main + mainGap_ + childMain > flexWrapLimit();
1400
+ if (written > start && wrap) finish();
1401
+ main += childMain + (written > start ? mainGap_ : 0);
1402
+ cross = std::max(cross, childCross);
1403
+ children_[written++] = id;
1404
+ }
1405
+ finish();
1406
+ childCount_ = written;
1407
+ return lineCount;
1408
+ }
1409
+
1410
+ int buildBalancedLines()
1411
+ {
1412
+ Node *nodes = Tree::instance().nodes();
1413
+ std::vector<int> sizes(childCount_);
1414
+ int total = 0;
1415
+ for (int i = 0; i < childCount_; ++i) {
1416
+ const Node &child = nodes[children_[i]];
1417
+ sizes[i] = isRow_ ? child.layout.width + child.style.margin[1] + child.style.margin[3]
1418
+ : child.layout.height + child.style.margin[0] + child.style.margin[2];
1419
+ total += std::max(0, sizes[i]) + (i ? mainGap_ : 0);
1420
+ }
1421
+ // An unconstrained automatic block main size is content-based; the
1422
+ // viewport height must not manufacture additional columns.
1423
+ const int available = std::min(total, flexWrapLimit());
1424
+ const auto ends = balancedFlexLineEnds(sizes, available, mainGap_, (GEA_CSS_FLEX_LINE_COUNT ? rstyle(node_.style).flex_line_count : 1));
1425
+ int start = 0, count = 0;
1426
+ for (const int end : ends) {
1427
+ int main = 0, cross = 0;
1428
+ for (int i = start; i < end; ++i) {
1429
+ const Node &child = nodes[children_[i]];
1430
+ main += sizes[i] + (i > start ? mainGap_ : 0);
1431
+ cross = std::max(cross, isRow_ ? child.layout.height + child.style.margin[0] + child.style.margin[2]
1432
+ : child.layout.width + child.style.margin[1] + child.style.margin[3]);
1433
+ }
1434
+ appendLine(count, start, end - start, main, cross);
1435
+ start = end;
1436
+ }
1437
+ return count;
1438
+ }
1439
+
1440
+ int flexPercentageBasis() const
1441
+ {
1442
+ if (isRow_ ? hasExplicitWidth(node_) : hasExplicitHeight(node_)) return mainAvail_;
1443
+ // A normal block's automatic inline size fills its containing block.
1444
+ // Intrinsic measurements and automatic block sizes remain indefinite.
1445
+ if (isRow_ && !intrinsicWidthConstraint(node_) && !node_.style.float_side &&
1446
+ !isIntrinsicSizeExpression(node_.style.width_expression) &&
1447
+ (node_.parent < 0 || Tree::instance().nodes()[node_.parent].style.display != kDisplayFlex)) return mainAvail_;
1448
+ if (assignedSize_ && node_.parent >= 0) {
1449
+ const Node &parent = Tree::instance().nodes()[node_.parent];
1450
+ if (parent.style.display == kDisplayFlex) {
1451
+ const bool parentRow = flexRowDirection(parent.style) != (writingMode(parent) != 0);
1452
+ if (isRow_ != parentRow ? definiteFlexCrossSize(parent, node_, parentRow)
1453
+ : (isRow_ ? hasExplicitWidth(parent) : hasExplicitHeight(parent))) return mainAvail_;
663
1454
  }
664
- return;
665
1455
  }
1456
+ return -1;
1457
+ }
1458
+
1459
+ void applyFlexBasis(int child)
1460
+ {
1461
+ Node &childNode = Tree::instance().nodes()[child];
1462
+ // Authored bases were measured on the physical main axis above. Preserve
1463
+ // that result, including content sizing for an indefinite percentage.
1464
+ if (hasFlexBasis(childNode)) return;
666
1465
  if (childNode.style.flex <= 0) return;
667
1466
  if (isRow_) {
668
1467
  if (hasExplicitWidth(childNode)) return;
@@ -681,18 +1480,39 @@ private:
681
1480
  // (free space exactly 0) is compensated in positionLines.
682
1481
  }
683
1482
 
1483
+ int baselineCrossSize(int start, int count, int crossSize) const
1484
+ {
1485
+ if (isRow_ && node_.style.display == kDisplayFlex) {
1486
+ for (int alignment : {5, kAlignLastBaseline}) {
1487
+ int ascent = 0, descent = 0;
1488
+ for (int i = start; i < start + count; ++i) {
1489
+ const Node &child = Tree::instance().nodes()[children_[i]];
1490
+ if (crossAlignFor(child) != alignment || (child.style.margin_auto & 5)) continue;
1491
+ const int baseline = childBaseline(child, alignment == kAlignLastBaseline);
1492
+ ascent = std::max(ascent, child.style.margin[0] + baseline);
1493
+ descent = std::max(descent, child.style.margin[2] + child.layout.height - baseline);
1494
+ }
1495
+ crossSize = std::max(crossSize, ascent + descent);
1496
+ }
1497
+ }
1498
+ return crossSize;
1499
+ }
1500
+
684
1501
  void appendLine(int &lineCount, int start, int count, int mainSize, int crossSize)
685
1502
  {
686
- if (lineCount >= kMaxFlexLines) return;
1503
+ if (lineCount >= (extraLines_.empty() ? kMaxFlexLines : static_cast<int>(extraLines_.size()))) return;
1504
+ crossSize = baselineCrossSize(start, count, crossSize);
687
1505
  lines_[lineCount].start = start;
688
1506
  lines_[lineCount].count = count;
689
1507
  lines_[lineCount].mainSize = mainSize;
690
1508
  lines_[lineCount].crossSize = crossSize;
1509
+ lines_[lineCount].strutSize = 0;
691
1510
  lineCount++;
692
1511
  }
693
1512
 
694
1513
  int totalFlexGrowForLine(const FlexLine &line, Node *nodes) const
695
1514
  {
1515
+ if (node_.style.display != kDisplayFlex) return 0;
696
1516
  int totalFlex = 0;
697
1517
  for (int i = 0; i < line.count; i++) {
698
1518
  totalFlex += nodes[children_[line.start + i]].style.flex;
@@ -713,6 +1533,7 @@ private:
713
1533
  // deficit redistributes to shrinkable siblings or becomes overflow.
714
1534
  bool childMainSizeIsShrinkable(const Node &childNode) const
715
1535
  {
1536
+ if (node_.style.display != kDisplayFlex) return false;
716
1537
  if (childNode.style.flex_shrink <= 0) return false;
717
1538
  if (!isRow_ && childNode.type == NodeType::Text) return false;
718
1539
  return true;
@@ -792,14 +1613,13 @@ private:
792
1613
  int automaticMinimumMainSize(const Node &childNode) const
793
1614
  {
794
1615
  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;
1616
+ if (explicitMin != kUnset) return 0;
1617
+ if (isScrollableOverflow(isRow_ ? overflowX(childNode.style) : overflowY(childNode.style))) return 0;
798
1618
  const Node *nodes = Tree::instance().nodes();
799
1619
  int extent = 0;
800
1620
  for (int c = childNode.first_child; c >= 0; c = nodes[c].next_sibling) {
801
1621
  const Node &grand = nodes[c];
802
- if (isDisplayNone(grand.style) || grand.style.position == 1) continue;
1622
+ if (isDisplayNone(grand.style) || isOutOfFlowPosition(grand.style.position)) continue;
803
1623
  // layout.{x,y} are still parent-relative here: resolveAbsoluteCoords runs
804
1624
  // after the whole layout pass.
805
1625
  const int end = isRow_
@@ -807,8 +1627,19 @@ private:
807
1627
  : grand.layout.y + grand.layout.height + grand.style.margin[2];
808
1628
  if (end > extent) extent = end;
809
1629
  }
1630
+ if (extent > 0) extent += isRow_ ? boxInset(childNode.style, 1) : boxInset(childNode.style, 2);
1631
+ if (preferredRatio(childNode) > 0 &&
1632
+ ((isRow_ ? hasExplicitHeight(childNode) : hasExplicitWidth(childNode)) || definiteFlexCrossSize(node_, childNode, isRow_))) {
1633
+ const int transferred = ratioTransferredSize(childNode, isRow_ ? childNode.layout.height : childNode.layout.width, isRow_);
1634
+ extent = childNode.type == NodeType::Image ? std::min(extent, transferred) : std::max(extent, transferred);
1635
+ }
810
1636
  if (extent <= 0) return 0;
811
- extent += isRow_ ? childNode.style.padding[1] : childNode.style.padding[2];
1637
+ const int max = isRow_ ? childNode.style.max_width : childNode.style.max_height;
1638
+ if (max != kUnset) extent = std::min(extent, contentSizeToBorderSize(childNode.style, max, isRow_));
1639
+ if (isRow_ ? hasExplicitWidth(childNode) : hasExplicitHeight(childNode)) {
1640
+ const int specified = isRow_ ? resolvedStyleWidth(childNode, mainAvail_) : resolvedStyleHeight(childNode, mainAvail_);
1641
+ extent = std::min(extent, contentSizeToBorderSize(childNode.style, specified, isRow_));
1642
+ }
812
1643
  return extent;
813
1644
  }
814
1645
 
@@ -828,21 +1659,23 @@ private:
828
1659
  if (after == before) return 0;
829
1660
  if (isRow_) childNode.layout.width = after;
830
1661
  else childNode.layout.height = after;
1662
+ if (preferredRatio(childNode) > 0 && !(isRow_ ? hasExplicitHeight(childNode) : hasExplicitWidth(childNode)) &&
1663
+ !definiteFlexCrossSize(node_, childNode, isRow_)) {
1664
+ int16_t &cross = isRow_ ? childNode.layout.height : childNode.layout.width;
1665
+ cross = clampInt16(clampLayoutSize(childNode, ratioTransferredSize(childNode, after, !isRow_), !isRow_));
1666
+ }
831
1667
  engine_.repositionChildren(child);
832
1668
  return delta > 0 ? after - before : before - after;
833
1669
  }
834
1670
 
835
1671
  int clampFlexMainSize(const Node &childNode, int size) const
836
1672
  {
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;
1673
+ return clampBorderSize(engine_, childNode, size, isRow_);
841
1674
  }
842
1675
 
843
- void applyJustifyContent(const FlexLine &line, int remaining, int *mainOffset, int *gapSpace) const
1676
+ void applyJustifyContent(int remaining, int *mainOffset) const
844
1677
  {
845
- switch (node_.style.justify_content) {
1678
+ switch (usedAlignment(node_.style.justify_content, remaining, node_.style.flex_direction_explicit && node_.style.flex_direction >= 2)) {
846
1679
  case 0:
847
1680
  break;
848
1681
  case 1:
@@ -851,31 +1684,50 @@ private:
851
1684
  case 2:
852
1685
  *mainOffset += remaining;
853
1686
  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
1687
  }
865
1688
  }
866
1689
 
867
- void positionLineChildren(const FlexLine &line, Node *nodes, int mainOffset, int crossOffset, int gapSpace)
1690
+ void positionLineChildren(const FlexLine &line, Node *nodes, int mainOffset, int crossOffset, int autoSpace = 0, int autoCount = 0, int distributedFree = 0)
868
1691
  {
1692
+ #if GEA_CSS_FLEX_WRAP
1693
+ const bool wrapReversed = (node_.style.flex_wrap & 3) == 2;
1694
+ #else
1695
+ constexpr bool wrapReversed = false;
1696
+ #endif
1697
+ const bool flex = node_.style.display == kDisplayFlex;
1698
+ const bool logicalRow = flexRowDirection(node_.style);
1699
+ const int mode = writingMode(node_);
1700
+ const bool blockReversed = mode == 2 || mode == 3;
1701
+ const bool inlineReversed = rightToLeft(node_) != (mode == 4);
1702
+ const bool reverseMain = flex && ((node_.style.flex_direction_explicit && node_.style.flex_direction >= 2) != (logicalRow ? inlineReversed : blockReversed));
1703
+ const bool reverseCross = flex && ((wrapReversed) != (logicalRow ? blockReversed : inlineReversed));
1704
+ const int mainBefore = isRow_ ? (reverseMain ? 1 : 3) : (reverseMain ? 2 : 0);
1705
+ const int mainAfter = (mainBefore + 2) % 4;
1706
+ const int crossBefore = isRow_ ? (reverseCross ? 2 : 0) : (reverseCross ? 1 : 3);
1707
+ const int crossAfter = (crossBefore + 2) % 4;
1708
+ int autoUsed = 0;
1709
+ auto autoMargin = [&](const Node &child, int side) {
1710
+ if (!(child.style.margin_auto & (1 << side)) || !autoCount) return 0;
1711
+ const int before = autoSpace * autoUsed / autoCount;
1712
+ return autoSpace * ++autoUsed / autoCount - before;
1713
+ };
869
1714
  // First baselines of this line's baseline-aligned children (rows only):
870
1715
  // every such child's baseline lands on the line's max baseline, matching
871
1716
  // CSS `align-items: baseline` (a 12px range label shares the 14px
872
1717
  // condition's baseline instead of top-aligning).
873
1718
  int lineMaxBaseline = 0;
1719
+ int lineMaxLastDescent = 0, lineMaxLastAscent = 0;
874
1720
  if (isRow_) {
875
1721
  for (int i = 0; i < line.count; i++) {
876
1722
  Node &probe = nodes[children_[line.start + i]];
1723
+ if (probe.style.margin_auto & 5) continue;
1724
+ if (crossAlignFor(probe) == kAlignLastBaseline) {
1725
+ const int baseline = childBaseline(probe, true);
1726
+ lineMaxLastDescent = std::max(lineMaxLastDescent, probe.style.margin[2] + probe.layout.height - baseline);
1727
+ lineMaxLastAscent = std::max(lineMaxLastAscent, probe.style.margin[0] + baseline);
1728
+ }
877
1729
  if (crossAlignFor(probe) != 5) continue;
878
- const int baseline = probe.style.margin[0] + childFirstBaseline(probe);
1730
+ const int baseline = probe.style.margin[0] + childBaseline(probe);
879
1731
  if (baseline > lineMaxBaseline) lineMaxBaseline = baseline;
880
1732
  }
881
1733
  }
@@ -884,27 +1736,44 @@ private:
884
1736
  const int child = children_[line.start + i];
885
1737
  Node &childNode = nodes[child];
886
1738
 
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];
1739
+ const int mainMarginBefore = childNode.style.margin[mainBefore] + autoMargin(childNode, mainBefore);
1740
+ const int mainMarginAfter = childNode.style.margin[mainAfter] + autoMargin(childNode, mainAfter);
1741
+ const int crossMarginBefore = childNode.style.margin[crossBefore];
1742
+ const int crossMarginAfter = childNode.style.margin[crossAfter];
891
1743
  const int crossSize = isRow_ ? childNode.layout.height : childNode.layout.width;
892
1744
  const int crossTotal = crossSize + crossMarginBefore + crossMarginAfter;
893
1745
 
894
1746
  mainOffset += mainMarginBefore;
895
1747
  int crossPosition = crossOffset + crossMarginBefore;
896
- positionCrossAxisChild(child, childNode, line.crossSize, crossMarginBefore, crossMarginAfter, crossTotal, &crossPosition, lineMaxBaseline);
1748
+ const bool crossAutoBefore = childNode.style.margin_auto & (1 << crossBefore);
1749
+ const bool crossAutoAfter = childNode.style.margin_auto & (1 << crossAfter);
1750
+ if (crossAutoBefore || crossAutoAfter) {
1751
+ const int free = std::max(0, line.crossSize - crossTotal);
1752
+ if (crossAutoBefore) crossPosition += crossAutoAfter ? free / 2 : free;
1753
+ } else {
1754
+ positionCrossAxisChild(child, childNode, line.crossSize, crossMarginBefore, crossMarginAfter, crossTotal, &crossPosition, lineMaxBaseline, std::max(lineMaxLastAscent, line.crossSize - lineMaxLastDescent));
1755
+ // Baselines are distances from physical top. Reversing the line
1756
+ // order must not mirror each item's baseline inside that line.
1757
+ const int alignment = crossAlignFor(childNode) & 15;
1758
+ if (isRow_ && reverseCross && (alignment == 5 || alignment == kAlignLastBaseline))
1759
+ crossPosition = crossOffset + line.crossSize - (crossPosition - crossOffset) - crossSize;
1760
+ }
897
1761
 
898
1762
  if (isRow_) {
899
- childNode.layout.x = mainOffset;
1763
+ childNode.layout.x = mainOffset + distributedAlignmentOffset(node_.style.justify_content, distributedFree, i, line.count);
900
1764
  childNode.layout.y = crossPosition;
901
1765
  } else {
902
1766
  childNode.layout.x = crossPosition;
903
- childNode.layout.y = mainOffset;
1767
+ childNode.layout.y = mainOffset + distributedAlignmentOffset(node_.style.justify_content, distributedFree, i, line.count);
904
1768
  }
905
1769
 
1770
+ const bool reverseX = isRow_ ? reverseMain : reverseCross;
1771
+ const bool reverseY = isRow_ ? reverseCross : reverseMain;
1772
+ if (reverseX) childNode.layout.x = node_.layout.width - childNode.layout.x - childNode.layout.width + boxInset(node_.style, 3) - boxInset(node_.style, 1);
1773
+ if (reverseY) childNode.layout.y = node_.layout.height - childNode.layout.y - childNode.layout.height + boxInset(node_.style, 0) - boxInset(node_.style, 2);
1774
+
906
1775
  const int mainSize = isRow_ ? childNode.layout.width : childNode.layout.height;
907
- mainOffset += mainSize + mainMarginAfter + node_.style.gap + gapSpace;
1776
+ mainOffset += mainSize + mainMarginAfter + mainGap_;
908
1777
  // Flex items own their boxes; nothing here shares a line box.
909
1778
  childNode.render.inline_baseline = 0;
910
1779
  }
@@ -921,17 +1790,27 @@ private:
921
1790
  return inlineRow_ ? 5 : node_.style.align_items;
922
1791
  }
923
1792
 
924
- void positionCrossAxisChild(int child, Node &childNode, int lineCrossSize, int crossMarginBefore, int crossMarginAfter, int crossTotal, int *crossPosition, int lineMaxBaseline)
1793
+ void positionCrossAxisChild(int child, Node &childNode, int lineCrossSize, int crossMarginBefore, int crossMarginAfter, int crossTotal, int *crossPosition, int lineMaxBaseline, int lineLastBaseline)
925
1794
  {
926
- const int align = crossAlignFor(childNode);
1795
+ #if GEA_CSS_FLEX_WRAP
1796
+ const bool wrapReversed = (node_.style.flex_wrap & 3) == 2;
1797
+ #else
1798
+ constexpr bool wrapReversed = false;
1799
+ #endif
1800
+ const int alignment = crossAlignFor(childNode);
1801
+ int align = physicalSelfAlignment(node_, childNode, alignment, lineCrossSize - crossTotal, !isRow_);
1802
+ if (align >= 0) {
1803
+ const bool reversed = gridAxisReversed(node_, !isRow_) != (wrapReversed);
1804
+ if (reversed) align = align == 2 ? 6 : 2;
1805
+ } else align = usedAlignment(alignment, lineCrossSize - crossTotal, wrapReversed);
927
1806
  switch (align) {
928
1807
  case 0:
929
1808
  if (isRow_) {
930
- if (!hasExplicitHeight(childNode)) {
1809
+ if (!hasExplicitHeight(childNode) && !isIntrinsicSizeExpression(childNode.style.height_expression)) {
931
1810
  childNode.layout.height = lineCrossSize - crossMarginBefore - crossMarginAfter;
932
1811
  engine_.repositionChildren(child);
933
1812
  }
934
- } else if (!hasExplicitWidth(childNode)) {
1813
+ } else if (!hasExplicitWidth(childNode) && !isIntrinsicSizeExpression(childNode.style.width_expression)) {
935
1814
  childNode.layout.width = lineCrossSize - crossMarginBefore - crossMarginAfter;
936
1815
  engine_.repositionChildren(child);
937
1816
  }
@@ -942,45 +1821,33 @@ private:
942
1821
  case 2:
943
1822
  *crossPosition += lineCrossSize - crossTotal;
944
1823
  break;
1824
+ case kAlignLastBaseline:
1825
+ if (isRow_) {
1826
+ *crossPosition += lineLastBaseline - childBaseline(childNode, true) - crossMarginBefore;
1827
+ } else if (lineCrossSize >= crossTotal) {
1828
+ *crossPosition += lineCrossSize - crossTotal;
1829
+ }
1830
+ break;
945
1831
  case 5:
946
1832
  // align-items/align-self: baseline (rows). Columns fall back to start,
947
1833
  // matching CSS, where baseline alignment only applies across an inline axis.
948
1834
  if (isRow_) {
949
- const int shift = lineMaxBaseline - (crossMarginBefore + childFirstBaseline(childNode));
1835
+ const int shift = lineMaxBaseline - (crossMarginBefore + childBaseline(childNode));
950
1836
  if (shift > 0) *crossPosition += shift;
951
1837
  }
952
1838
  break;
953
1839
  }
954
1840
  }
955
1841
 
956
- // First-baseline of a flex child, measured from its border-box top. Text
1842
+ // First/last baseline of a flex child, measured from its border-box top. Text
957
1843
  // leaves use the resolved atlas font's ascender — the glyph rasterizer
958
1844
  // 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
- }
1845
+ // pixels exactly. Flex items synthesize missing baselines from border edges;
1846
+ // inline boxes use margin edges.
1847
+ int childBaseline(const Node &childNode, bool last = false) const
1848
+ {
1849
+ if ((childNode.type == NodeType::Text || isLineBreak(childNode)) && childNode.style.font_id >= 0)
1850
+ return TextRenderer::baselineOffset(childNode, last);
984
1851
  // An inline wrapper (a <span> around text) carries no text of its own, so
985
1852
  // CSS takes the baseline of its FIRST in-flow line box. Its children were
986
1853
  // already positioned by measureChildren, and layout.y is still parent-
@@ -990,19 +1857,19 @@ private:
990
1857
  // dropped below every bare text run beside it.
991
1858
  if (childNode.type == NodeType::View && childNode.first_child >= 0) {
992
1859
  const Node *nodes = Tree::instance().nodes();
993
- for (int c = childNode.first_child; c >= 0; c = nodes[c].next_sibling) {
1860
+ for (int c = last ? childNode.last_child : childNode.first_child; c >= 0; c = last ? nodes[c].prev_sibling : nodes[c].next_sibling) {
994
1861
  const Node &inner = nodes[c];
995
- if (isDisplayNone(inner.style) || inner.style.position == 1) continue;
996
- return inner.layout.y + childFirstBaseline(inner);
1862
+ if (isDisplayNone(inner.style) || isOutOfFlowPosition(inner.style.position)) continue;
1863
+ return inner.layout.y + childBaseline(inner, last);
997
1864
  }
998
1865
  }
999
- return childNode.layout.height + childNode.style.margin[2];
1866
+ return childNode.layout.height + (inlineRow_ ? childNode.style.margin[2] : 0);
1000
1867
  }
1001
1868
 
1002
1869
  int totalCrossSize(int lineCount) const
1003
1870
  {
1004
1871
  int total = 0;
1005
- for (int i = 0; i < lineCount; i++) total += lines_[i].crossSize + (i > 0 ? node_.style.gap : 0);
1872
+ for (int i = 0; i < lineCount; i++) total += lines_[i].crossSize + (i > 0 ? crossGap_ : 0);
1006
1873
  return total;
1007
1874
  }
1008
1875
 
@@ -1023,10 +1890,14 @@ private:
1023
1890
  // True when this row is a synthesized INLINE FORMATTING context (a block
1024
1891
  // whose in-flow children are all inline-level), not a declared flex row.
1025
1892
  bool inlineRow_ = false;
1893
+ bool assignedSize_ = false;
1026
1894
  int mainAvail_ = 0;
1027
1895
  int padWidth_ = 0;
1028
1896
  int padHeight_ = 0;
1029
1897
  FlexLine *lines_ = nullptr;
1898
+ std::vector<FlexLine> extraLines_;
1899
+ int mainGap_ = 0;
1900
+ int crossGap_ = 0;
1030
1901
  };
1031
1902
 
1032
1903
  // CSS inline-level classification. Browsers flow inline-level boxes (text,
@@ -1037,13 +1908,58 @@ private:
1037
1908
  // display:flex/grid is its own formatting context, not inline.
1038
1909
  static bool isInlineLevelTag(const char *tag)
1039
1910
  {
1040
- return std::strcmp(tag, "span") == 0 || std::strcmp(tag, "a") == 0 || std::strcmp(tag, "b") == 0 ||
1911
+ return std::strcmp(tag, "br") == 0 || std::strcmp(tag, "span") == 0 || std::strcmp(tag, "a") == 0 || std::strcmp(tag, "b") == 0 ||
1041
1912
  std::strcmp(tag, "i") == 0 || std::strcmp(tag, "em") == 0 || std::strcmp(tag, "strong") == 0 ||
1042
1913
  std::strcmp(tag, "small") == 0 || std::strcmp(tag, "label") == 0 || std::strcmp(tag, "code") == 0 ||
1043
1914
  std::strcmp(tag, "u") == 0 || std::strcmp(tag, "sub") == 0 || std::strcmp(tag, "sup") == 0 ||
1044
1915
  std::strcmp(tag, "mark") == 0;
1045
1916
  }
1046
1917
 
1918
+ // Box-tree projection for inline ancestors split by in-flow blocks. The DOM
1919
+ // ancestry still owns inheritance, events, relative translation, and painting.
1920
+ // Visible inline decorations require fragments; keep those on their own path.
1921
+ bool splitInlineWrapper(const Node *nodes, int id)
1922
+ {
1923
+ const Node &n = nodes[id];
1924
+ if (n.type != NodeType::View || n.style.display_explicit || n.style.display != kDisplayBlock ||
1925
+ !isInlineLevelTag(tagFromId(n.tag_id)) || n.style.float_side || isOutOfFlowPosition(n.style.position) ||
1926
+ !FlexLayoutPass::paintsNoBox(n) || boxInsets(n.style, true) || boxInsets(n.style, false) ||
1927
+ n.style.margin[1] || n.style.margin[3] || n.style.opacity != 255 || overflowEstablishesContext(n.style)) return false;
1928
+ bool containsBlock = false;
1929
+ for (int c = n.first_child; c >= 0; c = nodes[c].next_sibling) {
1930
+ const Node &child = nodes[c];
1931
+ if (isDisplayNone(child.style)) continue;
1932
+ if (isOutOfFlowPosition(child.style.position)) return false;
1933
+ if (child.style.float_side) continue;
1934
+ if (child.type == NodeType::View && (child.style.display_explicit || !isInlineLevelTag(tagFromId(child.tag_id)))) containsBlock = true;
1935
+ if (splitInlineWrapper(nodes, c)) containsBlock = true;
1936
+ }
1937
+ return containsBlock;
1938
+ }
1939
+
1940
+ int formattingEdgeNode(const Node *nodes, int id, bool last)
1941
+ {
1942
+ if (!splitInlineWrapper(nodes, id)) return id;
1943
+ for (int c = last ? nodes[id].last_child : nodes[id].first_child; c >= 0; c = last ? nodes[c].prev_sibling : nodes[c].next_sibling) {
1944
+ const Node &child = nodes[c];
1945
+ if (isDisplayNone(child.style) || isOutOfFlowPosition(child.style.position) || child.style.float_side) continue;
1946
+ if (isAnonymousTextNode(child) && (child.style.white_space == 0 || child.style.white_space == 1) &&
1947
+ child.text.find_first_not_of(" \t\r\n\f") == std::string::npos) continue;
1948
+ return formattingEdgeNode(nodes, c, last);
1949
+ }
1950
+ return -1;
1951
+ }
1952
+
1953
+ template<class Visit>
1954
+ void visitFormattingChildren(const Node *nodes, int parent, const Visit &visit, bool reverse = false)
1955
+ {
1956
+ const bool project = nodes[parent].style.display == kDisplayBlock && !nodes[parent].style.flex_direction_explicit;
1957
+ for (int c = reverse ? nodes[parent].last_child : nodes[parent].first_child; c >= 0; c = reverse ? nodes[c].prev_sibling : nodes[c].next_sibling) {
1958
+ if (project && splitInlineWrapper(nodes, c)) visitFormattingChildren(nodes, c, visit, reverse);
1959
+ else visit(c);
1960
+ }
1961
+ }
1962
+
1047
1963
  class LayoutNodePass {
1048
1964
  public:
1049
1965
  LayoutNodePass(LayoutEngine &engine, int id, int availWidth, int availHeight)
@@ -1053,9 +1969,21 @@ public:
1053
1969
 
1054
1970
  void run()
1055
1971
  {
1972
+ invalidateInlineChildMetadata();
1973
+ #if GEA_CSS_FIRST_LINE
1974
+ if (NodeRareData *rare = rareDataFor(id_)) rare->firstLineBackground.lineValid = false;
1975
+ #endif
1056
1976
  if (isDisplayNone(node_.style)) return;
1057
1977
  prepareOwnSize();
1058
1978
 
1979
+ if (isLineBreak(node_) && LayoutEngine::isInlineLevelNode(node_) &&
1980
+ (node_.parent < 0 || (nodes_[node_.parent].style.display != kDisplayFlex && !isDisplayGrid(nodes_[node_.parent].style)))) {
1981
+ node_.layout.width = 0;
1982
+ node_.layout.height = clampInt16(TextRenderer::measureHeight(" ", node_.style.font_id,
1983
+ node_.style.font_size, 0, node_.style.line_height));
1984
+ return;
1985
+ }
1986
+
1059
1987
  if (node_.type == NodeType::Text) {
1060
1988
  const std::int64_t __tmT0 = refreshPerfNowUs();
1061
1989
  TextRenderer::layout(id_, availWidth_);
@@ -1082,8 +2010,8 @@ public:
1082
2010
  ScratchFrame scratch;
1083
2011
  if (!scratch.valid()) return;
1084
2012
 
1085
- const int childCount = engine_.collectChildren(id_, scratch.children(), kMaxChildren, true);
1086
- if (childCount == 0) {
2013
+ const int childCount = collectFormattingChildren(scratch.children(), kMaxChildren);
2014
+ if (childCount == 0 && !isDisplayGrid(node_.style)) {
1087
2015
  autosizeEmptyNode();
1088
2016
  positionAbsoluteChildren();
1089
2017
  applyRelativeOffsets();
@@ -1100,6 +2028,22 @@ public:
1100
2028
  return;
1101
2029
  }
1102
2030
 
2031
+ if (layoutFloatChildren(scratch.children(), childCount, padWidth, padHeight, true)) {
2032
+ encloseFloatDescendants();
2033
+ updateScrollContentSize();
2034
+ positionAbsoluteChildren();
2035
+ applyRelativeOffsets();
2036
+ return;
2037
+ }
2038
+ if (layoutBlockChildren(scratch.children(), childCount, padWidth, padHeight, true)) {
2039
+ encloseFloatDescendants();
2040
+ updateScrollContentSize();
2041
+ positionAbsoluteChildren();
2042
+ applyRelativeOffsets();
2043
+ applyVirtualListContentHeight();
2044
+ return;
2045
+ }
2046
+
1103
2047
  FlexLayoutPass flex(engine_, node_, scratch.children(), childCount, isRow, mainAvail, padWidth, padHeight, scratch.lines(), inlineRow);
1104
2048
  flex.measureChildren();
1105
2049
  if (inlineRow) {
@@ -1107,15 +2051,9 @@ public:
1107
2051
  // FlexLayoutPass::layoutInlineFlow.
1108
2052
  flex.layoutInlineFlow(true);
1109
2053
  } 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);
2054
+ flex.layoutLines(true);
1118
2055
  }
2056
+ encloseFloatDescendants();
1119
2057
  updateScrollContentSize();
1120
2058
  positionAbsoluteChildren();
1121
2059
  applyRelativeOffsets();
@@ -1125,6 +2063,10 @@ public:
1125
2063
  void repositionChildren()
1126
2064
  {
1127
2065
  if (node_.type == NodeType::Text || node_.type == NodeType::Image) return;
2066
+ invalidateInlineChildMetadata();
2067
+ #if GEA_CSS_FIRST_LINE
2068
+ if (NodeRareData *rare = rareDataFor(id_)) rare->firstLineBackground.lineValid = false;
2069
+ #endif
1128
2070
 
1129
2071
  const int padWidth = paddedWidth();
1130
2072
  const int padHeight = paddedHeight();
@@ -1135,8 +2077,8 @@ public:
1135
2077
  ScratchFrame scratch;
1136
2078
  if (!scratch.valid()) return;
1137
2079
 
1138
- const int childCount = engine_.collectChildren(id_, scratch.children(), kMaxChildren, true);
1139
- if (childCount == 0) {
2080
+ const int childCount = collectFormattingChildren(scratch.children(), kMaxChildren);
2081
+ if (childCount == 0 && !isDisplayGrid(node_.style)) {
1140
2082
  positionAbsoluteChildren();
1141
2083
  return;
1142
2084
  }
@@ -1148,27 +2090,639 @@ public:
1148
2090
  return;
1149
2091
  }
1150
2092
 
1151
- FlexLayoutPass flex(engine_, node_, scratch.children(), childCount, isRow, mainAvail, padWidth, padHeight, scratch.lines(), inlineRow);
2093
+ if (layoutFloatChildren(scratch.children(), childCount, padWidth, padHeight, false)) {
2094
+ updateScrollContentSize();
2095
+ positionAbsoluteChildren();
2096
+ applyRelativeOffsets();
2097
+ return;
2098
+ }
2099
+ if (layoutBlockChildren(scratch.children(), childCount, padWidth, padHeight, false)) {
2100
+ positionAbsoluteChildren();
2101
+ applyRelativeOffsets();
2102
+ return;
2103
+ }
2104
+
2105
+ FlexLayoutPass flex(engine_, node_, scratch.children(), childCount, isRow, mainAvail, padWidth, padHeight, scratch.lines(), inlineRow, true);
1152
2106
  flex.measureChildren();
1153
2107
  if (inlineRow) {
1154
2108
  flex.layoutInlineFlow(false);
1155
2109
  } else {
1156
- const int lineCount = flex.buildLines();
1157
- flex.expandCrossSizes(lineCount, false);
1158
- flex.positionLines(lineCount);
2110
+ flex.layoutLines(false);
1159
2111
  }
1160
2112
  positionAbsoluteChildren();
1161
2113
  applyRelativeOffsets();
1162
2114
  }
1163
2115
 
2116
+ bool containsChildMargins() const
2117
+ {
2118
+ // A stable border box is not sufficient for isolated relayout: child
2119
+ // margins can change an ancestor's position/size through either edge.
2120
+ // Check the boundary itself, so removing the last collapsing child is
2121
+ // handled as well as introducing or resizing one.
2122
+ const bool horizontal = writingMode(node_) != 0;
2123
+ return !blockBox(node_) || establishesBlockContext(node_) ||
2124
+ (boxInset(node_.style, blockMarginSide(false)) > 0 &&
2125
+ (boxInset(node_.style, blockMarginSide(true)) > 0 ||
2126
+ (horizontal ? hasExplicitWidth(node_) : hasExplicitHeight(node_)) ||
2127
+ (horizontal ? node_.style.min_width : node_.style.min_height) > 0));
2128
+ }
2129
+
1164
2130
  private:
2131
+ void invalidateInlineChildMetadata()
2132
+ {
2133
+ for (int child = node_.first_child; child >= 0; child = nodes_[child].next_sibling) {
2134
+ NodeRareData *rare = rareDataFor(child);
2135
+ if (!rare) continue;
2136
+ rare->inlineStaticPosition.valid = false;
2137
+ #if GEA_CSS_FIRST_LINE
2138
+ rare->firstLineFragment.valid = false;
2139
+ #endif
2140
+ }
2141
+ }
2142
+
2143
+ bool splitInlineChildren_ = false;
2144
+ int collectFormattingChildren(int *children, int capacity)
2145
+ {
2146
+ if (node_.style.display != kDisplayBlock || node_.style.flex_direction_explicit)
2147
+ return engine_.collectChildren(id_, children, capacity, true);
2148
+ int count = 0;
2149
+ auto collect = [&](auto &&self, int parent) -> void {
2150
+ for (int c = nodes_[parent].first_child; c >= 0; c = nodes_[c].next_sibling) {
2151
+ Node &child = nodes_[c];
2152
+ if (isDisplayNone(child.style) || isOutOfFlowPosition(child.style.position) || suppressAnonymousWhitespace(nodes_, parent, c)) continue;
2153
+ if (splitInlineWrapper(nodes_, c)) {
2154
+ splitInlineChildren_ = true;
2155
+ child.layout.x = child.layout.y = child.layout.width = child.layout.height = 0;
2156
+ #if GEA_CSS_SCROLLING
2157
+ child.layout.scroll_content_width = child.layout.scroll_content_height = 0;
2158
+ #endif
2159
+ child.layout.memo_pass = child.layout.memo2_pass = 0;
2160
+ self(self, c);
2161
+ } else if (count < capacity) children[count++] = c;
2162
+ }
2163
+ };
2164
+ collect(collect, id_);
2165
+ return count;
2166
+ }
2167
+
2168
+ struct FloatBox { int left, top, right, bottom, side; };
2169
+ // One exclusion space for the entire BFC, including ordinary wrappers.
2170
+ // Coordinates exclude relative-position offsets. Clearance is used layout
2171
+ // state, not a consequence of merely authoring a non-none clear value.
2172
+ struct FloatContext {
2173
+ std::vector<FloatBox> boxes;
2174
+ std::vector<int> cleared;
2175
+ int lastTop = 0;
2176
+ bool hasClearance(int id) const { return std::find(cleared.begin(), cleared.end(), id) != cleared.end(); }
2177
+ };
2178
+ FloatContext *floatContext_ = nullptr;
2179
+
2180
+ struct CollapsedMargin {
2181
+ int positive = 0, negative = 0;
2182
+ bool trimmed = false;
2183
+ void add(int value) { positive = std::max(positive, value); negative = std::min(negative, value); }
2184
+ void add(CollapsedMargin other) { add(other.positive); add(other.negative); trimmed |= other.trimmed; }
2185
+ int value() const { return trimmed ? 0 : positive + negative; }
2186
+ };
2187
+
2188
+ bool blockBox(const Node &n) const
2189
+ {
2190
+ return n.type == NodeType::View && !isDisplayNone(n.style) &&
2191
+ (n.style.display_explicit || !isInlineLevelTag(tagFromId(n.tag_id)));
2192
+ }
2193
+
2194
+ bool flowChild(int parent, int child) const
2195
+ {
2196
+ return !isDisplayNone(nodes_[child].style) && !isOutOfFlowPosition(nodes_[child].style.position) &&
2197
+ !nodes_[child].style.float_side && !suppressAnonymousWhitespace(nodes_, parent, child);
2198
+ }
2199
+
2200
+ bool establishesBlockContext(const Node &n) const
2201
+ {
2202
+ return n.parent < 0 || isOutOfFlowPosition(n.style.position) || n.style.float_side ||
2203
+ n.style.display != kDisplayBlock || overflowEstablishesContext(n.style) ||
2204
+ (n.parent >= 0 && (nodes_[n.parent].style.display == kDisplayFlex || isDisplayGrid(nodes_[n.parent].style) ||
2205
+ writingMode(n) != writingMode(nodes_[n.parent])));
2206
+ }
2207
+
2208
+ void encloseFloatDescendants()
2209
+ {
2210
+ if (node_.style.display != kDisplayBlock || hasExplicitHeight(node_) || !establishesBlockContext(node_)) return;
2211
+ int bottom = node_.layout.height - boxInset(node_.style, 2);
2212
+ // With floats absent, no descendant can extend this bound. Keep the
2213
+ // final height clamp without walking the same subtree at every ancestor.
2214
+ #if GEA_CSS_FLOATS
2215
+ // CSS 2.2 10.6.7 includes floats through ordinary wrappers, but never
2216
+ // crosses another formatting context. Child layout is still relative;
2217
+ // offsets below the first level have already been applied by its parent.
2218
+ auto visit = [&](auto &&self, int parent, int y) -> void {
2219
+ for (int id = nodes_[parent].first_child; id >= 0; id = nodes_[id].next_sibling) {
2220
+ const Node &child = nodes_[id];
2221
+ if (isDisplayNone(child.style) || isOutOfFlowPosition(child.style.position)) continue;
2222
+ int top = y + child.layout.y;
2223
+ if (parent != id_ && child.style.position == 2) {
2224
+ LayoutNodePass owner(engine_, parent, 0, 0);
2225
+ if (hasPositionOffset<0>(child)) top -= owner.resolvedRelativePositionOffset<0>(child);
2226
+ else if (hasPositionOffset<2>(child)) top += owner.resolvedRelativePositionOffset<2>(child);
2227
+ }
2228
+ if (child.style.float_side) bottom = std::max(bottom, top + child.layout.height + child.style.margin[2]);
2229
+ else if (!establishesBlockContext(child)) self(self, id, top);
2230
+ }
2231
+ };
2232
+ visit(visit, id_, 0);
2233
+ #endif
2234
+ node_.layout.height = clampBorderSize(engine_, node_, bottom + boxInset(node_.style, 2), false);
2235
+ }
2236
+
2237
+ int blockMarginSide(bool end) const
2238
+ {
2239
+ if (writingMode(node_) == 0) return end ? 2 : 0;
2240
+ return gridAxisReversed(node_, true) != end ? 1 : 3;
2241
+ }
2242
+
2243
+ bool collapsesThrough(int id) const
2244
+ {
2245
+ const Node &n = nodes_[id];
2246
+ const bool horizontal = writingMode(node_) != 0;
2247
+ if (!blockBox(n) || establishesBlockContext(n) || (horizontal ? n.layout.width : n.layout.height) != 0 ||
2248
+ (horizontal ? n.style.min_width : n.style.min_height) > 0 || boxInsets(n.style, horizontal)) return false;
2249
+ bool through = true;
2250
+ visitFormattingChildren(nodes_, id, [&](int c) {
2251
+ if (flowChild(nodes_[c].parent, c) && ((floatContext_ && floatContext_->hasClearance(c)) || !collapsesThrough(c))) through = false;
2252
+ });
2253
+ return through;
2254
+ }
2255
+
2256
+ bool collapsesWithChildren(int id, bool bottom) const
2257
+ {
2258
+ const Node &n = nodes_[id];
2259
+ const bool horizontal = writingMode(node_) != 0;
2260
+ if (!blockBox(n) || establishesBlockContext(n) || boxInset(n.style, blockMarginSide(bottom))) return false;
2261
+ if (bottom && ((horizontal ? hasExplicitWidth(n) : hasExplicitHeight(n)) ||
2262
+ isIntrinsicSizeExpression(horizontal ? n.style.width_expression : n.style.height_expression) ||
2263
+ (horizontal ? n.style.min_width : n.style.min_height) > 0)) return false;
2264
+ int edge = -1;
2265
+ visitFormattingChildren(nodes_, id, [&](int c) {
2266
+ if (!flowChild(nodes_[c].parent, c) || (edge >= 0 && !bottom)) return;
2267
+ edge = c;
2268
+ });
2269
+ return edge >= 0 && blockBox(nodes_[edge]) &&
2270
+ !(floatContext_ && floatContext_->hasClearance(edge) && (!bottom || collapsesThrough(edge)));
2271
+ }
2272
+
2273
+ CollapsedMargin edgeMargin(int id, bool bottom, bool separateBottom = false) const
2274
+ {
2275
+ const Node &n = nodes_[id];
2276
+ CollapsedMargin margin;
2277
+ margin.add(n.style.margin[blockMarginSide(bottom)]);
2278
+ CollapsedMargin descendants;
2279
+ if (!separateBottom && collapsesThrough(id)) {
2280
+ margin.add(n.style.margin[blockMarginSide(!bottom)]);
2281
+ visitFormattingChildren(nodes_, id, [&](int c) {
2282
+ if (flowChild(nodes_[c].parent, c)) descendants.add(childEdgeMargin(id, c, false));
2283
+ });
2284
+ } else if (collapsesWithChildren(id, bottom)) {
2285
+ bool stop = false;
2286
+ visitFormattingChildren(nodes_, id, [&](int c) {
2287
+ if (stop || !flowChild(nodes_[c].parent, c)) return;
2288
+ if (!blockBox(nodes_[c]) || (floatContext_ && floatContext_->hasClearance(c) && (!bottom || collapsesThrough(c)))) { stop = true; return; }
2289
+ descendants.add(childEdgeMargin(id, c, bottom));
2290
+ if (!collapsesThrough(c)) stop = true;
2291
+ }, bottom);
2292
+ }
2293
+ if (!descendants.trimmed) margin.add(descendants);
2294
+ return margin;
2295
+ }
2296
+
2297
+ // Whether this edge belongs to the collapsed group adjoining a container
2298
+ // boundary. Floats and positioned children do not consume that boundary;
2299
+ // inline content and non-empty blocks do.
2300
+ bool trimmedBlockEdge(int owner, int id, bool bottom) const
2301
+ {
2302
+ const Node &container = nodes_[owner];
2303
+ const int trim = (GEA_CSS_MARGIN_TRIM ? rstyle(container.style).margin_trim : 0);
2304
+ if (!(trim & 3) || container.style.display != kDisplayBlock || container.style.flex_direction_explicit || !blockBox(nodes_[id])) return false;
2305
+ for (bool end : {false, true}) {
2306
+ if (!(trim & (end ? 2 : 1)) || (end != bottom && !collapsesThrough(id))) continue;
2307
+ bool adjacent = true, found = false;
2308
+ visitFormattingChildren(nodes_, owner, [&](int child) {
2309
+ if (found || !adjacent || !flowChild(nodes_[child].parent, child)) return;
2310
+ if (child == id) { found = true; return; }
2311
+ if (!collapsesThrough(child) || (floatContext_ && floatContext_->hasClearance(child))) adjacent = false;
2312
+ }, end);
2313
+ if (found && adjacent) return true;
2314
+ }
2315
+ return false;
2316
+ }
2317
+
2318
+ CollapsedMargin childEdgeMargin(int owner, int id, bool bottom, bool separateBottom = false) const
2319
+ {
2320
+ auto margin = edgeMargin(id, bottom, separateBottom);
2321
+ margin.trimmed = trimmedBlockEdge(owner, id, bottom);
2322
+ return margin;
2323
+ }
2324
+
2325
+ bool layoutBlockChildren(int *children, int count, int contentWidth, int contentHeight, bool autosize)
2326
+ {
2327
+ if (node_.style.display != kDisplayBlock || node_.style.flex_direction_explicit) return false;
2328
+ const bool vertical = writingMode(node_) != 0;
2329
+ for (int i = 0; i < count; ++i)
2330
+ if (!blockBox(nodes_[children[i]]) || nodes_[children[i]].style.float_side) return false;
2331
+ if (vertical) {
2332
+ const bool measureInline = autosize && !hasExplicitHeight(node_) && node_.parent >= 0;
2333
+ int intrinsicHeight = 0;
2334
+ for (int i = 0; i < count; ++i) {
2335
+ engine_.layoutNode(children[i], contentWidth, contentHeight);
2336
+ const Node &child = nodes_[children[i]];
2337
+ intrinsicHeight = std::max(intrinsicHeight, child.layout.height + child.style.margin[0] + child.style.margin[2]);
2338
+ }
2339
+ if (measureInline) {
2340
+ node_.layout.height = clampLayoutSize(node_, intrinsicHeight + boxInsets(node_.style, false), false);
2341
+ contentHeight = paddedHeight();
2342
+ }
2343
+ for (int i = 0; i < count; ++i) {
2344
+ const int id = children[i]; Node &child = nodes_[id];
2345
+ if (measureInline) engine_.layoutNode(id, contentWidth, contentHeight);
2346
+ if (!hasExplicitHeight(child) && !isIntrinsicSizeExpression(child.style.height_expression) && writingMode(child) != 0 &&
2347
+ !(preferredRatio(child) > 0 && hasExplicitWidth(child))) {
2348
+ const int height = clampLayoutSize(child, std::max(0, contentHeight - child.style.margin[0] - child.style.margin[2]), false);
2349
+ if (child.layout.height != height) {
2350
+ child.layout.height = clampInt16(height); engine_.repositionChildren(id);
2351
+ }
2352
+ }
2353
+ const int slack = contentHeight - child.layout.height - child.style.margin[0] - child.style.margin[2];
2354
+ const bool autoTop = child.style.margin_auto & 1, autoBottom = child.style.margin_auto & 4;
2355
+ int offset = slack > 0 && autoTop ? (autoBottom ? slack / 2 : slack) : 0;
2356
+ if (!autoTop && !autoBottom && gridAxisReversed(node_, false)) offset = slack;
2357
+ child.layout.y = boxInset(node_.style, 0) + child.style.margin[0] + offset;
2358
+ }
2359
+ } else {
2360
+ // Measure content before assigning the normal-flow fill width. A flex
2361
+ // item, float, or absolute box can use this intrinsic width; its parent
2362
+ // assigns the final width and calls repositionChildren afterwards.
2363
+ const bool measureIntrinsic = autosize && (node_.parent >= 0 || node_.style.float_side || intrinsicWidthConstraint(node_)) && !hasExplicitWidth(node_);
2364
+ int intrinsicWidth = 0;
2365
+ for (int i = 0; i < count; ++i) {
2366
+ const int id = children[i];
2367
+ engine_.layoutNode(id, contentWidth, contentHeight, measureIntrinsic);
2368
+ const Node &child = nodes_[id];
2369
+ intrinsicWidth = std::max(intrinsicWidth, child.layout.width + child.style.margin[1] + child.style.margin[3]);
2370
+ }
2371
+ if (measureIntrinsic) {
2372
+ node_.layout.width = clampLayoutSize(node_, intrinsicWidth + boxInsets(node_.style, true), true);
2373
+ contentWidth = paddedWidth();
2374
+ }
2375
+ for (int i = 0; i < count; ++i) {
2376
+ const int id = children[i];
2377
+ Node &child = nodes_[id];
2378
+ if (measureIntrinsic) engine_.layoutNode(id, contentWidth, contentHeight);
2379
+ // This horizontal formatting context fills the inline size of
2380
+ // parallel children. An orthogonal child's width is its block size.
2381
+ if (!hasExplicitWidth(child) && !isIntrinsicSizeExpression(child.style.width_expression) && writingMode(child) == 0 && !(preferredRatio(child) > 0 && hasExplicitHeight(child))) {
2382
+ const int width = clampLayoutSize(child, std::max(0, contentWidth - child.style.margin[1] - child.style.margin[3]), true);
2383
+ if (child.layout.width != width) {
2384
+ child.layout.width = clampInt16(width);
2385
+ engine_.repositionChildren(id);
2386
+ }
2387
+ }
2388
+ const int slack = contentWidth - child.layout.width - child.style.margin[1] - child.style.margin[3];
2389
+ const bool autoLeft = child.style.margin_auto & (1 << 3);
2390
+ const bool autoRight = child.style.margin_auto & (1 << 1);
2391
+ int offset = slack > 0 && autoLeft ? (autoRight ? slack / 2 : slack) : 0;
2392
+ if (!autoLeft && !autoRight && rightToLeft(node_)) offset = slack;
2393
+ child.layout.x = boxInset(node_.style, 3) + child.style.margin[3] + offset;
2394
+ }
2395
+ }
2396
+ const bool mergeTop = collapsesWithChildren(id_, false);
2397
+ const bool mergeBottom = collapsesWithChildren(id_, true);
2398
+ int cursor = 0;
2399
+ bool first = true;
2400
+ CollapsedMargin pending;
2401
+ for (int i = 0; i < count; ++i) {
2402
+ const int id = children[i];
2403
+ Node &child = nodes_[id];
2404
+ if (collapsesThrough(id)) {
2405
+ // CSS 2.2 8.3.1: an empty box sharing the parent's top margin
2406
+ // starts at that edge. Otherwise position it as if it had a bottom
2407
+ // border, before its own bottom and following siblings' margins
2408
+ // join the group. Its position does not advance normal flow.
2409
+ auto before = pending;
2410
+ before.add(childEdgeMargin(id_, id, false, true));
2411
+ (vertical ? child.layout.x : child.layout.y) = boxInset(node_.style, blockMarginSide(false)) + cursor + (first && mergeTop ? 0 : before.value());
2412
+ pending.add(childEdgeMargin(id_, id, false));
2413
+ continue;
2414
+ }
2415
+ pending.add(childEdgeMargin(id_, id, false));
2416
+ cursor += first && mergeTop ? 0 : pending.value();
2417
+ (vertical ? child.layout.x : child.layout.y) = boxInset(node_.style, blockMarginSide(false)) + cursor;
2418
+ cursor += vertical ? child.layout.width : child.layout.height;
2419
+ pending = childEdgeMargin(id_, id, true);
2420
+ first = false;
2421
+ }
2422
+ cursor += mergeBottom || (first && mergeTop) ? 0 : pending.value();
2423
+ if (vertical) {
2424
+ if (autosize && !hasExplicitWidth(node_) && !(scrollsOverflowX(node_.style) && node_.layout.width > 0))
2425
+ node_.layout.width = clampLayoutSize(node_, std::max(0, cursor) + boxInsets(node_.style, true), true);
2426
+ if (gridAxisReversed(node_, true)) for (int i = 0; i < count; ++i) {
2427
+ Node &child = nodes_[children[i]];
2428
+ child.layout.x = node_.layout.width - child.layout.x - child.layout.width;
2429
+ }
2430
+ } else if (autosize && !hasExplicitHeight(node_) && !(scrollsOverflowY(node_.style) && node_.layout.height > 0)) {
2431
+ node_.layout.height = clampLayoutSize(node_, std::max(0, cursor) + boxInsets(node_.style, false), false);
2432
+ }
2433
+ return true;
2434
+ }
2435
+
2436
+ bool layoutFloatChildren(int *children, int count, int contentWidth, int contentHeight, bool autosize)
2437
+ {
2438
+ if (node_.style.display != kDisplayBlock) return false;
2439
+ #if GEA_CSS_FLOATS
2440
+ auto containsFloat = [&](auto &&self, int parent) -> bool {
2441
+ for (int c = nodes_[parent].first_child; c >= 0; c = nodes_[c].next_sibling) {
2442
+ const Node &child = nodes_[c];
2443
+ if (isDisplayNone(child.style) || isOutOfFlowPosition(child.style.position)) continue;
2444
+ if (child.style.float_side || (!establishesBlockContext(child) && self(self, c))) return true;
2445
+ }
2446
+ return false;
2447
+ };
2448
+ #endif
2449
+ bool blocks = false, inlines = false;
2450
+ for (int i = 0; i < count; ++i) {
2451
+ if (blockBox(nodes_[children[i]])) blocks = true;
2452
+ else if (!nodes_[children[i]].style.float_side) inlines = true;
2453
+ }
2454
+ if (!splitInlineChildren_ && !(blocks && inlines)
2455
+ #if GEA_CSS_FLOATS
2456
+ && !containsFloat(containsFloat, id_)
2457
+ #endif
2458
+ ) return false;
2459
+ FloatContext context;
2460
+ const bool measureWidth = autosize && !hasExplicitWidth(node_) &&
2461
+ (node_.parent >= 0 || node_.style.float_side || intrinsicWidthConstraint(node_)) &&
2462
+ !(scrollsOverflowX(node_.style) && node_.layout.width > 0 && !intrinsicWidthConstraint(node_));
2463
+ layoutFloatChildrenInContext(children, count, contentWidth, contentHeight, autosize, context, 0, 0, measureWidth);
2464
+ if (measureWidth && paddedWidth() != contentWidth) {
2465
+ // As in ordinary block layout, measure first, then assign the used
2466
+ // containing width. Descendants in an existing float context already
2467
+ // have an assigned width and must not shrink it during placement.
2468
+ context = {};
2469
+ layoutFloatChildrenInContext(children, count, paddedWidth(), contentHeight, autosize, context, 0, 0);
2470
+ }
2471
+ floatContext_ = nullptr;
2472
+ return true;
2473
+ }
2474
+
2475
+ void layoutFloatChildrenInContext(int *children, int count, int contentWidth, int contentHeight, bool autosize,
2476
+ FloatContext &context, int originX, int originY, bool measureWidth = false)
2477
+ {
2478
+ floatContext_ = &context;
2479
+ auto &floats = context.boxes;
2480
+ int flowY = 0;
2481
+ int intrinsicWidth = 0;
2482
+ CollapsedMargin pending;
2483
+ bool first = true, clearedThrough = false;
2484
+ for (int i = 0; i < count; ++i) {
2485
+ Node &child = nodes_[children[i]];
2486
+ if (!blockBox(child) && !child.style.float_side) {
2487
+ int end = i + 1;
2488
+ // Keep a BR with the line it terminates, then recompute the
2489
+ // float exclusions for the next line.
2490
+ while (!isLineBreak(nodes_[children[end - 1]]) &&
2491
+ end < count && !blockBox(nodes_[children[end]]) && !nodes_[children[end]].style.float_side) ++end;
2492
+ flowY += pending.value();
2493
+ pending = {};
2494
+ ScratchFrame inlineScratch;
2495
+ if (inlineScratch.valid()) {
2496
+ auto layoutRun = [&](int width) {
2497
+ FlexLayoutPass line(engine_, node_, children + i, end - i, true, width, width, contentHeight, inlineScratch.lines(), true);
2498
+ line.measureChildren();
2499
+ return line.layoutInlineFlow(false, true);
2500
+ };
2501
+ #if GEA_CSS_FIRST_LINE
2502
+ NodeRareData *ownerRare = rareDataFor(id_);
2503
+ const bool ownerLineWasValid = ownerRare && ownerRare->firstLineBackground.lineValid;
2504
+ #endif
2505
+ auto extent = layoutRun(contentWidth);
2506
+ // If even the first unbreakable unit cannot fit beside a float,
2507
+ // move this line down to the next float boundary and retry.
2508
+ // Once the whole containing width is available, the word may overflow.
2509
+ int minimum = 0;
2510
+ for (int j = i; j < end && minimum == 0; ++j) {
2511
+ const Node &item = nodes_[children[j]];
2512
+ if (isLineBreak(item)) break;
2513
+ const int inner = FlexLayoutPass::transparentInlineRun(item);
2514
+ minimum = item.type == NodeType::Text || inner >= 0
2515
+ ? TextRenderer::firstUnbreakableWidth(inner >= 0 ? nodes_[inner] : item)
2516
+ : item.layout.width;
2517
+ minimum += item.style.margin[1] + item.style.margin[3];
2518
+ if (item.type == NodeType::Text) minimum += boxInsets(item.style, true);
2519
+ }
2520
+ int left = 0, right = contentWidth;
2521
+ for (;;) {
2522
+ left = 0; right = contentWidth;
2523
+ int nextBottom = INT_MAX;
2524
+ for (const auto &f : floats) {
2525
+ if (originY + flowY >= f.bottom || originY + flowY + extent.firstLineHeight <= f.top) continue;
2526
+ if (f.side == 1) left = std::max(left, f.right - originX);
2527
+ else right = std::min(right, f.left - originX);
2528
+ nextBottom = std::min(nextBottom, f.bottom - originY);
2529
+ }
2530
+ if (minimum <= right-left || (left == 0 && right == contentWidth) || nextBottom == INT_MAX) break;
2531
+ flowY = nextBottom;
2532
+ }
2533
+ if (right - left != contentWidth) extent = layoutRun(std::max(0, right - left));
2534
+ #if GEA_CSS_FIRST_LINE
2535
+ if (!ownerLineWasValid && ownerRare && ownerRare->firstLineBackground.lineValid)
2536
+ ownerRare->firstLineBackground.lineY = clampInt16(ownerRare->firstLineBackground.lineY + flowY);
2537
+ for (int j = i; j < end; ++j) {
2538
+ const int childId = children[j];
2539
+ const int runId = FlexLayoutPass::transparentInlineRun(nodes_[childId]);
2540
+ for (int fragmentId : {childId, runId}) {
2541
+ if (fragmentId < 0) continue;
2542
+ if (NodeRareData *rare = rareDataFor(fragmentId)) {
2543
+ auto &fragment = rare->firstLineFragment;
2544
+ if (fragment.valid && fragment.contextNode == id_) {
2545
+ fragment.x = clampInt16(fragment.x + left);
2546
+ fragment.y = clampInt16(fragment.y + flowY);
2547
+ }
2548
+ }
2549
+ }
2550
+ }
2551
+ #endif
2552
+ for (int j = i; j < end; ++j) {
2553
+ nodes_[children[j]].layout.x += left;
2554
+ nodes_[children[j]].layout.y += flowY;
2555
+ }
2556
+ flowY += extent.height;
2557
+ intrinsicWidth = std::max(intrinsicWidth, left + extent.width);
2558
+ const Node &last = nodes_[children[end - 1]];
2559
+ if (isLineBreak(last)) for (const auto &f : floats)
2560
+ if (last.style.clear_side & f.side) flowY = std::max(flowY, f.bottom - originY);
2561
+ }
2562
+ first = false; clearedThrough = false;
2563
+ i = end - 1;
2564
+ continue;
2565
+ }
2566
+ engine_.layoutNode(children[i], contentWidth, contentHeight, measureWidth);
2567
+ const bool block = !child.style.float_side && blockBox(child);
2568
+ const int measuredOuterW = child.layout.width + child.style.margin[3] + child.style.margin[1];
2569
+ const bool automaticWidth = block && !hasExplicitWidth(child) && !isIntrinsicSizeExpression(child.style.width_expression) &&
2570
+ writingMode(child) == 0 && !(preferredRatio(child) > 0 && hasExplicitHeight(child));
2571
+ // Ordinary blocks still fill their containing block beside floats;
2572
+ // only their line boxes are shortened by float exclusions.
2573
+ if (automaticWidth) {
2574
+ const int width = clampLayoutSize(child, std::max(0, contentWidth - child.style.margin[1] - child.style.margin[3]), true);
2575
+ if (child.layout.width != width) {
2576
+ child.layout.width = clampInt16(width);
2577
+ engine_.repositionChildren(children[i]);
2578
+ }
2579
+ }
2580
+ int outerW = child.layout.width + child.style.margin[3] + child.style.margin[1];
2581
+ int outerH = child.layout.height + child.style.margin[0] + child.style.margin[2];
2582
+ const bool mergeTop = first && collapsesWithChildren(id_, false);
2583
+ if (!block && !child.style.float_side) {
2584
+ flowY += mergeTop ? 0 : pending.value();
2585
+ pending = {};
2586
+ first = false;
2587
+ }
2588
+ auto before = pending;
2589
+ if (block) before.add(childEdgeMargin(id_, children[i], false, true));
2590
+ // Normal blocks clear their border edge, after adjoining margins
2591
+ // collapse. Floats instead clear their outer edge (CSS 2.2 9.5.2).
2592
+ int y = block ? flowY + (mergeTop ? 0 : before.value()) :
2593
+ child.style.float_side ? std::max(flowY + (mergeTop ? 0 : pending.value()), context.lastTop - originY) : flowY;
2594
+ const int hypotheticalY = y;
2595
+ int clearBottom = INT_MIN;
2596
+ for (const auto &f : floats)
2597
+ if (child.style.clear_side & f.side) clearBottom = std::max(clearBottom, f.bottom - originY);
2598
+ const bool clearance = block && clearBottom != INT_MIN && (clearBottom > hypotheticalY || context.hasClearance(children[i]));
2599
+ // Once clearance separated the margins, rebasing the wrapper must
2600
+ // not mistake the now non-collapsing margin for a new hypothetical
2601
+ // position. CSS permits aligning exactly to the float bottom, even
2602
+ // when that requires negative clearance above the top margin.
2603
+ y = clearance ? clearBottom : std::max(y, clearBottom);
2604
+ if (clearance && !context.hasClearance(children[i])) context.cleared.push_back(children[i]);
2605
+ int left = 0, right = contentWidth, contextX = 0;
2606
+ const bool independentBlock = block && establishesBlockContext(child);
2607
+ if (child.style.float_side || child.style.display != kDisplayBlock || establishesBlockContext(child)) {
2608
+ for (;;) {
2609
+ left = 0; right = contentWidth;
2610
+ int nextY = 32767;
2611
+ bool hasLeft = false, hasRight = false;
2612
+ for (const auto &global : floats) {
2613
+ const FloatBox f{global.left - originX, global.top - originY, global.right - originX, global.bottom - originY, global.side};
2614
+ if (y >= f.bottom || y + std::max(1, independentBlock ? int(child.layout.height) : outerH) <= f.top) continue;
2615
+ if (f.side == 1) { left = std::max(left, f.right); hasLeft = true; }
2616
+ else { right = std::min(right, f.left); hasRight = true; }
2617
+ nextY = std::min(nextY, f.bottom);
2618
+ }
2619
+ bool fits = outerW <= right - left;
2620
+ if (independentBlock) {
2621
+ // A BFC's border box cannot overlap float margin boxes.
2622
+ // Automatic width uses the remaining interval. Even a
2623
+ // zero-width float prevents a negative margin crossing it.
2624
+ const int start = hasLeft ? std::max<int>(child.style.margin[3], left) : child.style.margin[3];
2625
+ const int end = hasRight ? std::min<int>(contentWidth - child.style.margin[1], right) : contentWidth - child.style.margin[1];
2626
+ contextX = start - child.style.margin[3];
2627
+ if (automaticWidth) {
2628
+ const int width = clampLayoutSize(child, std::max(0, end - start), true);
2629
+ if (child.layout.width != width) {
2630
+ const int previousHeight = child.layout.height;
2631
+ engine_.layoutNode(children[i], width + child.style.margin[1] + child.style.margin[3], contentHeight);
2632
+ child.layout.width = clampInt16(width);
2633
+ engine_.repositionChildren(children[i]);
2634
+ outerW = width + child.style.margin[1] + child.style.margin[3];
2635
+ outerH = child.layout.height + child.style.margin[0] + child.style.margin[2];
2636
+ if (previousHeight != child.layout.height) continue;
2637
+ }
2638
+ }
2639
+ fits = child.layout.width <= end - start;
2640
+ }
2641
+ if (fits || nextY == 32767) break;
2642
+ y = nextY;
2643
+ }
2644
+ }
2645
+ const int x = child.style.float_side == 2 ? right - outerW : independentBlock ? contextX : left;
2646
+ intrinsicWidth = std::max(intrinsicWidth, child.style.float_side
2647
+ ? left + outerW + contentWidth - right : measuredOuterW);
2648
+ child.layout.x = boxInset(node_.style, 3) + x + child.style.margin[3];
2649
+ child.layout.y = boxInset(node_.style, 0) + y + (block ? 0 : child.style.margin[0]);
2650
+ if (block && !establishesBlockContext(child) && child.first_child >= 0) {
2651
+ LayoutNodePass nested(engine_, children[i], contentWidth, contentHeight);
2652
+ if (!nested.resolveInlineFormattingRow()) {
2653
+ ScratchFrame nestedScratch;
2654
+ if (nestedScratch.valid()) {
2655
+ const int nestedCount = nested.collectFormattingChildren(nestedScratch.children(), kMaxChildren);
2656
+ const auto precedingFloats = floats.size();
2657
+ const int precedingTop = context.lastTop;
2658
+ auto placeDescendants = [&]() {
2659
+ nested.layoutFloatChildrenInContext(nestedScratch.children(), nestedCount, nested.paddedWidth(), nested.paddedHeight(), true,
2660
+ context, originX + x + child.style.margin[3] + boxInset(child.style, 3), originY + y + boxInset(child.style, 0));
2661
+ };
2662
+ placeDescendants();
2663
+ // Actual descendant clearance can separate a margin that was
2664
+ // adjoining this wrapper's top during hypothetical placement.
2665
+ // Rebase the subtree with that separation recorded; discard
2666
+ // its provisional floats before placing them at the final edge.
2667
+ auto separated = pending;
2668
+ separated.add(childEdgeMargin(id_, children[i], false, true));
2669
+ int finalY = flowY + (first && collapsesWithChildren(id_, false) ? 0 : separated.value());
2670
+ if (clearance) finalY = clearBottom;
2671
+ for (std::size_t f = 0; f < precedingFloats; ++f)
2672
+ if (child.style.clear_side & floats[f].side) finalY = std::max(finalY, floats[f].bottom - originY);
2673
+ if (finalY != y) {
2674
+ y = finalY;
2675
+ child.layout.y = boxInset(node_.style, 0) + y;
2676
+ floats.resize(precedingFloats);
2677
+ context.lastTop = precedingTop;
2678
+ placeDescendants();
2679
+ }
2680
+ nested.updateScrollContentSize();
2681
+ nested.positionAbsoluteChildren();
2682
+ nested.applyRelativeOffsets();
2683
+ // This result depends on preceding floats, beyond the size-only memo key.
2684
+ child.layout.memo_pass = child.layout.memo2_pass = 0;
2685
+ }
2686
+ }
2687
+ }
2688
+ if (child.style.float_side) {
2689
+ floats.push_back({originX + x, originY + y, originX + x + outerW, originY + y + outerH, child.style.float_side});
2690
+ context.lastTop = originY + y;
2691
+ } else if (block && collapsesThrough(children[i])) {
2692
+ if (clearance) {
2693
+ // The cleared empty box's margins can still collapse forward,
2694
+ // but that group cannot escape through the parent's bottom.
2695
+ flowY = y - childEdgeMargin(id_, children[i], false, true).value();
2696
+ pending = {};
2697
+ first = false;
2698
+ clearedThrough = true;
2699
+ }
2700
+ pending.add(childEdgeMargin(id_, children[i], false));
2701
+ } else if (block) {
2702
+ flowY = y + child.layout.height;
2703
+ pending = childEdgeMargin(id_, children[i], true);
2704
+ first = false;
2705
+ clearedThrough = false;
2706
+ } else flowY = y + outerH;
2707
+ }
2708
+ if (clearedThrough || (!collapsesWithChildren(id_, true) && !(first && collapsesWithChildren(id_, false))))
2709
+ flowY += pending.value();
2710
+ if (measureWidth)
2711
+ node_.layout.width = clampInt16(clampLayoutSize(node_, intrinsicWidth + boxInsets(node_.style, true), true));
2712
+ if (autosize && !hasExplicitHeight(node_)) {
2713
+ // Float enclosure is finalized with all same-context descendants.
2714
+ node_.layout.height = clampBorderSize(engine_, node_, flowY + boxInsets(node_.style, false), false);
2715
+ }
2716
+ }
2717
+
1165
2718
  // Direction for FlexLayoutPass. Explicit flex-direction / display:flex win
1166
2719
  // (usesRowLayout). Otherwise a plain block whose in-flow children are all
1167
2720
  // inline-level flows them on a row (CSS inline formatting); a block with any
1168
2721
  // block-level in-flow child stacks them (column), as a browser would.
1169
2722
  bool resolveRowDirection() const
1170
2723
  {
1171
- if (usesRowLayout(node_.style)) return true;
2724
+ if (node_.style.display == kDisplayFlex)
2725
+ return flexRowDirection(node_.style) != (writingMode(node_) != 0);
1172
2726
  return resolveInlineFormattingRow();
1173
2727
  }
1174
2728
 
@@ -1181,29 +2735,15 @@ private:
1181
2735
  {
1182
2736
  if (usesRowLayout(node_.style)) return false;
1183
2737
  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) {
2738
+ bool anyInFlow = false, allInline = true;
2739
+ visitFormattingChildren(nodes_, id_, [&](int c) {
1186
2740
  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;
2741
+ if (child.style.display == kDisplayNone || isOutOfFlowPosition(child.style.position)) return;
2742
+ if (suppressAnonymousWhitespace(nodes_, child.parent, c)) return;
2743
+ if (!LayoutEngine::isInlineLevelNode(child)) allInline = false;
1189
2744
  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;
2745
+ });
2746
+ return anyInFlow && allInline;
1207
2747
  }
1208
2748
 
1209
2749
  void measureGridChildren(int *children, int childCount, int padWidth, int padHeight)
@@ -1214,34 +2754,12 @@ private:
1214
2754
  }
1215
2755
  }
1216
2756
 
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
2757
  void computeTrackSizes(int count,
1241
2758
  const int8_t *types,
1242
2759
  const int16_t *values,
1243
2760
  const int *autoSizes,
1244
2761
  int available,
2762
+ int gap,
1245
2763
  int *outSizes)
1246
2764
  {
1247
2765
  int fixedTotal = 0;
@@ -1259,7 +2777,7 @@ private:
1259
2777
  }
1260
2778
  }
1261
2779
 
1262
- const int gapTotal = count > 1 ? (count - 1) * node_.style.gap : 0;
2780
+ const int gapTotal = count > 1 ? (count - 1) * gap : 0;
1263
2781
  int remaining = available - fixedTotal - gapTotal;
1264
2782
  if (remaining < 0) remaining = 0;
1265
2783
 
@@ -1281,20 +2799,41 @@ private:
1281
2799
  }
1282
2800
  }
1283
2801
 
1284
- int gridTrackTotalSize(int count, const int *sizes) const
2802
+ int gridTrackTotalSize(int count, const int *sizes, int gap) const
1285
2803
  {
1286
2804
  int total = 0;
1287
- for (int i = 0; i < count; ++i) total += sizes[i] + (i > 0 ? node_.style.gap : 0);
2805
+ for (int i = 0; i < count; ++i) total += sizes[i] + (i > 0 ? gap : 0);
1288
2806
  return total;
1289
2807
  }
1290
2808
 
1291
- int gridContentOffset(int available, int total, int alignment, int paddingBefore) const
2809
+ void stretchAutoGridTracks(int count, const int8_t *types, int *sizes,
2810
+ int available, int gap, int alignment) const
2811
+ {
2812
+ // CSS Grid track sizing, "Stretch auto Tracks": normal/stretch
2813
+ // distributes remaining space equally to auto tracks, not to items.
2814
+ if (alignment != 0) return;
2815
+ int free = available - gridTrackTotalSize(count, sizes, gap);
2816
+ int autoCount = 0;
2817
+ for (int i = 0; i < count; ++i) if (types[i] == 0) ++autoCount;
2818
+ if (free <= 0 || !autoCount) return;
2819
+ for (int i = 0; i < count; ++i) {
2820
+ if (types[i] != 0) continue;
2821
+ const int extra = free / autoCount;
2822
+ sizes[i] += extra;
2823
+ free -= extra;
2824
+ --autoCount;
2825
+ }
2826
+ }
2827
+
2828
+ int gridContentOffset(int available, int total, int alignment, int index, int count) const
1292
2829
  {
1293
2830
  int free = available - total;
2831
+ if (isDistributedAlignment(alignment)) return distributedAlignmentOffset(alignment, free, index, count);
2832
+ alignment = usedAlignment(alignment, free);
1294
2833
  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;
2834
+ if (alignment == 1) return free / 2;
2835
+ if (alignment == 2) return free;
2836
+ return 0;
1298
2837
  }
1299
2838
 
1300
2839
  void stretchGridChild(int child, Node &childNode, int cellWidth, int cellHeight, int alignX, int alignY)
@@ -1302,13 +2841,13 @@ private:
1302
2841
  bool resized = false;
1303
2842
  const int availableWidth = cellWidth - childNode.style.margin[1] - childNode.style.margin[3];
1304
2843
  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) {
2844
+ const int width = clampLayoutSize(childNode, availableWidth < 0 ? 0 : availableWidth, true);
2845
+ const int height = clampLayoutSize(childNode, availableHeight < 0 ? 0 : availableHeight, false);
2846
+ if (alignX == 0 && !(childNode.style.margin_auto & 10) && !hasExplicitWidth(childNode) && !isIntrinsicSizeExpression(childNode.style.width_expression) && childNode.layout.width != width) {
1308
2847
  childNode.layout.width = width;
1309
2848
  resized = true;
1310
2849
  }
1311
- if (alignY == 0 && !hasExplicitHeight(childNode) && childNode.layout.height != height) {
2850
+ if (alignY == 0 && !(childNode.style.margin_auto & 5) && !hasExplicitHeight(childNode) && !isIntrinsicSizeExpression(childNode.style.height_expression) && childNode.layout.height != height) {
1312
2851
  childNode.layout.height = height;
1313
2852
  resized = true;
1314
2853
  }
@@ -1317,14 +2856,87 @@ private:
1317
2856
 
1318
2857
  void layoutGridChildren(int *children, int childCount, int padWidth, int padHeight, bool allowAutosizeParent)
1319
2858
  {
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;
2859
+ #if GEA_CSS_GRID
2860
+ if (!childCount && !rstyle(node_.style).grid_column_count && !rstyle(node_.style).grid_row_count) {
2861
+ if (auto *rare = rareDataFor(id_)) rare->gridLayout.reset();
2862
+ if (allowAutosizeParent) autosizeEmptyNode();
2863
+ return;
2864
+ }
2865
+ const bool vertical = writingMode(node_) != 0;
2866
+ int columnCount = std::max(childCount ? 1 : 0, int(rstyle(node_.style).grid_column_count));
2867
+ int rowCount = std::max(childCount ? 1 : 0, int(rstyle(node_.style).grid_row_count));
2868
+ struct Placement { GridAxisPlacement column, row; };
2869
+ std::vector<Placement> placements(childCount);
2870
+ int columnOrigin = 0, rowOrigin = 0;
2871
+ for (int i = 0; i < childCount; ++i) {
2872
+ const auto &rs = rstyle(nodes_[children[i]].style);
2873
+ auto &p = placements[i];
2874
+ p.column = gridAxisPlacement(rs.grid_line[1], rs.grid_line[3], rstyle(node_.style).grid_column_count, false);
2875
+ p.row = gridAxisPlacement(rs.grid_line[0], rs.grid_line[2], rstyle(node_.style).grid_row_count, false);
2876
+ if (p.column.start != kUnset) columnOrigin = std::max(columnOrigin, -p.column.start);
2877
+ if (p.row.start != kUnset) rowOrigin = std::max(rowOrigin, -p.row.start);
2878
+ columnCount = std::max(columnCount, p.column.end == kUnset ? p.column.span : p.column.end);
2879
+ if (p.row.end != kUnset) rowCount = std::max(rowCount, p.row.end);
2880
+ }
2881
+ columnOrigin = std::min(columnOrigin, kMaxGridLayoutTracks - 1);
2882
+ rowOrigin = std::min(rowOrigin, kMaxGridLayoutTracks - 1);
2883
+ columnCount = std::min(kMaxGridLayoutTracks, columnCount + columnOrigin);
2884
+ rowCount = std::min(kMaxGridLayoutTracks, rowCount + rowOrigin);
2885
+ uint64_t occupied[kMaxGridLayoutTracks][2] = {};
2886
+ auto fits = [&](int row, int column, int rows, int columns) {
2887
+ if (row + rows > kMaxGridLayoutTracks || column + columns > kMaxGridLayoutTracks) return false;
2888
+ for (int y = row; y < row + rows; ++y)
2889
+ for (int x = column; x < column + columns; ++x)
2890
+ if (occupied[y][x / 64] & (uint64_t{1} << (x % 64))) return false;
2891
+ return true;
2892
+ };
2893
+ auto occupy = [&](Placement &p) {
2894
+ p.row.start = std::clamp(p.row.start, 0, kMaxGridLayoutTracks - p.row.span);
2895
+ p.column.start = std::clamp(p.column.start, 0, kMaxGridLayoutTracks - p.column.span);
2896
+ p.row.end = p.row.start + p.row.span;
2897
+ p.column.end = p.column.start + p.column.span;
2898
+ rowCount = std::max(rowCount, p.row.end);
2899
+ columnCount = std::max(columnCount, p.column.end);
2900
+ for (int y = p.row.start; y < p.row.end; ++y)
2901
+ for (int x = p.column.start; x < p.column.end; ++x)
2902
+ occupied[y][x / 64] |= uint64_t{1} << (x % 64);
2903
+ };
2904
+ for (auto &p : placements) {
2905
+ if (p.row.start != kUnset) p.row.start = std::clamp(p.row.start + rowOrigin, 0, kMaxGridLayoutTracks - p.row.span);
2906
+ if (p.column.start != kUnset) p.column.start = std::clamp(p.column.start + columnOrigin, 0, kMaxGridLayoutTracks - p.column.span);
2907
+ if (p.row.start != kUnset && p.column.start != kUnset) occupy(p);
2908
+ }
2909
+ int rowCursor[kMaxGridLayoutTracks] = {};
2910
+ for (auto &p : placements) {
2911
+ if (p.row.start == kUnset || p.column.start != kUnset) continue;
2912
+ int x = rowCursor[p.row.start];
2913
+ while (x + p.column.span < kMaxGridLayoutTracks && !fits(p.row.start, x, p.row.span, p.column.span)) ++x;
2914
+ p.column.start = x;
2915
+ occupy(p);
2916
+ rowCursor[p.row.start] = p.column.end;
2917
+ }
2918
+ int cursorRow = 0, cursorColumn = 0;
2919
+ for (auto &p : placements) {
2920
+ if (p.row.start != kUnset) continue;
2921
+ if (p.column.start != kUnset) {
2922
+ if (p.column.start < cursorColumn) ++cursorRow;
2923
+ cursorColumn = p.column.start;
2924
+ while (cursorRow + p.row.span < kMaxGridLayoutTracks && !fits(cursorRow, cursorColumn, p.row.span, p.column.span)) ++cursorRow;
2925
+ } else {
2926
+ while (cursorRow + p.row.span <= kMaxGridLayoutTracks) {
2927
+ if (cursorColumn + p.column.span > columnCount) { ++cursorRow; cursorColumn = 0; continue; }
2928
+ if (fits(cursorRow, cursorColumn, p.row.span, p.column.span)) break;
2929
+ ++cursorColumn;
2930
+ }
2931
+ p.column.start = cursorColumn;
2932
+ }
2933
+ p.row.start = cursorRow;
2934
+ occupy(p);
2935
+ cursorColumn = p.column.end;
2936
+ }
1327
2937
 
2938
+ const int columnGap = resolvedGap(node_, false, padWidth, padHeight);
2939
+ const int rowGap = resolvedGap(node_, true, padWidth, padHeight);
1328
2940
  measureGridChildren(children, childCount, padWidth, padHeight);
1329
2941
 
1330
2942
  int8_t columnTypes[kMaxGridLayoutTracks] = {0};
@@ -1332,78 +2944,148 @@ private:
1332
2944
  int16_t columnValues[kMaxGridLayoutTracks] = {0};
1333
2945
  int16_t rowValues[kMaxGridLayoutTracks] = {0};
1334
2946
  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;
2947
+ const int track = i - columnOrigin;
2948
+ columnTypes[i] = track >= 0 && track < rstyle(node_.style).grid_column_count ? rstyle(node_.style).grid_column_type[track] : 0;
2949
+ columnValues[i] = track >= 0 && track < rstyle(node_.style).grid_column_count ? rstyle(node_.style).grid_column_value[track] : 0;
1337
2950
  }
1338
2951
  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;
2952
+ const int track = i - rowOrigin;
2953
+ rowTypes[i] = track >= 0 && track < rstyle(node_.style).grid_row_count ? rstyle(node_.style).grid_row_type[track] : 0;
2954
+ rowValues[i] = track >= 0 && track < rstyle(node_.style).grid_row_count ? rstyle(node_.style).grid_row_value[track] : 0;
1341
2955
  }
1342
2956
 
1343
2957
  int autoColumns[kMaxGridLayoutTracks] = {0};
1344
2958
  int autoRows[kMaxGridLayoutTracks] = {0};
1345
- computeAutoTrackSizes(children, childCount, columnCount, rowCount, autoColumns, autoRows);
2959
+ // Resolve increasing span lengths. Contributions with the same span
2960
+ // share one set of base sizes and commit their maximum planned growth
2961
+ // together, so source order cannot bias overlapping spans.
2962
+ for (bool columns : {true, false}) {
2963
+ int *sizes = columns ? autoColumns : autoRows;
2964
+ const int8_t *types = columns ? columnTypes : rowTypes;
2965
+ const int16_t *values = columns ? columnValues : rowValues;
2966
+ const int gap = columns ? columnGap : rowGap;
2967
+ const int count = columns ? columnCount : rowCount;
2968
+ int maxSpan = 0;
2969
+ for (const auto &p : placements) maxSpan = std::max(maxSpan, columns ? p.column.span : p.row.span);
2970
+ for (int span = 1; span <= maxSpan; ++span) {
2971
+ int planned[kMaxGridLayoutTracks] = {};
2972
+ std::copy(sizes, sizes + count, planned);
2973
+ for (int i = 0; i < childCount; ++i) {
2974
+ const auto &p = columns ? placements[i].column : placements[i].row;
2975
+ if (p.span != span) continue;
2976
+ const Node &child = nodes_[children[i]];
2977
+ const bool horizontal = columns != vertical;
2978
+ const int size = horizontal ? child.layout.width + child.style.margin[1] + child.style.margin[3]
2979
+ : child.layout.height + child.style.margin[0] + child.style.margin[2];
2980
+ int occupied = (span - 1) * gap, autos = 0;
2981
+ for (int t = p.start; t < p.end; ++t) {
2982
+ occupied += types[t] == 1 ? values[t] : sizes[t];
2983
+ if (types[t] == 0) ++autos;
2984
+ }
2985
+ int extra = size - occupied;
2986
+ for (int t = p.start; t < p.end && extra > 0 && autos; ++t) {
2987
+ if (types[t] != 0) continue;
2988
+ const int amount = extra / autos;
2989
+ planned[t] = std::max(planned[t], sizes[t] + amount);
2990
+ extra -= amount; --autos;
2991
+ }
2992
+ }
2993
+ std::copy(planned, planned + count, sizes);
2994
+ }
2995
+ }
1346
2996
 
1347
2997
  int columnSizes[kMaxGridLayoutTracks] = {0};
1348
2998
  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;
2999
+ computeTrackSizes(columnCount, columnTypes, columnValues, autoColumns, vertical ? padHeight : padWidth, columnGap, columnSizes);
3000
+ computeTrackSizes(rowCount, rowTypes, rowValues, autoRows, vertical ? padWidth : padHeight, rowGap, rowSizes);
3001
+ if (allowAutosizeParent && !hasExplicitWidth(node_) &&
3002
+ rstyle(node_.style).grid_column_count == 0 && columnCount == 1 &&
3003
+ writingMode(node_) == 0 && node_.style.justify_content == 0) columnSizes[0] = padWidth;
1352
3004
 
1353
3005
  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);
3006
+ int width = boxInset(node_.style, 1) + boxInset(node_.style, 3);
3007
+ width += vertical ? gridTrackTotalSize(rowCount, rowSizes, rowGap) : gridTrackTotalSize(columnCount, columnSizes, columnGap);
3008
+ node_.layout.width = clampLayoutSize(node_, width, true);
1357
3009
  }
1358
3010
  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);
3011
+ int height = boxInset(node_.style, 0) + boxInset(node_.style, 2);
3012
+ height += vertical ? gridTrackTotalSize(columnCount, columnSizes, columnGap) : gridTrackTotalSize(rowCount, rowSizes, rowGap);
3013
+ node_.layout.height = clampLayoutSize(node_, height, false);
1362
3014
  }
3015
+ // Auto-height grids first derive their size from intrinsic tracks.
3016
+ // A definite size (including one assigned by the parent) can then
3017
+ // contribute free space without making an auto-sized grid fill its parent.
3018
+ padWidth = paddedWidth();
3019
+ padHeight = paddedHeight();
3020
+ stretchAutoGridTracks(columnCount, columnTypes, columnSizes, vertical ? padHeight : padWidth, columnGap, node_.style.justify_content);
3021
+ stretchAutoGridTracks(rowCount, rowTypes, rowSizes, vertical ? padWidth : padHeight, rowGap, node_.style.align_content);
1363
3022
 
1364
3023
  int rowY[kMaxGridLayoutTracks] = {0};
1365
3024
  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;
3025
+ const int columnTotal = gridTrackTotalSize(columnCount, columnSizes, columnGap);
3026
+ const int rowTotal = gridTrackTotalSize(rowCount, rowSizes, rowGap);
3027
+ int columnPosition = 0, rowPosition = 0;
3028
+ for (int i = 0; i < columnCount; ++i) {
3029
+ columnX[i] = columnPosition + gridContentOffset(vertical ? padHeight : padWidth, columnTotal, node_.style.justify_content, i, columnCount);
3030
+ columnPosition += columnSizes[i] + columnGap;
3031
+ }
3032
+ for (int i = 0; i < rowCount; ++i) {
3033
+ rowY[i] = rowPosition + gridContentOffset(vertical ? padWidth : padHeight, rowTotal, node_.style.align_content, i, rowCount);
3034
+ rowPosition += rowSizes[i] + rowGap;
3035
+ }
1380
3036
 
3037
+ auto &rare = ensureRareData(id_);
3038
+ if (!rare.gridLayout) rare.gridLayout = std::make_unique<GridTrackLayout>();
3039
+ auto &tracks = *rare.gridLayout;
3040
+ tracks.columnOrigin = columnOrigin; tracks.rowOrigin = rowOrigin;
3041
+ tracks.columnStart.assign(columnX, columnX + columnCount);
3042
+ tracks.rowStart.assign(rowY, rowY + rowCount);
3043
+ tracks.columnEnd.resize(columnCount); tracks.rowEnd.resize(rowCount);
3044
+ for (int i = 0; i < columnCount; ++i) tracks.columnEnd[i] = columnX[i] + columnSizes[i];
3045
+ for (int i = 0; i < rowCount; ++i) tracks.rowEnd[i] = rowY[i] + rowSizes[i];
1381
3046
  for (int i = 0; i < childCount; ++i) {
1382
- const int column = i % columnCount;
1383
- const int row = i / columnCount;
1384
- if (row >= rowCount) break;
3047
+ const auto &p = placements[i];
1385
3048
  const int child = children[i];
1386
3049
  Node &childNode = nodes_[child];
1387
- const int cellWidth = columnSizes[column];
1388
- const int cellHeight = rowSizes[row];
3050
+ int cellX, cellY, cellWidth, cellHeight;
3051
+ gridPhysicalRange(node_, true, columnX[p.column.start], tracks.columnEnd[p.column.end - 1], vertical ? cellY : cellX, vertical ? cellHeight : cellWidth);
3052
+ gridPhysicalRange(node_, false, rowY[p.row.start], tracks.rowEnd[p.row.end - 1], vertical ? cellX : cellY, vertical ? cellWidth : cellHeight);
1389
3053
  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;
3054
+ const int inlineAlign = (GEA_CSS_JUSTIFY_SELF ? rstyle(childNode.style).justify_self : -1) >= 0 ? (GEA_CSS_JUSTIFY_SELF ? rstyle(childNode.style).justify_self : -1) : node_.style.justify_items;
3055
+ const int blockAlign = childNode.style.align_self >= 0 ? childNode.style.align_self : node_.style.align_items;
3056
+ const int alignX = vertical ? blockAlign : inlineAlign;
3057
+ const int alignY = vertical ? inlineAlign : blockAlign;
1393
3058
  stretchGridChild(child, childNode, cellWidth, cellHeight, alignX, alignY);
1394
3059
 
1395
- int x = columnX[column] + childNode.style.margin[3];
1396
- int y = rowY[row] + childNode.style.margin[0];
3060
+ int x = cellX + childNode.style.margin[3];
3061
+ int y = cellY + childNode.style.margin[0];
1397
3062
  const int freeX = cellWidth - childNode.layout.width - childNode.style.margin[1] - childNode.style.margin[3];
1398
3063
  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;
3064
+ const int usedX = usedGridAlignment(node_, childNode, alignX, freeX, true);
3065
+ const int usedY = usedGridAlignment(node_, childNode, alignY, freeY, false);
3066
+ // Auto margins consume positive free space before self-alignment and
3067
+ // suppress it even when the item overflows the grid area.
3068
+ if (childNode.style.margin_auto & 10) {
3069
+ if (freeX > 0 && (childNode.style.margin_auto & 8))
3070
+ x += (childNode.style.margin_auto & 2) ? freeX / 2 : freeX;
3071
+ } else if (usedX == 1) x += freeX / 2;
3072
+ else if (usedX == 2) x += freeX;
3073
+ if (childNode.style.margin_auto & 5) {
3074
+ if (freeY > 0 && (childNode.style.margin_auto & 1))
3075
+ y += (childNode.style.margin_auto & 4) ? freeY / 2 : freeY;
3076
+ } else if (usedY == 1) y += freeY / 2;
3077
+ else if (usedY == 2) y += freeY;
1403
3078
  childNode.layout.x = x;
1404
3079
  childNode.layout.y = y;
1405
3080
  }
1406
- }
3081
+ #else
3082
+ (void)children;
3083
+ (void)childCount;
3084
+ (void)padWidth;
3085
+ (void)padHeight;
3086
+ (void)allowAutosizeParent;
3087
+ #endif
3088
+ }
1407
3089
 
1408
3090
  void prepareOwnSize()
1409
3091
  {
@@ -1415,31 +3097,40 @@ private:
1415
3097
  if (!hasExplicitHeight(node_)) {
1416
3098
  contentHeight -= node_.style.margin[0] + node_.style.margin[2];
1417
3099
  }
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
3100
 
1421
- node_.layout.width = contentWidth;
1422
- node_.layout.height = contentHeight;
3101
+ if (hasExplicitWidth(node_)) contentWidth = contentSizeToBorderSize(node_.style, contentWidth, true);
3102
+ if (hasExplicitHeight(node_)) contentHeight = contentSizeToBorderSize(node_.style, contentHeight, false);
3103
+ node_.layout.width = clampLayoutSize(node_, contentWidth, true);
3104
+ node_.layout.height = clampLayoutSize(node_, contentHeight, false);
3105
+ // Resolve a definite ratio-derived axis before measuring percentage
3106
+ // descendants. Final sizing can still grow to the content-based minimum.
3107
+ if (preferredRatio(node_) > 0) {
3108
+ if (hasExplicitWidth(node_) && !hasExplicitHeight(node_))
3109
+ node_.layout.height = clampLayoutSize(node_, ratioTransferredSize(node_, node_.layout.width, false), false);
3110
+ else if (hasExplicitHeight(node_) && !hasExplicitWidth(node_))
3111
+ node_.layout.width = clampLayoutSize(node_, ratioTransferredSize(node_, node_.layout.height, true), true);
3112
+ }
1423
3113
  }
1424
3114
 
1425
3115
  int paddedWidth() const
1426
3116
  {
1427
- int width = node_.layout.width - node_.style.padding[1] - node_.style.padding[3];
3117
+ int width = node_.layout.width - boxInset(node_.style, 1) - boxInset(node_.style, 3);
1428
3118
  return width < 0 ? 0 : width;
1429
3119
  }
1430
3120
 
1431
3121
  int paddedHeight() const
1432
3122
  {
1433
- int height = node_.layout.height - node_.style.padding[0] - node_.style.padding[2];
3123
+ int height = node_.layout.height - boxInset(node_.style, 0) - boxInset(node_.style, 2);
1434
3124
  return height < 0 ? 0 : height;
1435
3125
  }
1436
3126
 
1437
3127
  void autosizeEmptyNode()
1438
3128
  {
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);
3129
+ if (!hasExplicitWidth(node_)) node_.layout.width = boxInset(node_.style, 1) + boxInset(node_.style, 3);
3130
+ if (!hasExplicitHeight(node_)) node_.layout.height = boxInset(node_.style, 0) + boxInset(node_.style, 2);
3131
+ node_.layout.width = clampLayoutSize(node_, node_.layout.width, true);
3132
+ node_.layout.height = clampLayoutSize(node_, node_.layout.height, false);
3133
+ #if GEA_CSS_SCROLLING
1443
3134
  // A <virtual-list>'s scroll geometry is owned by
1444
3135
  // applyVirtualListContentHeight() (invoked right after this in the
1445
3136
  // empty-node branch). Its recycled slot pool is entirely
@@ -1453,10 +3144,12 @@ private:
1453
3144
  node_.layout.scroll_x = 0;
1454
3145
  node_.layout.scroll_y = 0;
1455
3146
  }
3147
+ #endif
1456
3148
  }
1457
3149
 
1458
3150
  void updateScrollContentSize()
1459
3151
  {
3152
+ #if GEA_CSS_SCROLLING
1460
3153
  // A <virtual-list>'s scroll geometry is owned by
1461
3154
  // applyVirtualListContentHeight() (scroll_content_height = itemCount *
1462
3155
  // rowHeight). Its real children are the recycled, position:absolute slot
@@ -1467,14 +3160,18 @@ private:
1467
3160
  if (node_.type == NodeType::VirtualList) return;
1468
3161
  int contentWidth = node_.layout.width;
1469
3162
  int contentHeight = node_.layout.height;
1470
- for (int child = node_.first_child; child >= 0; child = nodes_[child].next_sibling) {
3163
+ visitFormattingChildren(nodes_, id_, [&](int child) {
1471
3164
  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];
3165
+ if (isCollapsedFlexItem(childNode) || isDisplayNone(childNode.style) || isOutOfFlowPosition(childNode.style.position)) return;
3166
+ // A visible axis contributes descendant overflow; a clipping axis
3167
+ // traps it at this child's border box independently of the other axis.
3168
+ const int width = overflowX(childNode.style) == 0 ? std::max<int>(childNode.layout.width, childNode.layout.scroll_content_width) : childNode.layout.width;
3169
+ const int height = overflowY(childNode.style) == 0 ? std::max<int>(childNode.layout.height, childNode.layout.scroll_content_height) : childNode.layout.height;
3170
+ const int right = childNode.layout.x + width + childNode.style.margin[1] + boxInset(node_.style, 1);
1474
3171
  if (right > contentWidth) contentWidth = right;
1475
- const int bottom = childNode.layout.y + childNode.layout.height + childNode.style.margin[2] + node_.style.padding[2];
3172
+ const int bottom = childNode.layout.y + height + childNode.style.margin[2] + boxInset(node_.style, 2);
1476
3173
  if (bottom > contentHeight) contentHeight = bottom;
1477
- }
3174
+ });
1478
3175
  node_.layout.scroll_content_width = contentWidth;
1479
3176
  node_.layout.scroll_content_height = contentHeight;
1480
3177
 
@@ -1495,7 +3192,10 @@ private:
1495
3192
  if (node_.layout.scroll_y < 0) node_.layout.scroll_y = 0;
1496
3193
  if (node_.layout.scroll_y > maxScroll) node_.layout.scroll_y = maxScroll;
1497
3194
  }
1498
- }
3195
+ #else
3196
+
3197
+ #endif
3198
+ }
1499
3199
 
1500
3200
  // A <virtual-list> only materializes a small pool of real child slot nodes
1501
3201
  // but scrolls over a virtual content height of itemCount * rowHeight. The
@@ -1503,6 +3203,7 @@ private:
1503
3203
  // controls it purely through the template's stylesheet.
1504
3204
  void applyVirtualListContentHeight()
1505
3205
  {
3206
+ #if GEA_CSS_SCROLLING
1506
3207
  if (node_.type != NodeType::VirtualList) return;
1507
3208
  int rowHeight = 0;
1508
3209
  for (int child = node_.first_child; child >= 0; child = nodes_[child].next_sibling) {
@@ -1519,16 +3220,55 @@ private:
1519
3220
  if (maxScroll < 0) maxScroll = 0;
1520
3221
  if (node_.layout.scroll_y < 0) node_.layout.scroll_y = 0;
1521
3222
  if (node_.layout.scroll_y > maxScroll) node_.layout.scroll_y = maxScroll;
3223
+ #else
3224
+
3225
+ #endif
3226
+ }
3227
+
3228
+ void captureBlockStaticPositions()
3229
+ {
3230
+ for (int c = node_.first_child; c >= 0; c = nodes_[c].next_sibling)
3231
+ if (isOutOfFlowPosition(nodes_[c].style.position)) nodes_[c].layout.static_block_axis = 0;
3232
+ if (node_.style.display != kDisplayBlock || node_.style.flex_direction_explicit ||
3233
+ (LayoutEngine::isInlineLevelNode(node_) && !isOutOfFlowPosition(node_.style.position))) return;
3234
+ const bool vertical = writingMode(node_) != 0;
3235
+ const bool reversed = vertical && gridAxisReversed(node_, true);
3236
+ int cursor = boxInset(node_.style, blockMarginSide(false));
3237
+ bool first = true;
3238
+ CollapsedMargin pending;
3239
+ visitFormattingChildren(nodes_, id_, [&](int id) {
3240
+ Node &child = nodes_[id];
3241
+ if (isDisplayNone(child.style)) return;
3242
+ if (isOutOfFlowPosition(child.style.position)) {
3243
+ if (child.parent != id_ || !blockBox(child)) return;
3244
+ const int edge = cursor + (first && collapsesWithChildren(id_, false) ? 0 : pending.value());
3245
+ child.layout.static_block_start = clampInt16(reversed ? node_.layout.width - edge : edge);
3246
+ child.layout.static_block_axis = vertical ? 2 : 1;
3247
+ return;
3248
+ }
3249
+ if (child.style.float_side || suppressAnonymousWhitespace(nodes_, child.parent, id)) return;
3250
+ if (blockBox(child) && collapsesThrough(id)) {
3251
+ pending.add(childEdgeMargin(id_, id, false));
3252
+ return;
3253
+ }
3254
+ const int end = vertical ? (reversed ? node_.layout.width - child.layout.x : child.layout.x + child.layout.width)
3255
+ : child.layout.y + child.layout.height;
3256
+ cursor = blockBox(child) ? end : std::max(cursor, end);
3257
+ pending = blockBox(child) ? childEdgeMargin(id_, id, true) : CollapsedMargin{};
3258
+ first = false;
3259
+ });
1522
3260
  }
1523
3261
 
1524
3262
  void positionAbsoluteChildren()
1525
3263
  {
3264
+ captureBlockStaticPositions();
1526
3265
  for (int child = node_.first_child; child >= 0; child = nodes_[child].next_sibling) {
1527
3266
  Node &childNode = nodes_[child];
1528
- if (isDisplayNone(childNode.style) || childNode.style.position != 1) continue;
3267
+ if (isDisplayNone(childNode.style) || !isOutOfFlowPosition(childNode.style.position)) continue;
1529
3268
 
1530
- const int childAvailWidth = node_.layout.width;
1531
- const int childAvailHeight = node_.layout.height;
3269
+ int childAvailWidth, childAvailHeight;
3270
+ int areaX, areaY;
3271
+ LayoutEngine::absoluteContainingArea(node_, childNode, areaX, areaY, childAvailWidth, childAvailHeight);
1532
3272
  engine_.layoutNode(child, childAvailWidth, childAvailHeight);
1533
3273
  stretchAbsoluteChild(child, childNode, childAvailWidth, childAvailHeight);
1534
3274
  positionAbsoluteChild(childNode);
@@ -1538,26 +3278,26 @@ private:
1538
3278
  void stretchAbsoluteChild(int child, Node &childNode, int childAvailWidth, int childAvailHeight)
1539
3279
  {
1540
3280
  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) -
3281
+ if (!hasExplicitWidth(childNode) && !isIntrinsicSizeExpression(childNode.style.width_expression) &&
3282
+ hasPositionOffset<3>(childNode) &&
3283
+ hasPositionOffset<1>(childNode)) {
3284
+ int width = childAvailWidth - resolvedPositionOffsetWithBasis<3>(childNode, childAvailWidth) - resolvedPositionOffsetWithBasis<1>(childNode, childAvailWidth) -
1545
3285
  childNode.style.margin[1] - childNode.style.margin[3];
1546
3286
  if (width < 0) width = 0;
1547
- width = engine_.clampSize(width, childNode.style.min_width, childNode.style.max_width);
3287
+ width = clampLayoutSize(childNode, width, true);
1548
3288
  if (childNode.layout.width != width) {
1549
3289
  childNode.layout.width = width;
1550
3290
  resized = true;
1551
3291
  }
1552
3292
  }
1553
3293
 
1554
- if (!hasExplicitHeight(childNode) &&
1555
- hasPositionOffset(childNode, 0) &&
1556
- hasPositionOffset(childNode, 2)) {
1557
- int height = childAvailHeight - resolvedPositionOffset(childNode, 0) - resolvedPositionOffset(childNode, 2) -
3294
+ if (!hasExplicitHeight(childNode) && !isIntrinsicSizeExpression(childNode.style.height_expression) &&
3295
+ hasPositionOffset<0>(childNode) &&
3296
+ hasPositionOffset<2>(childNode)) {
3297
+ int height = childAvailHeight - resolvedPositionOffsetWithBasis<0>(childNode, childAvailHeight) - resolvedPositionOffsetWithBasis<2>(childNode, childAvailHeight) -
1558
3298
  childNode.style.margin[0] - childNode.style.margin[2];
1559
3299
  if (height < 0) height = 0;
1560
- height = engine_.clampSize(height, childNode.style.min_height, childNode.style.max_height);
3300
+ height = clampLayoutSize(childNode, height, false);
1561
3301
  if (childNode.layout.height != height) {
1562
3302
  childNode.layout.height = height;
1563
3303
  resized = true;
@@ -1569,83 +3309,68 @@ private:
1569
3309
 
1570
3310
  void positionAbsoluteChild(Node &childNode)
1571
3311
  {
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);
3312
+ int x, y, width, height;
3313
+ LayoutEngine::absoluteContainingArea(node_, childNode, x, y, width, height);
3314
+ if (hasPositionOffset<3>(childNode)) childNode.layout.x = x + resolvedPositionOffsetWithBasis<3>(childNode, width) + childNode.style.margin[3];
3315
+ else if (hasPositionOffset<1>(childNode)) childNode.layout.x = x + width - childNode.layout.width - resolvedPositionOffsetWithBasis<1>(childNode, width) - childNode.style.margin[1];
3316
+ else childNode.layout.x = alignedAbsoluteChildPosition(childNode, true);
3317
+ if (hasPositionOffset<0>(childNode)) childNode.layout.y = y + resolvedPositionOffsetWithBasis<0>(childNode, height) + childNode.style.margin[0];
3318
+ else if (hasPositionOffset<2>(childNode)) childNode.layout.y = y + height - childNode.layout.height - resolvedPositionOffsetWithBasis<2>(childNode, height) - childNode.style.margin[2];
3319
+ else childNode.layout.y = alignedAbsoluteChildPosition(childNode, false);
1585
3320
  }
1586
3321
 
1587
3322
  int alignedAbsoluteChildPosition(const Node &childNode, bool horizontal) const
1588
3323
  {
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;
3324
+ return LayoutEngine::alignedAbsoluteOffset(node_, childNode, horizontal);
1608
3325
  }
1609
3326
 
1610
3327
  void applyRelativeOffsets()
1611
3328
  {
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
- }
3329
+ auto apply = [&](auto &&self, int parent) -> void {
3330
+ for (int child = nodes_[parent].first_child; child >= 0; child = nodes_[child].next_sibling) {
3331
+ Node &childNode = nodes_[child];
3332
+ if (splitInlineChildren_ && splitInlineWrapper(nodes_, child)) self(self, child);
3333
+ if (childNode.style.position != 2) continue;
3334
+ if (hasPositionOffset<0>(childNode))
3335
+ childNode.layout.y += resolvedRelativePositionOffset<0>(childNode);
3336
+ else if (hasPositionOffset<2>(childNode))
3337
+ childNode.layout.y -= resolvedRelativePositionOffset<2>(childNode);
3338
+ if (hasPositionOffset<3>(childNode))
3339
+ childNode.layout.x += resolvedRelativePositionOffset<3>(childNode);
3340
+ else if (hasPositionOffset<1>(childNode))
3341
+ childNode.layout.x -= resolvedRelativePositionOffset<1>(childNode);
3342
+ }
3343
+ };
3344
+ apply(apply, id_);
1624
3345
  }
1625
3346
 
1626
- bool hasPositionOffset(const Node &node, int side) const
3347
+ template <int side>
3348
+ bool hasPositionOffset(const Node &node) const
1627
3349
  {
1628
- return node.style.pos_offsets[side] != kUnset || node.style.pos_offset_percent[side] != kUnset;
3350
+ return GEA_CSS_POSITION_PX(node.style, side) != kUnset || GEA_CSS_POSITION_PERCENT(node.style, side) != kUnset;
1629
3351
  }
1630
3352
 
1631
- int resolvedPositionOffset(const Node &node, int side) const
3353
+ template <int side>
3354
+ int resolvedPositionOffset(const Node &node) const
1632
3355
  {
1633
- return resolvedPositionOffsetWithBasis(node, side, (side == 0 || side == 2) ? node_.layout.height : node_.layout.width);
3356
+ return resolvedPositionOffsetWithBasis<side>(node, (side == 0 || side == 2) ? node_.layout.height : node_.layout.width);
1634
3357
  }
1635
3358
 
1636
- int resolvedRelativePositionOffset(const Node &node, int side) const
3359
+ template <int side>
3360
+ int resolvedRelativePositionOffset(const Node &node) const
1637
3361
  {
1638
3362
  int basis = (side == 0 || side == 2) ? node_.layout.height : node_.layout.width;
1639
3363
  if (isDisplayGrid(node_.style)) {
1640
3364
  basis = (side == 0 || side == 2) ? node.layout.height : node.layout.width;
1641
3365
  }
1642
- return resolvedPositionOffsetWithBasis(node, side, basis);
3366
+ return resolvedPositionOffsetWithBasis<side>(node, basis);
1643
3367
  }
1644
3368
 
1645
- int resolvedPositionOffsetWithBasis(const Node &node, int side, int percentBasis) const
3369
+ template <int side>
3370
+ int resolvedPositionOffsetWithBasis(const Node &node, int percentBasis) const
1646
3371
  {
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];
3372
+ int offset = GEA_CSS_POSITION_PX(node.style, side) != kUnset ? GEA_CSS_POSITION_PX(node.style, side) : 0;
3373
+ const int percent = GEA_CSS_POSITION_PERCENT(node.style, side);
1649
3374
  if (percent != kUnset) {
1650
3375
  const int numerator = percentBasis * percent;
1651
3376
  offset += (numerator + (numerator >= 0 ? 500 : -500)) / 1000;
@@ -1661,28 +3386,45 @@ private:
1661
3386
  Node &node_;
1662
3387
  };
1663
3388
 
3389
+ bool establishesTransformContainingBlock(const Node &node)
3390
+ {
3391
+ if (!ViewRenderer::isTransformableBox(node)) return false;
3392
+ const auto &r = rstyle(node.style);
3393
+ return r.translate_present || r.transform_present || r.rotate_present || r.scale_present || r.filter_present || r.transform_preserve_3d ||
3394
+ r.transform_rotate || r.transform_rotate_x || r.transform_rotate_y ||
3395
+ composedTranslateX(r) || composedTranslateY(r) || composedTranslateZ(r) ||
3396
+ composedTranslateXPercent(r) || composedTranslateYPercent(r) ||
3397
+ r.transform_scale_x != 1000 || r.transform_scale_y != 1000 || r.transform_scale_z != 1000 || r.perspective || r.filter_blur_radius;
3398
+ }
3399
+
1664
3400
  bool establishesAbsoluteContainingBlock(const Node &node)
1665
3401
  {
1666
- return node.style.position == 1 || node.style.position == 2;
3402
+ return isOutOfFlowPosition(node.style.position) || node.style.position == 2 || establishesTransformContainingBlock(node);
1667
3403
  }
1668
3404
 
1669
3405
  int containingBlockForAbsoluteNode(int node, int root, Node *nodes)
1670
3406
  {
3407
+ if (nodes[node].style.position == kPositionFixed) {
3408
+ const int fixed = LayoutEngine::fixedContainingBlock(nodes[node]);
3409
+ return fixed >= 0 ? fixed : root;
3410
+ }
1671
3411
  for (int cursor = nodes[node].parent; cursor >= 0; cursor = nodes[cursor].parent) {
1672
3412
  if (establishesAbsoluteContainingBlock(nodes[cursor])) return cursor;
1673
3413
  }
1674
3414
  return root;
1675
3415
  }
1676
3416
 
1677
- bool hasPositionOffsetValue(const Node &node, int side)
3417
+ template <int side>
3418
+ bool hasPositionOffsetValue(const Node &node)
1678
3419
  {
1679
- return node.style.pos_offsets[side] != kUnset || node.style.pos_offset_percent[side] != kUnset;
3420
+ return GEA_CSS_POSITION_PX(node.style, side) != kUnset || GEA_CSS_POSITION_PERCENT(node.style, side) != kUnset;
1680
3421
  }
1681
3422
 
1682
- int resolvedPositionOffsetForBasis(const Node &node, int side, int percentBasis)
3423
+ template <int side>
3424
+ int resolvedPositionOffsetForBasis(const Node &node, int percentBasis)
1683
3425
  {
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];
3426
+ int offset = GEA_CSS_POSITION_PX(node.style, side) != kUnset ? GEA_CSS_POSITION_PX(node.style, side) : 0;
3427
+ const int percent = GEA_CSS_POSITION_PERCENT(node.style, side);
1686
3428
  if (percent != kUnset) {
1687
3429
  const int numerator = percentBasis * percent;
1688
3430
  offset += (numerator + (numerator >= 0 ? 500 : -500)) / 1000;
@@ -1709,30 +3451,30 @@ void stretchAbsoluteNodeToContainingBlock(int node, int containingWidth, int con
1709
3451
  {
1710
3452
  Node &absolute = nodes[node];
1711
3453
  bool resized = false;
1712
- if (!hasExplicitWidth(absolute) &&
1713
- hasPositionOffsetValue(absolute, 3) &&
1714
- hasPositionOffsetValue(absolute, 1)) {
3454
+ if (!hasExplicitWidth(absolute) && !isIntrinsicSizeExpression(absolute.style.width_expression) &&
3455
+ hasPositionOffsetValue<3>(absolute) &&
3456
+ hasPositionOffsetValue<1>(absolute)) {
1715
3457
  int width = containingWidth -
1716
- resolvedPositionOffsetForBasis(absolute, 3, containingWidth) -
1717
- resolvedPositionOffsetForBasis(absolute, 1, containingWidth) -
3458
+ resolvedPositionOffsetForBasis<3>(absolute, containingWidth) -
3459
+ resolvedPositionOffsetForBasis<1>(absolute, containingWidth) -
1718
3460
  absolute.style.margin[1] - absolute.style.margin[3];
1719
3461
  if (width < 0) width = 0;
1720
- width = LayoutEngine::instance().clampSize(width, absolute.style.min_width, absolute.style.max_width);
3462
+ width = clampLayoutSize(absolute, width, true);
1721
3463
  if (absolute.layout.width != width) {
1722
3464
  absolute.layout.width = width;
1723
3465
  resized = true;
1724
3466
  }
1725
3467
  }
1726
3468
 
1727
- if (!hasExplicitHeight(absolute) &&
1728
- hasPositionOffsetValue(absolute, 0) &&
1729
- hasPositionOffsetValue(absolute, 2)) {
3469
+ if (!hasExplicitHeight(absolute) && !isIntrinsicSizeExpression(absolute.style.height_expression) &&
3470
+ hasPositionOffsetValue<0>(absolute) &&
3471
+ hasPositionOffsetValue<2>(absolute)) {
1730
3472
  int height = containingHeight -
1731
- resolvedPositionOffsetForBasis(absolute, 0, containingHeight) -
1732
- resolvedPositionOffsetForBasis(absolute, 2, containingHeight) -
3473
+ resolvedPositionOffsetForBasis<0>(absolute, containingHeight) -
3474
+ resolvedPositionOffsetForBasis<2>(absolute, containingHeight) -
1733
3475
  absolute.style.margin[0] - absolute.style.margin[2];
1734
3476
  if (height < 0) height = 0;
1735
- height = LayoutEngine::instance().clampSize(height, absolute.style.min_height, absolute.style.max_height);
3477
+ height = clampLayoutSize(absolute, height, false);
1736
3478
  if (absolute.layout.height != height) {
1737
3479
  absolute.layout.height = height;
1738
3480
  resized = true;
@@ -1742,49 +3484,120 @@ void stretchAbsoluteNodeToContainingBlock(int node, int containingWidth, int con
1742
3484
  if (resized) LayoutEngine::instance().repositionChildren(node);
1743
3485
  }
1744
3486
 
3487
+ void layoutAbsoluteNode(int node, int containing, int areaX, int areaWidth, int areaHeight, Node *nodes)
3488
+ {
3489
+ Node &absolute = nodes[node];
3490
+ auto &engine = LayoutEngine::instance();
3491
+ const bool left = hasPositionOffsetValue<3>(absolute), right = hasPositionOffsetValue<1>(absolute);
3492
+ if (absolute.type != NodeType::View || writingMode(absolute) != 0 ||
3493
+ hasExplicitWidth(absolute) || isIntrinsicSizeExpression(absolute.style.width_expression) ||
3494
+ (left && right) || (preferredRatio(absolute) > 0 && hasExplicitHeight(absolute))) {
3495
+ engine.layoutNode(node, areaWidth, areaHeight);
3496
+ return;
3497
+ }
3498
+ // Auto inline sizes shrink to fit the space from their resolved inset (or
3499
+ // static position) to the opposite containing-block edge. Keep the actual
3500
+ // containing width for percentages during the final used-width layout.
3501
+ IntrinsicSizeScope scope(absolute, 1);
3502
+ engine.layoutNode(node, 1, areaHeight, true);
3503
+ const int minimum = std::max(0, absolute.layout.width - boxInsets(absolute.style, true));
3504
+ scope.constraint = 2;
3505
+ engine.layoutNode(node, 32767, areaHeight, true);
3506
+ const int maximum = std::max(minimum, absolute.layout.width - boxInsets(absolute.style, true));
3507
+ #if GEA_CSS_BOX_EXPRESSIONS
3508
+ resolveLayoutBoxLengths(node, areaWidth);
3509
+ #endif
3510
+ int available = areaWidth - absolute.style.margin[3] - absolute.style.margin[1];
3511
+ if (left || right) {
3512
+ available -= (left ? resolvedPositionOffsetForBasis<3>(absolute, areaWidth) : resolvedPositionOffsetForBasis<1>(absolute, areaWidth));
3513
+ } else {
3514
+ int parentX = 0, parentY = 0;
3515
+ offsetFromAncestorToNode(containing, absolute.parent, nodes, &parentX, &parentY);
3516
+ const int staticX = parentX + engine.alignedAbsoluteOffset(nodes[absolute.parent], absolute, true);
3517
+ available = rightToLeft(nodes[absolute.parent])
3518
+ ? staticX + absolute.layout.width - areaX - absolute.style.margin[3]
3519
+ : areaX + areaWidth - staticX - absolute.style.margin[1];
3520
+ }
3521
+ const int edges = boxInsets(absolute.style, true);
3522
+ scope.borderSize = edges + std::min(maximum, std::max(minimum, available - edges));
3523
+ scope.constraint = 0;
3524
+ engine.layoutNode(node, areaWidth, areaHeight);
3525
+ }
3526
+
1745
3527
  void positionAbsoluteNodeInContainingBlock(int node, int containing, Node *nodes)
1746
3528
  {
1747
3529
  Node &absolute = nodes[node];
1748
3530
  const Node &containingNode = nodes[containing];
1749
3531
  const int parent = absolute.parent;
1750
3532
  if (parent < 0) return;
3533
+ if (LayoutEngine::isViewportFixed(absolute)) {
3534
+ const int width = containingNode.layout.memo_avail_w;
3535
+ const int height = containingNode.layout.memo_avail_h;
3536
+ LayoutEngine::instance().layoutNode(node, width, height);
3537
+ stretchAbsoluteNodeToContainingBlock(node, width, height, nodes);
3538
+ int staticX = LayoutEngine::alignedAbsoluteOffset(nodes[parent], absolute, true);
3539
+ int staticY = LayoutEngine::alignedAbsoluteOffset(nodes[parent], absolute, false);
3540
+ for (int id = parent; id >= 0; id = nodes[id].parent) {
3541
+ staticX += nodes[id].layout.x; staticY += nodes[id].layout.y;
3542
+ if (LayoutEngine::isViewportFixed(nodes[id])) break;
3543
+ }
3544
+ absolute.layout.x = hasPositionOffsetValue<3>(absolute) ? resolvedPositionOffsetForBasis<3>(absolute, width) + absolute.style.margin[3]
3545
+ : hasPositionOffsetValue<1>(absolute) ? width - absolute.layout.width - resolvedPositionOffsetForBasis<1>(absolute, width) - absolute.style.margin[1] : staticX;
3546
+ absolute.layout.y = hasPositionOffsetValue<0>(absolute) ? resolvedPositionOffsetForBasis<0>(absolute, height) + absolute.style.margin[0]
3547
+ : hasPositionOffsetValue<2>(absolute) ? height - absolute.layout.height - resolvedPositionOffsetForBasis<2>(absolute, height) - absolute.style.margin[2] : staticY;
3548
+ return;
3549
+ }
1751
3550
 
1752
- stretchAbsoluteNodeToContainingBlock(node, containingNode.layout.width, containingNode.layout.height, nodes);
1753
-
1754
- int parentOffsetX = 0;
1755
- int parentOffsetY = 0;
3551
+ int areaX, areaY, areaWidth, areaHeight;
3552
+ LayoutEngine::absoluteContainingArea(containingNode, absolute, areaX, areaY, areaWidth, areaHeight);
3553
+ // The provisional parent pass may have measured this box against a static
3554
+ // wrapper (or an as-yet-unsized grid). Resolve dimensions using the same
3555
+ // final containing block that supplies its insets. The static-position
3556
+ // rectangle still comes from the parent, but alignment must use the final
3557
+ // dimensions (for example, a percentage-sized child centered in a grid
3558
+ // whose containing block is an outer positioned ancestor).
3559
+ layoutAbsoluteNode(node, containing, areaX, areaWidth, areaHeight, nodes);
3560
+ stretchAbsoluteNodeToContainingBlock(node, areaWidth, areaHeight, nodes);
3561
+ int parentOffsetX = 0, parentOffsetY = 0;
1756
3562
  offsetFromAncestorToNode(containing, parent, nodes, &parentOffsetX, &parentOffsetY);
3563
+ if (!hasPositionOffsetValue<3>(absolute) && !hasPositionOffsetValue<1>(absolute))
3564
+ absolute.layout.x = LayoutEngine::alignedAbsoluteOffset(nodes[parent], absolute, true, &containingNode, areaX - parentOffsetX, areaWidth);
3565
+ if (!hasPositionOffsetValue<0>(absolute) && !hasPositionOffsetValue<2>(absolute))
3566
+ absolute.layout.y = LayoutEngine::alignedAbsoluteOffset(nodes[parent], absolute, false, &containingNode, areaY - parentOffsetY, areaHeight);
1757
3567
 
1758
3568
  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);
3569
+ if (hasPositionOffsetValue<3>(absolute))
3570
+ containingX = areaX + resolvedPositionOffsetForBasis<3>(absolute, areaWidth) + absolute.style.margin[3];
3571
+ else if (hasPositionOffsetValue<1>(absolute))
3572
+ containingX = areaX + areaWidth - absolute.layout.width -
3573
+ resolvedPositionOffsetForBasis<1>(absolute, areaWidth) - absolute.style.margin[1];
1764
3574
 
1765
3575
  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);
3576
+ if (hasPositionOffsetValue<0>(absolute))
3577
+ containingY = areaY + resolvedPositionOffsetForBasis<0>(absolute, areaHeight) + absolute.style.margin[0];
3578
+ else if (hasPositionOffsetValue<2>(absolute))
3579
+ containingY = areaY + areaHeight - absolute.layout.height -
3580
+ resolvedPositionOffsetForBasis<2>(absolute, areaHeight) - absolute.style.margin[2];
1771
3581
 
1772
3582
  absolute.layout.x = containingX - parentOffsetX;
1773
3583
  absolute.layout.y = containingY - parentOffsetY;
1774
3584
  }
1775
3585
 
1776
- void resolveAbsoluteContainingBlocks(int root)
3586
+ void resolvePositionedDescendants(int node, int root, Node *nodes)
1777
3587
  {
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);
3588
+ for (int child = nodes[node].first_child; child >= 0; child = nodes[child].next_sibling) {
3589
+ if (isDisplayNone(nodes[child].style)) continue;
3590
+ if (isOutOfFlowPosition(nodes[child].style.position))
3591
+ positionAbsoluteNodeInContainingBlock(child, containingBlockForAbsoluteNode(child, root, nodes), nodes);
3592
+ resolvePositionedDescendants(child, root, nodes);
1785
3593
  }
1786
3594
  }
1787
3595
 
3596
+ void resolveAbsoluteContainingBlocks(int root)
3597
+ {
3598
+ resolvePositionedDescendants(root, root, Tree::instance().nodes());
3599
+ }
3600
+
1788
3601
  } // namespace
1789
3602
 
1790
3603
  LayoutEngine &LayoutEngine::instance()
@@ -1793,6 +3606,236 @@ LayoutEngine &LayoutEngine::instance()
1793
3606
  return engine;
1794
3607
  }
1795
3608
 
3609
+ int LayoutEngine::fixedContainingBlock(const Node &node)
3610
+ {
3611
+ const Node *nodes = Tree::instance().nodes();
3612
+ for (int id = node.parent; id >= 0; id = nodes[id].parent) {
3613
+ if (establishesTransformContainingBlock(nodes[id])) return id;
3614
+ }
3615
+ return -1;
3616
+ }
3617
+
3618
+ bool LayoutEngine::isViewportFixed(const Node &node)
3619
+ {
3620
+ return node.style.position == kPositionFixed && fixedContainingBlock(node) < 0;
3621
+ }
3622
+
3623
+ bool LayoutEngine::containsViewportFixed(int node)
3624
+ {
3625
+ if (!treeState().fixedPositionUsed) return false;
3626
+ const Node *nodes = Tree::instance().nodes();
3627
+ if (isViewportFixed(nodes[node])) return true;
3628
+ for (int child = nodes[node].first_child; child >= 0; child = nodes[child].next_sibling)
3629
+ if (containsViewportFixed(child)) return true;
3630
+ return false;
3631
+ }
3632
+
3633
+ void LayoutEngine::absoluteContainingArea(const Node &parent, const Node &child, int &x, int &y, int &width, int &height)
3634
+ {
3635
+ x = y = 0;
3636
+ width = parent.layout.width; height = parent.layout.height;
3637
+ if (isDocumentCanvasRoot(parent) && !establishesAbsoluteContainingBlock(parent)) {
3638
+ // The initial containing block is viewport-sized, even when the HTML
3639
+ // element has an auto height, margins, or an explicit smaller size.
3640
+ x = -parent.layout.x; y = -parent.layout.y;
3641
+ width = parent.layout.memo_avail_w; height = parent.layout.memo_avail_h;
3642
+ return;
3643
+ }
3644
+ if (establishesAbsoluteContainingBlock(parent) || child.style.position == kPositionFixed) {
3645
+ // Insets and percentages reference the padding box, excluding borders.
3646
+ x = boxInset(parent.style, 3) - parent.style.padding[3];
3647
+ y = boxInset(parent.style, 0) - parent.style.padding[0];
3648
+ width = std::max(0, width - x - boxInset(parent.style, 1) + parent.style.padding[1]);
3649
+ height = std::max(0, height - y - boxInset(parent.style, 2) + parent.style.padding[2]);
3650
+ }
3651
+ absoluteGridArea(parent, child, x, y, width, height);
3652
+ }
3653
+
3654
+ bool LayoutEngine::absoluteGridArea(const Node &parent, const Node &child, int &x, int &y, int &width, int &height)
3655
+ {
3656
+ #if GEA_CSS_GRID
3657
+ if (!isDisplayGrid(parent.style)) return false;
3658
+ if (child.style.position == kPositionFixed) {
3659
+ if (fixedContainingBlock(child) != &parent - Tree::instance().nodes()) return false;
3660
+ } else if (!establishesAbsoluteContainingBlock(parent)) return false;
3661
+ const auto *rare = rareDataFor(static_cast<int>(&parent - Tree::instance().nodes()));
3662
+ const GridTrackLayout *tracks = rare ? rare->gridLayout.get() : nullptr;
3663
+ const bool vertical = writingMode(parent) != 0;
3664
+ for (bool columns : {true, false}) {
3665
+ const bool horizontal = columns != vertical;
3666
+ const int explicitCount = columns ? rstyle(parent.style).grid_column_count : rstyle(parent.style).grid_row_count;
3667
+ const auto &lines = rstyle(child.style).grid_line;
3668
+ const std::vector<int> *starts = tracks ? (columns ? &tracks->columnStart : &tracks->rowStart) : nullptr;
3669
+ const std::vector<int> *ends = tracks ? (columns ? &tracks->columnEnd : &tracks->rowEnd) : nullptr;
3670
+ const int origin = tracks ? (columns ? tracks->columnOrigin : tracks->rowOrigin) : 0;
3671
+ const int count = starts ? static_cast<int>(starts->size()) : 0;
3672
+ auto existing = [origin, count](int line) { return line != kUnset && line + origin >= 0 && line + origin <= count; };
3673
+ // Invalid absolute line references become auto before a dependent span
3674
+ // is resolved; otherwise an absent end line could invent a start line.
3675
+ auto validLine = [&](int value) {
3676
+ if (!value || value >= kGridLineSpan) return value;
3677
+ const int index = value > 0 ? value - 1 : explicitCount + 1 + value;
3678
+ return existing(index) ? value : 0;
3679
+ };
3680
+ auto placement = gridAxisPlacement(validLine(lines[columns ? 1 : 0]), validLine(lines[columns ? 3 : 2]), explicitCount, true);
3681
+ const bool hasStart = existing(placement.start), hasEnd = existing(placement.end);
3682
+ const int available = (horizontal ? parent.layout.width : parent.layout.height) - boxInsets(parent.style, horizontal);
3683
+ int beforeSide = horizontal ? 3 : 0, afterSide = horizontal ? 1 : 2;
3684
+ if (gridAxisReversed(parent, horizontal)) std::swap(beforeSide, afterSide);
3685
+ int start = -parent.style.padding[beforeSide], end = available + parent.style.padding[afterSide];
3686
+ if (hasStart) {
3687
+ const int index = placement.start + origin;
3688
+ start = count == 0 ? 0 : index == count ? ends->back() : (*starts)[index];
3689
+ }
3690
+ if (hasEnd) {
3691
+ const int index = placement.end + origin;
3692
+ end = count == 0 ? 0 : index == 0 ? starts->front() : (*ends)[index - 1];
3693
+ }
3694
+ gridPhysicalRange(parent, columns, start, std::max(start, end), horizontal ? x : y, horizontal ? width : height);
3695
+ }
3696
+ return true;
3697
+ #else
3698
+ (void)parent;
3699
+ (void)child;
3700
+ (void)x;
3701
+ (void)y;
3702
+ (void)width;
3703
+ (void)height;
3704
+ return false;
3705
+ #endif
3706
+ }
3707
+
3708
+ int LayoutEngine::alignedAbsoluteOffset(const Node &parent, const Node &childNode, bool horizontal,
3709
+ const Node *containing, int containingStart, int containingSize)
3710
+ {
3711
+ const Node *treeNodes = Tree::instance().nodes();
3712
+ const int childId = static_cast<int>(&childNode - treeNodes);
3713
+ if (const auto *rare = rareDataFor(childId); rare && rare->inlineStaticPosition.valid) {
3714
+ int continuationOrigin = 0;
3715
+ if (horizontal && rare->inlineStaticPosition.continuationLine) {
3716
+ // Resolve fragmented inline origins here, after ancestor layout has
3717
+ // finalized their first-fragment x positions. The continuation line
3718
+ // starts at the nearest formatting block's content edge, not at the
3719
+ // inline parent's first-fragment padding edge.
3720
+ int inlineOffset = 0;
3721
+ int cursor = static_cast<int>(&parent - treeNodes);
3722
+ while (cursor >= 0 && isCssInlineLevelBox(treeNodes[cursor])) {
3723
+ inlineOffset += treeNodes[cursor].layout.x;
3724
+ cursor = treeNodes[cursor].parent;
3725
+ }
3726
+ if (cursor >= 0) continuationOrigin = boxInset(treeNodes[cursor].style, 3) - inlineOffset;
3727
+ }
3728
+ return (horizontal ? rare->inlineStaticPosition.x + continuationOrigin + childNode.style.margin[3]
3729
+ : rare->inlineStaticPosition.y + childNode.style.margin[0]);
3730
+ }
3731
+ if (parent.style.display == kDisplayBlock && !parent.style.flex_direction_explicit &&
3732
+ childNode.layout.static_block_axis == (horizontal ? 2 : 1)) {
3733
+ const bool reversed = horizontal && gridAxisReversed(parent, true);
3734
+ return childNode.layout.static_block_start + (reversed ? -childNode.layout.width - childNode.style.margin[1]
3735
+ : childNode.style.margin[horizontal ? 3 : 0]);
3736
+ }
3737
+ // In block layout the hypothetical box starts at the parent's inline
3738
+ // content edge. RTL anchors its inline-end margin edge, even when the absolute
3739
+ // box is wider than its static-position parent. Its actual containing
3740
+ // block can be an entirely different ancestor.
3741
+ if (horizontal == (writingMode(parent) == 0) && parent.style.display == kDisplayBlock &&
3742
+ (!isInlineLevelNode(parent) || isOutOfFlowPosition(parent.style.position)) &&
3743
+ !parent.style.flex_direction_explicit) {
3744
+ return rightToLeft(parent)
3745
+ ? (horizontal ? parent.layout.width : parent.layout.height) - boxInset(parent.style, horizontal ? 1 : 2) -
3746
+ (horizontal ? childNode.layout.width : childNode.layout.height) - childNode.style.margin[horizontal ? 1 : 2]
3747
+ : boxInset(parent.style, horizontal ? 3 : 0) + childNode.style.margin[horizontal ? 3 : 0];
3748
+ }
3749
+ const bool grid = isDisplayGrid(parent.style), flex = parent.style.display == kDisplayFlex;
3750
+ const bool row = flex ? flexRowDirection(parent.style) != (writingMode(parent) != 0) : usesRowLayout(parent.style);
3751
+ const int crossAlign = childNode.style.align_self >= 0 ? childNode.style.align_self : parent.style.align_items;
3752
+ const int inlineAlign = (GEA_CSS_JUSTIFY_SELF ? rstyle(childNode.style).justify_self : -1) >= 0 ? (GEA_CSS_JUSTIFY_SELF ? rstyle(childNode.style).justify_self : -1) : parent.style.justify_items;
3753
+ int align = grid
3754
+ ? (horizontal == (writingMode(parent) == 0) ? inlineAlign : crossAlign)
3755
+ : (horizontal ? (row ? parent.style.justify_content : crossAlign)
3756
+ : (row ? crossAlign : parent.style.justify_content));
3757
+ if (flex && horizontal == row && isDistributedAlignment(align)) {
3758
+ // Static position lays out the absolute box as the sole hypothetical
3759
+ // flex item: between falls back to flex-start, around/evenly to center.
3760
+ // This static center anchor remains centered even when it overflows.
3761
+ align = ((align & 15) == 3 ? 6 : 1) | kAlignUnsafe;
3762
+ }
3763
+ // A grid supplies its content box when the containing block is outside
3764
+ // it; when it is the containing block, grid placement supplies the area.
3765
+ int inset = grid || flex ? boxInset(parent.style, horizontal ? 3 : 0) : 0;
3766
+ int parentSize = (horizontal ? parent.layout.width : parent.layout.height) -
3767
+ (grid || flex ? boxInsets(parent.style, horizontal) : 0);
3768
+ int areaX, areaY, areaWidth, areaHeight;
3769
+ if (absoluteGridArea(parent, childNode, areaX, areaY, areaWidth, areaHeight)) {
3770
+ inset = horizontal ? areaX : areaY;
3771
+ parentSize = horizontal ? areaWidth : areaHeight;
3772
+ }
3773
+ const int childSize = horizontal ? childNode.layout.width : childNode.layout.height;
3774
+ const int beforeMargin = horizontal ? childNode.style.margin[3] : childNode.style.margin[0];
3775
+ const int afterMargin = horizontal ? childNode.style.margin[1] : childNode.style.margin[2];
3776
+ int available = parentSize;
3777
+ if (available < 0) available = 0;
3778
+ const int occupied = childSize + beforeMargin + afterMargin;
3779
+ int free = available - occupied;
3780
+ const bool baseline = (align & 15) == 5 || (align & 15) == kAlignLastBaseline;
3781
+ // Baseline static positions already use their specified fallback edge
3782
+ // without overflow safety; do not turn that fallback into safe alignment.
3783
+ const bool resolveInsets = containing && (grid || flex) && (align & 15) != 0 && !baseline;
3784
+ const int pointAlignment = resolveInsets ? (align & ~kAlignSafe) | kAlignUnsafe : align;
3785
+ if (!grid && !flex && !baseline && free < 0 && !(align & (kAlignSafe | kAlignUnsafe))) free = 0;
3786
+ const int self = physicalSelfAlignment(parent, childNode, pointAlignment, free, horizontal);
3787
+ int used = grid || flex ? usedGridAlignment(parent, childNode, pointAlignment, free, horizontal, true)
3788
+ : self >= 0 ? self : baseline ? baselineFallbackAlignment(parent, childNode, pointAlignment, free, horizontal, true)
3789
+ : usedAlignment(pointAlignment, free);
3790
+ const int keyword = align & 15;
3791
+ if (flex && horizontal == row && parent.style.flex_direction_explicit && parent.style.flex_direction >= 2 &&
3792
+ (keyword == 0 || keyword == 2 || keyword == 6)) used = used == 2 ? 6 : 2;
3793
+ int position = inset + beforeMargin;
3794
+ if (used == 1) position += free / 2;
3795
+ else if (used == 2) position += free;
3796
+ if (resolveInsets) {
3797
+ // CSS Position 3.5.1 resolves the automatic inset(s) from the static
3798
+ // alignment point before overflow safety uses the available rectangle.
3799
+ const int containingEnd = containingStart + containingSize;
3800
+ int start = used == 2 ? containingStart : inset;
3801
+ int end = used == 2 ? inset + available : containingEnd;
3802
+ if (used == 1) {
3803
+ const int centerTwice = 2 * inset + available;
3804
+ const int startDistanceTwice = centerTwice - 2 * containingStart;
3805
+ const int endDistanceTwice = 2 * containingEnd - centerTwice;
3806
+ if (startDistanceTwice <= endDistanceTwice) {
3807
+ start = containingStart; end = start + std::abs(startDistanceTwice);
3808
+ } else {
3809
+ end = containingEnd; start = end - std::abs(endDistanceTwice);
3810
+ }
3811
+ }
3812
+ const bool reversed = gridAxisReversed(parent, horizontal);
3813
+ if (end < start) { if (reversed) start = end; else end = start; }
3814
+ const int remaining = end - start - occupied;
3815
+ if ((align & kAlignSafe) && remaining < 0) {
3816
+ position = reversed ? end - childSize - afterMargin : start + beforeMargin;
3817
+ } else if (flex && !(align & (kAlignSafe | kAlignUnsafe)) && remaining < 0) {
3818
+ const int limitStart = std::min(start, containingStart), limitEnd = std::max(end, containingEnd);
3819
+ if (occupied > limitEnd - limitStart)
3820
+ position = reversed ? limitEnd - childSize - afterMargin : limitStart + beforeMargin;
3821
+ else position = std::clamp(position, limitStart + beforeMargin, limitEnd - childSize - afterMargin);
3822
+ }
3823
+ // Unqualified grid self-alignment keeps the unsafe fallback used by browsers
3824
+ // and CSS Align's allowance for engines without smart overflow safety.
3825
+ // Applying a partial default-safety rule here changes ordinary grid
3826
+ // center/end alignment, even when no safe keyword was specified.
3827
+ }
3828
+ if (containing && flex && horizontal == row && keyword == 0 && !(align & (kAlignSafe | kAlignUnsafe))) {
3829
+ // The hypothetical single flex item can overflow its main-axis start
3830
+ // when that axis runs opposite to the actual containing block. Default
3831
+ // alignment keeps its start side reachable in the containing block.
3832
+ if (gridAxisReversed(*containing, horizontal))
3833
+ position = std::min(position, containingStart + containingSize - childSize - afterMargin);
3834
+ else position = std::max(position, containingStart + beforeMargin);
3835
+ }
3836
+ return position;
3837
+ }
3838
+
1796
3839
  bool LayoutEngine::isInlineLevelNode(const Node &n)
1797
3840
  {
1798
3841
  if (n.style.display == kDisplayFlex || n.style.display == kDisplayGrid || n.style.display == kDisplayNone)
@@ -1813,6 +3856,18 @@ bool LayoutEngine::isInlineLevelNode(const Node &n)
1813
3856
  return isInlineLevelTag(tagFromId(n.tag_id));
1814
3857
  }
1815
3858
 
3859
+ bool LayoutEngine::isCssInlineLevelBox(const Node &n, bool hypothetical)
3860
+ {
3861
+ if (n.style.display == kDisplayNone || n.style.display_explicit) return false;
3862
+ if (!hypothetical && (n.style.float_side || isOutOfFlowPosition(n.style.position))) return false;
3863
+ if (!hypothetical && n.parent >= 0) {
3864
+ const Node &parent = Tree::instance().nodes()[n.parent];
3865
+ if (parent.style.display == kDisplayFlex || isDisplayGrid(parent.style)) return false;
3866
+ }
3867
+ if (n.type == NodeType::Text || n.type == NodeType::Image) return true;
3868
+ return n.type == NodeType::View && isInlineLevelTag(tagFromId(n.tag_id));
3869
+ }
3870
+
1816
3871
  int LayoutEngine::clampSize(int size, int minSize, int maxSize) const
1817
3872
  {
1818
3873
  if (minSize > 0 && size < minSize) size = minSize;
@@ -1826,9 +3881,26 @@ int LayoutEngine::collectChildren(int parent, int *out, int max, bool skipAbs) c
1826
3881
  Node *nodes = Tree::instance().nodes();
1827
3882
  for (int child = nodes[parent].first_child; child >= 0; child = nodes[child].next_sibling) {
1828
3883
  if (isDisplayNone(nodes[child].style)) continue;
1829
- if (skipAbs && nodes[child].style.position == 1) continue;
3884
+ if (suppressAnonymousWhitespace(nodes, parent, child)) continue;
3885
+ if (skipAbs && isOutOfFlowPosition(nodes[child].style.position)) continue;
1830
3886
  if (n < max) out[n++] = child;
1831
3887
  }
3888
+ // All consumers (layout, painting, and hit testing) start from this stable
3889
+ // order. Subsequent stable z-index/depth sorting preserves it for ties.
3890
+ // Absolutely positioned children have order 0 for painting and are excluded
3891
+ // by skipAbs when collecting actual flex/grid items for layout.
3892
+ if (nodes[parent].style.display == kDisplayFlex || isDisplayGrid(nodes[parent].style)) {
3893
+ auto order = [&](int child) { return isOutOfFlowPosition(nodes[child].style.position) ? 0 : nodes[child].style.order; };
3894
+ for (int i = 1; i < n; ++i) {
3895
+ const int child = out[i];
3896
+ int j = i;
3897
+ while (j > 0 && order(out[j - 1]) > order(child)) {
3898
+ out[j] = out[j - 1];
3899
+ --j;
3900
+ }
3901
+ out[j] = child;
3902
+ }
3903
+ }
1832
3904
  return n;
1833
3905
  }
1834
3906
 
@@ -1840,31 +3912,99 @@ std::uint32_t gLayoutPassSerial = 1;
1840
3912
 
1841
3913
  void LayoutEngine::beginLayoutPass()
1842
3914
  {
1843
- if (++gLayoutPassSerial == 0) gLayoutPassSerial = 1;
3915
+ if (++gLayoutPassSerial == 0x10000u) {
3916
+ // Stored tags are 16-bit. Invalidate before reusing a serial so a node
3917
+ // untouched for a full cycle cannot appear freshly laid out. Keep the
3918
+ // arithmetic counter 32-bit; normal memo field reads remain direct.
3919
+ auto &tree = Tree::instance();
3920
+ for (int id = 0; id < tree.nodeCount(); ++id)
3921
+ tree.nodes()[id].layout.memo_pass = tree.nodes()[id].layout.memo2_pass = 0;
3922
+ gLayoutPassSerial = 1;
3923
+ }
1844
3924
  }
1845
3925
 
1846
- void LayoutEngine::layoutNode(int id, int avail_w, int avail_h)
3926
+ void LayoutEngine::layoutNode(int id, int avail_w, int avail_h, bool intrinsicBoxEdges)
1847
3927
  {
1848
3928
  Node &node = Tree::instance().nodes()[id];
1849
- const bool memoizable = avail_w >= INT16_MIN && avail_w <= INT16_MAX &&
3929
+ const Node *parent = node.parent >= 0 ? &Tree::instance().nodes()[node.parent] : nullptr;
3930
+ // Horizontal non-replaced floats use the same min/max-content measurement
3931
+ // and final used-width phase as fit-content. Floats on flex/grid items are
3932
+ // ignored; orthogonal automatic inline sizing is handled separately.
3933
+ const bool shrinkFloat = node.type == NodeType::View && node.style.float_side &&
3934
+ !isOutOfFlowPosition(node.style.position) &&
3935
+ (!parent || (parent->style.display != kDisplayFlex && !isDisplayGrid(parent->style))) &&
3936
+ node.style.width == kUnset && node.style.width_percent == kUnset && node.style.width_expression == -1 &&
3937
+ writingMode(node) == 0;
3938
+ // CSS Writing Modes 7.3.2: an orthogonal flow root's automatic inline
3939
+ // size is fit-content. Measure before fixing the used size so cyclic
3940
+ // percentage gaps are zero in the probes but resolve in final layout.
3941
+ // Flex and grid items obtain their automatic sizes from those algorithms.
3942
+ const bool horizontalInline = writingMode(node) == 0;
3943
+ const bool orthogonalAuto = node.type == NodeType::View && parent &&
3944
+ horizontalInline != (writingMode(*parent) == 0) &&
3945
+ parent->style.display != kDisplayFlex && !isDisplayGrid(parent->style) &&
3946
+ !isOutOfFlowPosition(node.style.position) &&
3947
+ (horizontalInline ? node.style.width : node.style.height) == kUnset &&
3948
+ (horizontalInline ? node.style.width_percent : node.style.height_percent) == kUnset &&
3949
+ (horizontalInline ? node.style.width_expression : node.style.height_expression) == -1;
3950
+ const bool intrinsicWidth = isIntrinsicSizeExpression(node.style.width_expression) && !intrinsicSizeScope(node, true);
3951
+ const bool horizontal = intrinsicWidth || !orthogonalAuto || horizontalInline;
3952
+ if ((intrinsicWidth || shrinkFloat || orthogonalAuto) &&
3953
+ !intrinsicSizeScope(node, horizontal) && !flexBasisScope(node, horizontal)) {
3954
+ const int inherited = parent ? intrinsicSizeConstraint(*parent, horizontal) : 0;
3955
+ const int keyword = intrinsicWidth ? node.style.width_expression : kSizeFitContent;
3956
+ IntrinsicSizeScope scope(node, 1, horizontal);
3957
+ auto measure = [&](int mode) {
3958
+ scope.constraint = mode;
3959
+ const int available = mode == 1 ? 1 : 32767;
3960
+ layoutNode(id, horizontal ? available : avail_w, horizontal ? avail_h : available, true);
3961
+ return std::max(0, (horizontal ? node.layout.width : node.layout.height) - boxInsets(node.style, horizontal));
3962
+ };
3963
+ if (inherited) {
3964
+ measure(keyword == kSizeMinContent ? 1 : keyword == kSizeMaxContent ? 2 : inherited);
3965
+ return;
3966
+ }
3967
+ const int minimum = keyword == kSizeMaxContent ? 0 : measure(1);
3968
+ const int maximum = keyword == kSizeMinContent ? minimum : std::max(minimum, measure(2));
3969
+ #if GEA_CSS_BOX_EXPRESSIONS
3970
+ const int inlineBasis = node.parent >= 0 && writingMode(Tree::instance().nodes()[node.parent]) != 0 ? avail_h : avail_w;
3971
+ resolveLayoutBoxLengths(id, intrinsicBoxEdges ? 0 : inlineBasis);
3972
+ #endif
3973
+ const int edges = boxInsets(node.style, horizontal);
3974
+ const int stretch = std::max(0, (horizontal ? avail_w : avail_h) -
3975
+ node.style.margin[horizontal ? 1 : 0] - node.style.margin[horizontal ? 3 : 2] - edges);
3976
+ scope.borderSize = edges + (keyword == kSizeMinContent ? minimum : keyword == kSizeMaxContent ? maximum : std::min(maximum, std::max(minimum, stretch)));
3977
+ scope.constraint = 0;
3978
+ layoutNode(id, avail_w, avail_h, intrinsicBoxEdges);
3979
+ return;
3980
+ }
3981
+ if (node.type == NodeType::Text && intrinsicWidthConstraint(node) == 1)
3982
+ avail_w = std::max(avail_w, TextRenderer::minContentWidth(node) + boxInsets(node.style, true));
3983
+ #if GEA_CSS_BOX_EXPRESSIONS
3984
+ const int inlineBasis = node.parent >= 0 && writingMode(Tree::instance().nodes()[node.parent]) != 0 ? avail_h : avail_w;
3985
+ if (resolveLayoutBoxLengths(id, intrinsicBoxEdges ? 0 : inlineBasis)) {
3986
+ node.layout.memo_pass = node.layout.memo2_pass = 0;
3987
+ }
3988
+ #endif
3989
+ const bool memoizable = !gIntrinsicSizeScope && !gFlexBasisScope && avail_w >= INT16_MIN && avail_w <= INT16_MAX &&
1850
3990
  avail_h >= INT16_MIN && avail_h <= INT16_MAX;
1851
3991
  if (memoizable) {
1852
3992
  if (node.layout.memo_pass == gLayoutPassSerial &&
1853
3993
  node.layout.memo_avail_w == avail_w &&
1854
- node.layout.memo_avail_h == avail_h) {
3994
+ node.layout.memo_avail_h == avail_h &&
3995
+ node.layout.memo_result_w == node.layout.width &&
3996
+ node.layout.memo_result_h == node.layout.height) {
1855
3997
  refreshPerfStatsMutable().treeLayoutMemoHits++;
1856
3998
  return;
1857
3999
  }
1858
4000
  if (node.layout.memo2_pass == gLayoutPassSerial &&
1859
4001
  node.layout.memo2_avail_w == avail_w &&
1860
4002
  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) {
4003
+ node.layout.memo_result_w == node.layout.width &&
4004
+ node.layout.memo_result_h == node.layout.height) {
1863
4005
  // Promote the hit to the MRU slot.
1864
4006
  std::swap(node.layout.memo_avail_w, node.layout.memo2_avail_w);
1865
4007
  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
4008
  std::swap(node.layout.memo_pass, node.layout.memo2_pass);
1869
4009
  refreshPerfStatsMutable().treeLayoutMemoHits++;
1870
4010
  return;
@@ -1872,11 +4012,22 @@ void LayoutEngine::layoutNode(int id, int avail_w, int avail_h)
1872
4012
  }
1873
4013
  refreshPerfStatsMutable().treeLayoutNodeCalls++;
1874
4014
  LayoutNodePass(*this, id, avail_w, avail_h).run();
4015
+ const int beforeRatioWidth = node.layout.width, beforeRatioHeight = node.layout.height;
4016
+ applyPreferredRatio(node, avail_w, avail_h);
4017
+ if (node.first_child >= 0 && (node.layout.width != beforeRatioWidth || node.layout.height != beforeRatioHeight))
4018
+ LayoutNodePass(*this, id, node.layout.width, node.layout.height).repositionChildren();
4019
+ if (node.parent < 0) {
4020
+ // The initial containing block places the root; there is no parent
4021
+ // layout pass to position its margin box or apply float alignment.
4022
+ node.layout.x = node.style.float_side == 2
4023
+ ? avail_w - node.layout.width - node.style.margin[1]
4024
+ : node.style.margin[3];
4025
+ node.layout.y = node.style.margin[0];
4026
+ }
1875
4027
  node.layout.memo2_avail_w = node.layout.memo_avail_w;
1876
4028
  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;
4029
+ node.layout.memo2_pass = node.layout.memo_result_w == node.layout.width &&
4030
+ node.layout.memo_result_h == node.layout.height ? node.layout.memo_pass : 0;
1880
4031
  if (memoizable) {
1881
4032
  node.layout.memo_avail_w = static_cast<std::int16_t>(avail_w);
1882
4033
  node.layout.memo_avail_h = static_cast<std::int16_t>(avail_h);
@@ -1907,6 +4058,11 @@ bool LayoutEngine::layoutNodeScoped(int scope, int treeRoot)
1907
4058
  refreshPerfStatsMutable().treeScopedRejectNode = scope;
1908
4059
  return false;
1909
4060
  }
4061
+ if (!LayoutNodePass(*this, scope, a.layout.memo_avail_w, a.layout.memo_avail_h).containsChildMargins()) {
4062
+ refreshPerfStatsMutable().treeScopedRejectReason = 5;
4063
+ refreshPerfStatsMutable().treeScopedRejectNode = scope;
4064
+ return false;
4065
+ }
1910
4066
 
1911
4067
  auto inScope = [&](int node) {
1912
4068
  for (int c = node; c >= 0 && c < nodeCount; c = nodes[c].parent) {
@@ -1920,7 +4076,7 @@ bool LayoutEngine::layoutNodeScoped(int scope, int treeRoot)
1920
4076
  // pre-resolve relative space) — those trees must take the full path.
1921
4077
  for (int i = 0; i < nodeCount; ++i) {
1922
4078
  const Node &n = nodes[i];
1923
- if (n.parent < 0 || n.style.position != 1 || isDisplayNone(n.style)) continue;
4079
+ if (n.parent < 0 || !isOutOfFlowPosition(n.style.position) || isDisplayNone(n.style)) continue;
1924
4080
  if (!inScope(i)) continue;
1925
4081
  const int containing = containingBlockForAbsoluteNode(i, treeRoot, nodes);
1926
4082
  if (containing >= 0 && !inScope(containing)) {
@@ -1951,13 +4107,15 @@ bool LayoutEngine::layoutNodeScoped(int scope, int treeRoot)
1951
4107
  if (a.parent >= 0 && a.parent < nodeCount) {
1952
4108
  const Node &parent = nodes[a.parent];
1953
4109
  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;
4110
+ const int inlineAlign = (GEA_CSS_JUSTIFY_SELF ? rstyle(a.style).justify_self : -1) >= 0 ? (GEA_CSS_JUSTIFY_SELF ? rstyle(a.style).justify_self : -1) : parent.style.justify_items;
4111
+ const int blockAlign = a.style.align_self >= 0 ? a.style.align_self : parent.style.align_items;
4112
+ const int alignX = writingMode(parent) == 0 ? inlineAlign : blockAlign;
4113
+ const int alignY = writingMode(parent) == 0 ? blockAlign : inlineAlign;
4114
+ parentOwnsWidth = parentOwnsWidth || (alignX == 0 && !(a.style.margin_auto & 10));
4115
+ parentOwnsHeight = parentOwnsHeight || (alignY == 0 && !(a.style.margin_auto & 5));
1958
4116
  } else {
1959
4117
  const bool row = usesRowLayout(parent.style);
1960
- const bool parentOwnsMain = a.style.flex > 0 || a.style.flex_basis != kUnset;
4118
+ const bool parentOwnsMain = a.style.flex > 0 || hasFlexBasis(a);
1961
4119
  const int crossAlign = a.style.align_self >= 0 ? a.style.align_self : parent.style.align_items;
1962
4120
  const bool parentOwnsCross = crossAlign == 0;
1963
4121
  parentOwnsWidth = parentOwnsWidth || (row ? parentOwnsMain : parentOwnsCross);
@@ -1983,7 +4141,7 @@ bool LayoutEngine::layoutNodeScoped(int scope, int treeRoot)
1983
4141
  // Scoped equivalent of the root containing-block pass (both the node and
1984
4142
  // its containing block are inside the scope, in the same relative space).
1985
4143
  for (int i = 0; i < nodeCount; ++i) {
1986
- if (isDisplayNone(nodes[i].style) || nodes[i].style.position != 1 || nodes[i].parent < 0) continue;
4144
+ if (isDisplayNone(nodes[i].style) || !isOutOfFlowPosition(nodes[i].style.position) || nodes[i].parent < 0) continue;
1987
4145
  if (!inScope(i) || i == scope) continue;
1988
4146
  const int containing = containingBlockForAbsoluteNode(i, scope, nodes);
1989
4147
  if (containing < 0) continue;
@@ -2007,8 +4165,10 @@ void LayoutEngine::resolveAbsoluteCoords(int id, int parent_x, int parent_y)
2007
4165
  Node *nodes = Tree::instance().nodes();
2008
4166
  Node *node = &nodes[id];
2009
4167
  if (node->parent < 0) resolveAbsoluteContainingBlocks(id);
2010
- node->layout.x += parent_x;
2011
- node->layout.y += parent_y;
4168
+ if (!isViewportFixed(*node)) {
4169
+ node->layout.x += parent_x;
4170
+ node->layout.y += parent_y;
4171
+ }
2012
4172
 
2013
4173
  int childParentX = node->layout.x;
2014
4174
  int childParentY = node->layout.y;