File: InlineLineBoxVerticalAligner.cpp

package info (click to toggle)
webkit2gtk 2.42.2-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 362,452 kB
  • sloc: cpp: 2,881,971; javascript: 282,447; ansic: 134,088; python: 43,789; ruby: 18,308; perl: 15,872; asm: 14,389; xml: 4,395; yacc: 2,350; sh: 2,074; java: 1,734; lex: 1,323; makefile: 288; pascal: 60
file content (562 lines) | stat: -rw-r--r-- 31,012 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
/*
 * Copyright (C) 2021 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "InlineLineBoxVerticalAligner.h"

#include "InlineFormattingContext.h"
#include "InlineLevelBoxInlines.h"
#include "LayoutBoxGeometry.h"
#include "LayoutChildIterator.h"

namespace WebCore {
namespace Layout {

LineBoxVerticalAligner::LineBoxVerticalAligner(const InlineFormattingContext& inlineFormattingContext)
    : m_inlineFormattingContext(inlineFormattingContext)
    , m_inlineFormattingGeometry(inlineFormattingContext)
{
}

InlineLayoutUnit LineBoxVerticalAligner::computeLogicalHeightAndAlign(LineBox& lineBox) const
{
    auto canUseSimplifiedAlignment = [&] {
        if (!lineBox.hasContent())
            return true;

        if (rootBox().style().lineBoxContain() != RenderStyle::initialLineBoxContain())
            return false;
        auto& rootInlineBox = lineBox.rootInlineBox();
        if (!layoutState().inStandardsMode() || !rootInlineBox.isPreferredLineHeightFontMetricsBased() || rootInlineBox.verticalAlign().type != VerticalAlign::Baseline)
            return false;
        if (rootInlineBox.hasAnnotation())
            return false;

        for (auto& inlineLevelBox : lineBox.nonRootInlineLevelBoxes()) {
            auto shouldUseSimplifiedAlignmentForInlineLevelBox = [&] {
                if (inlineLevelBox.hasAnnotation())
                    return false;
                if (inlineLevelBox.isAtomicInlineLevelBox()) {
                    // Baseline aligned, non-stretchy direct children are considered to be simple for now.
                    auto& layoutBox = inlineLevelBox.layoutBox();
                    if (&layoutBox.parent() != &rootInlineBox.layoutBox() || inlineLevelBox.verticalAlign().type != VerticalAlign::Baseline)
                        return false;
                    auto& inlineLevelBoxGeometry = formattingContext().geometryForBox(layoutBox);
                    return !inlineLevelBoxGeometry.marginBefore() && !inlineLevelBoxGeometry.marginAfter() && inlineLevelBoxGeometry.marginBoxHeight() <= rootInlineBox.layoutBounds().ascent;
                }
                if (inlineLevelBox.isLineBreakBox()) {
                    // Baseline aligned, non-stretchy line breaks e.g. <div><span><br></span></div> but not <div><span style="font-size: 100px;"><br></span></div>.
                    return inlineLevelBox.verticalAlign().type == VerticalAlign::Baseline && inlineLevelBox.layoutBounds().ascent <= rootInlineBox.layoutBounds().ascent;
                }
                if (inlineLevelBox.isInlineBox()) {
                    // Baseline aligned, non-stretchy inline boxes e.g. <div><span></span></div> but not <div><span style="font-size: 100px;"></span></div>.
                    return inlineLevelBox.verticalAlign().type == VerticalAlign::Baseline && inlineLevelBox.layoutBounds() == rootInlineBox.layoutBounds();
                }
                return false;
            };
            if (!shouldUseSimplifiedAlignmentForInlineLevelBox())
                return false;
        }
        return true;
    };

    if (canUseSimplifiedAlignment())
        return simplifiedVerticalAlignment(lineBox);
    // This function (partially) implements:
    // 2.2. Layout Within Line Boxes
    // https://www.w3.org/TR/css-inline-3/#line-layout
    // 1. Compute the line box height using the layout bounds geometry. This height computation strictly uses layout bounds and not normal inline level box geometries.
    // 2. Compute the baseline/logical top position of the root inline box. Aligned boxes push the root inline box around inside the line box.
    // 3. Finally align the inline level boxes using (mostly) normal inline level box geometries.
    ASSERT(lineBox.hasContent());
    auto lineBoxAlignmentContent = computeLineBoxLogicalHeight(lineBox);
    computeRootInlineBoxVerticalPosition(lineBox, lineBoxAlignmentContent);

    auto lineBoxHeight = lineBoxAlignmentContent.height();
    alignInlineLevelBoxes(lineBox, lineBoxHeight);
    if (lineBoxAlignmentContent.hasAnnotation)
        lineBoxHeight = adjustForAnnotationIfNeeded(lineBox, lineBoxHeight);
    return lineBoxHeight;
}

InlineLayoutUnit LineBoxVerticalAligner::simplifiedVerticalAlignment(LineBox& lineBox) const
{
    auto& rootInlineBox = lineBox.rootInlineBox();
    auto rootInlineBoxAscent = rootInlineBox.ascent();

    if (!lineBox.hasContent()) {
        rootInlineBox.setLogicalTop(-rootInlineBoxAscent);
        return { };
    }

    auto rootInlineBoxLayoutBounds = rootInlineBox.layoutBounds();
    auto lineBoxLogicalTop = InlineLayoutUnit { 0 };
    auto lineBoxLogicalBottom = rootInlineBoxLayoutBounds.height();
    auto rootInlineBoxLogicalTop = rootInlineBoxLayoutBounds.ascent - rootInlineBoxAscent;
    for (auto& inlineLevelBox : lineBox.nonRootInlineLevelBoxes()) {
        // Only baseline alignment for now.
        inlineLevelBox.setLogicalTop(rootInlineBoxAscent - inlineLevelBox.ascent());
        auto layoutBounds = inlineLevelBox.layoutBounds();
        auto layoutBoundsLogicalTop = rootInlineBoxLayoutBounds.ascent - layoutBounds.ascent;
        lineBoxLogicalTop = std::min(lineBoxLogicalTop, layoutBoundsLogicalTop);
        lineBoxLogicalBottom = std::max(lineBoxLogicalBottom, layoutBoundsLogicalTop + layoutBounds.height());
        rootInlineBoxLogicalTop = std::max(rootInlineBoxLogicalTop, layoutBounds.ascent - rootInlineBoxAscent);
    }
    rootInlineBox.setLogicalTop(rootInlineBoxLogicalTop);
    return lineBoxLogicalBottom - lineBoxLogicalTop;
}

LineBoxVerticalAligner::LineBoxAlignmentContent LineBoxVerticalAligner::computeLineBoxLogicalHeight(LineBox& lineBox) const
{
    // This function (partially) implements:
    // 2.2. Layout Within Line Boxes
    // https://www.w3.org/TR/css-inline-3/#line-layout
    // 1. Compute the line box height using the layout bounds geometry. This height computation strictly uses layout bounds and not normal inline level box geometries.
    // 2. Compute the baseline/logical top position of the root inline box. Aligned boxes push the root inline box around inside the line box.
    // 3. Finally align the inline level boxes using (mostly) normal inline level box geometries.
    auto& rootInlineBox = lineBox.rootInlineBox();
    auto& formattingGeometry = this->formattingGeometry();
    auto contentHasAnnotation = rootInlineBox.hasAnnotation();

    // Line box height computation is based on the layout bounds of the inline boxes and not their logical (ascent/descent) dimensions.
    struct AbsoluteTopAndBottom {
        InlineLayoutUnit top { 0 };
        InlineLayoutUnit bottom { 0 };
    };
    HashMap<const InlineLevelBox*, AbsoluteTopAndBottom> inlineLevelBoxAbsoluteTopAndBottomMap;

    auto minimumLogicalTop = std::optional<InlineLayoutUnit> { };
    auto maximumLogicalBottom = std::optional<InlineLayoutUnit> { };
    if (formattingGeometry.inlineLevelBoxAffectsLineBox(rootInlineBox)) {
        minimumLogicalTop = InlineLayoutUnit { };
        maximumLogicalBottom = rootInlineBox.layoutBounds().height();
        inlineLevelBoxAbsoluteTopAndBottomMap.add(&rootInlineBox, AbsoluteTopAndBottom { *minimumLogicalTop, *maximumLogicalBottom });
    } else
        inlineLevelBoxAbsoluteTopAndBottomMap.add(&rootInlineBox, AbsoluteTopAndBottom { });

    Vector<InlineLevelBox*> lineBoxRelativeInlineLevelBoxes;
    for (auto& inlineLevelBox : lineBox.nonRootInlineLevelBoxes()) {
        contentHasAnnotation = contentHasAnnotation || inlineLevelBox.hasAnnotation();

        if (inlineLevelBox.hasLineBoxRelativeAlignment()) {
            lineBoxRelativeInlineLevelBoxes.append(&inlineLevelBox);
            continue;
        }
        auto& parentInlineBox = lineBox.parentInlineBox(inlineLevelBox);
        // Logical top is relative to the parent inline box's layout bounds.
        // Note that this logical top is not the final logical top of the inline level box.
        // This is the logical top in the context of the layout bounds geometry which may be very different from the inline box's normal geometry.
        auto logicalTop = InlineLayoutUnit { };

        auto verticalAlign = inlineLevelBox.verticalAlign();
        auto layoutBounds = inlineLevelBox.layoutBounds();
        auto parentInlineBoxAscent = parentInlineBox.layoutBounds().ascent;

        switch (verticalAlign.type) {
        case VerticalAlign::Baseline:
            logicalTop = parentInlineBoxAscent - layoutBounds.ascent;
            break;
        case VerticalAlign::Middle: {
            auto logicalTopOffsetFromParentBaseline = layoutBounds.height() / 2 + parentInlineBox.primarymetricsOfPrimaryFont().xHeight() / 2;
            logicalTop = parentInlineBoxAscent - logicalTopOffsetFromParentBaseline;
            break;
        }
        case VerticalAlign::BaselineMiddle: {
            auto logicalTopOffsetFromParentBaseline = layoutBounds.height() / 2;
            logicalTop = parentInlineBoxAscent - logicalTopOffsetFromParentBaseline;
            break;
        }
        case VerticalAlign::Length: {
            auto logicalTopOffsetFromParentBaseline = *verticalAlign.baselineOffset + layoutBounds.ascent;
            logicalTop = parentInlineBoxAscent - logicalTopOffsetFromParentBaseline;
            break;
        }
        case VerticalAlign::TextTop: {
            // Note that text-top aligns with the inline box's font metrics top (ascent) and not the layout bounds top.
            logicalTop = parentInlineBoxAscent - parentInlineBox.ascent();
            break;
        }
        case VerticalAlign::TextBottom: {
            // Note that text-bottom aligns with the inline box's font metrics bottom (descent) and not the layout bounds bottom.
            auto parentInlineBoxLayoutBounds = parentInlineBox.layoutBounds();
            auto parentInlineBoxLogicalBottom = parentInlineBoxLayoutBounds.height() - parentInlineBoxLayoutBounds.descent + parentInlineBox.descent();
            logicalTop = parentInlineBoxLogicalBottom - layoutBounds.height();
            break;
        }
        case VerticalAlign::Sub: {
            auto logicalTopOffsetFromParentBaseline = layoutBounds.ascent - (parentInlineBox.fontSize() / 5 + 1);
            logicalTop = parentInlineBoxAscent - logicalTopOffsetFromParentBaseline;
            break;
        }
        case VerticalAlign::Super: {
            auto logicalTopOffsetFromParentBaseline = layoutBounds.ascent + parentInlineBox.fontSize() / 3 + 1;
            logicalTop = parentInlineBoxAscent - logicalTopOffsetFromParentBaseline;
            break;
        }
        default:
            ASSERT_NOT_IMPLEMENTED_YET();
            break;
        }
        auto parentInlineBoxAbsoluteTopAndBottom = inlineLevelBoxAbsoluteTopAndBottomMap.get(&parentInlineBox);
        auto absoluteLogicalTop = parentInlineBoxAbsoluteTopAndBottom.top + logicalTop;
        auto absoluteLogicalBottom = absoluteLogicalTop + layoutBounds.height();
        inlineLevelBoxAbsoluteTopAndBottomMap.add(&inlineLevelBox, AbsoluteTopAndBottom { absoluteLogicalTop, absoluteLogicalBottom });
        // Stretch the min/max absolute values if applicable.
        if (formattingGeometry.inlineLevelBoxAffectsLineBox(inlineLevelBox)) {
            minimumLogicalTop = std::min(minimumLogicalTop.value_or(absoluteLogicalTop), absoluteLogicalTop);
            maximumLogicalBottom = std::max(maximumLogicalBottom.value_or(absoluteLogicalBottom), absoluteLogicalBottom);
        }
    }
    // The line box height computation is as follows:
    // 1. Stretch the line box with the non-line-box relative aligned inline box absolute top and bottom values.
    // 2. Check if the line box relative aligned inline boxes (top, bottom etc) have enough room and stretch the line box further if needed.
    auto nonLineBoxRelativeAlignedBoxesMaximumHeight = valueOrDefault(maximumLogicalBottom) - valueOrDefault(minimumLogicalTop);
    auto topAlignedBoxesMaximumHeight = std::optional<InlineLayoutUnit> { };
    auto bottomAlignedBoxesMaximumHeight = std::optional<InlineLayoutUnit> { };
    for (auto* lineBoxRelativeInlineLevelBox : lineBoxRelativeInlineLevelBoxes) {
        if (!formattingGeometry.inlineLevelBoxAffectsLineBox(*lineBoxRelativeInlineLevelBox))
            continue;
        // This line box relative aligned inline level box stretches the line box.
        auto inlineLevelBoxHeight = lineBoxRelativeInlineLevelBox->layoutBounds().height();
        if (lineBoxRelativeInlineLevelBox->verticalAlign().type == VerticalAlign::Top) {
            topAlignedBoxesMaximumHeight = std::max(inlineLevelBoxHeight, topAlignedBoxesMaximumHeight.value_or(0.f));
            continue;
        }
        if (lineBoxRelativeInlineLevelBox->verticalAlign().type == VerticalAlign::Bottom) {
            bottomAlignedBoxesMaximumHeight = std::max(inlineLevelBoxHeight, bottomAlignedBoxesMaximumHeight.value_or(0.f));
            continue;
        }
        ASSERT_NOT_REACHED();
    }
    return { nonLineBoxRelativeAlignedBoxesMaximumHeight, { topAlignedBoxesMaximumHeight, bottomAlignedBoxesMaximumHeight }, contentHasAnnotation };
}

void LineBoxVerticalAligner::computeRootInlineBoxVerticalPosition(LineBox& lineBox, const LineBoxAlignmentContent& lineBoxAlignmentContent) const
{
    auto& rootInlineBox = lineBox.rootInlineBox();
    auto& formattingGeometry = this->formattingGeometry();
    auto hasTopAlignedInlineLevelBox = false;

    HashMap<const InlineLevelBox*, InlineLayoutUnit> inlineLevelBoxAbsoluteBaselineOffsetMap;
    inlineLevelBoxAbsoluteBaselineOffsetMap.add(&rootInlineBox, InlineLayoutUnit { });

    auto maximumTopOffsetFromRootInlineBoxBaseline = std::optional<InlineLayoutUnit> { };
    if (formattingGeometry.inlineLevelBoxAffectsLineBox(rootInlineBox))
        maximumTopOffsetFromRootInlineBoxBaseline = rootInlineBox.layoutBounds().ascent;

    auto affectsRootInlineBoxVerticalPosition = [&](auto& inlineLevelBox) {
        auto inlineLevelBoxStrechesLineBox = formattingGeometry.inlineLevelBoxAffectsLineBox(inlineLevelBox);
        return inlineLevelBoxStrechesLineBox || ((inlineLevelBox.isAtomicInlineLevelBox() && !inlineLevelBox.isListMarker()) && inlineLevelBox.layoutBounds().ascent && inlineLevelBox.mayStretchLineBox());
    };

    for (auto& inlineLevelBox : lineBox.nonRootInlineLevelBoxes()) {
        auto verticalAlign = inlineLevelBox.verticalAlign();
        auto layoutBounds = inlineLevelBox.layoutBounds();

        if (inlineLevelBox.hasLineBoxRelativeAlignment()) {
            if (verticalAlign.type == VerticalAlign::Top) {
                hasTopAlignedInlineLevelBox = hasTopAlignedInlineLevelBox || affectsRootInlineBoxVerticalPosition(inlineLevelBox);
                inlineLevelBoxAbsoluteBaselineOffsetMap.add(&inlineLevelBox, rootInlineBox.layoutBounds().ascent - layoutBounds.ascent);
            } else if (verticalAlign.type == VerticalAlign::Bottom)
                inlineLevelBoxAbsoluteBaselineOffsetMap.add(&inlineLevelBox, layoutBounds.descent - rootInlineBox.layoutBounds().descent);
            else
                ASSERT_NOT_REACHED();
            continue;
        }
        auto& parentInlineBox = lineBox.parentInlineBox(inlineLevelBox);
        auto baselineOffsetFromParentBaseline = InlineLayoutUnit { };

        switch (verticalAlign.type) {
        case VerticalAlign::Baseline:
            baselineOffsetFromParentBaseline = { };
            break;
        case VerticalAlign::Middle: {
            auto logicalTopOffsetFromParentBaseline = (layoutBounds.height() / 2 + parentInlineBox.primarymetricsOfPrimaryFont().xHeight() / 2);
            baselineOffsetFromParentBaseline = logicalTopOffsetFromParentBaseline - layoutBounds.ascent;
            break;
        }
        case VerticalAlign::BaselineMiddle: {
            auto logicalTopOffsetFromParentBaseline = layoutBounds.height() / 2;
            baselineOffsetFromParentBaseline = logicalTopOffsetFromParentBaseline - layoutBounds.ascent;
            break;
        }
        case VerticalAlign::Length: {
            auto logicalTopOffsetFromParentBaseline = *verticalAlign.baselineOffset + inlineLevelBox.ascent();
            baselineOffsetFromParentBaseline = logicalTopOffsetFromParentBaseline - inlineLevelBox.ascent();
            break;
        }
        case VerticalAlign::TextTop:
            baselineOffsetFromParentBaseline = parentInlineBox.ascent() - layoutBounds.ascent;
            break;
        case VerticalAlign::TextBottom:
            baselineOffsetFromParentBaseline = layoutBounds.descent - parentInlineBox.descent();
            break;
        case VerticalAlign::Sub:
            baselineOffsetFromParentBaseline = -(parentInlineBox.fontSize() / 5 + 1);
            break;
        case VerticalAlign::Super:
            baselineOffsetFromParentBaseline = parentInlineBox.fontSize() / 3 + 1;
            break;
        default:
            ASSERT_NOT_IMPLEMENTED_YET();
            break;
        }
        auto absoluteBaselineOffset = inlineLevelBoxAbsoluteBaselineOffsetMap.get(&parentInlineBox) + baselineOffsetFromParentBaseline;
        inlineLevelBoxAbsoluteBaselineOffsetMap.add(&inlineLevelBox, absoluteBaselineOffset);

        if (affectsRootInlineBoxVerticalPosition(inlineLevelBox)) {
            auto topOffsetFromRootInlineBoxBaseline = absoluteBaselineOffset + layoutBounds.ascent;
            if (maximumTopOffsetFromRootInlineBoxBaseline)
                maximumTopOffsetFromRootInlineBoxBaseline = std::max(*maximumTopOffsetFromRootInlineBoxBaseline, topOffsetFromRootInlineBoxBaseline);
            else {
                // We are is quirk mode and the root inline box has no content. The root inline box's baseline is anchored at 0.
                // However negative ascent (e.g negative top margin) can "push" the root inline box upwards and have a negative value.
                maximumTopOffsetFromRootInlineBoxBaseline = layoutBounds.ascent >= 0
                    ? std::max(0.0f, topOffsetFromRootInlineBoxBaseline)
                    : topOffsetFromRootInlineBoxBaseline;
            }
        }
    }

    if (!maximumTopOffsetFromRootInlineBoxBaseline && hasTopAlignedInlineLevelBox) {
        // vertical-align: top is a line box relative alignment. It stretches the line box downwards meaning that it does not affect
        // the root inline box's baseline position, but in quirks mode we have to ensure that the root inline box does not end up at 0px.
        maximumTopOffsetFromRootInlineBoxBaseline = rootInlineBox.ascent();
    }
    // vertical-align: bottom stretches the top of the line box pushing the root inline box downwards.
    auto bottomAlignedBoxStretch = lineBoxAlignmentContent.topAndBottomAlignedMaximumHeight.bottom.value_or(0.f);
    if (bottomAlignedBoxStretch) {
        // If top happens to stretch the line box, we don't need to push the root inline box anymore.
        if (bottomAlignedBoxStretch <= lineBoxAlignmentContent.topAndBottomAlignedMaximumHeight.top.value_or(0.f))
            bottomAlignedBoxStretch = { };

        // However non-line box relative content needs some space. Root inline box may not end up being at the very bottom.
        if (bottomAlignedBoxStretch) {
            if (lineBoxAlignmentContent.nonLineBoxRelativeAlignedMaximumHeight > 0) {
                // Negative vertical margin can make aligned boxes have negative height.
                bottomAlignedBoxStretch -= std::max(0.f, lineBoxAlignmentContent.nonLineBoxRelativeAlignedMaximumHeight);
            }
            bottomAlignedBoxStretch = std::max(0.f, bottomAlignedBoxStretch);
        }
    }
    auto rootInlineBoxLogicalTop = bottomAlignedBoxStretch + maximumTopOffsetFromRootInlineBoxBaseline.value_or(0.f) - rootInlineBox.ascent();
    rootInlineBox.setLogicalTop(rootInlineBoxLogicalTop);
}

InlineLevelBox::AscentAndDescent LineBoxVerticalAligner::layoutBoundsForInlineBoxSubtree(const LineBox::InlineLevelBoxList& nonRootInlineLevelBoxes, size_t inlineBoxIndex) const
{
    // https://w3c.github.io/csswg-drafts/css2/#propdef-vertical-align
    //
    // top/bottom values align the element relative to the line box.
    // Since the element may have children aligned relative to it (which in turn may have descendants aligned relative to them),
    // these values use the bounds of the aligned subtree.
    // The aligned subtree of an inline element contains that element and the aligned subtrees of all children
    // inline elements whose computed vertical-align value is not top or bottom.
    // The top of the aligned subtree is the highest of the tops of the boxes in the subtree, and the bottom is analogous.
    ASSERT(nonRootInlineLevelBoxes[inlineBoxIndex].isInlineBox());
    auto& formattingGeometry = this->formattingGeometry();
    auto enclosingLayoutBounds = InlineLevelBox::AscentAndDescent { };
    auto& inlineBoxParent = nonRootInlineLevelBoxes[inlineBoxIndex].layoutBox().parent();
    for (size_t index = inlineBoxIndex + 1; index < nonRootInlineLevelBoxes.size(); ++index) {
        auto& descendantInlineLevelBox = nonRootInlineLevelBoxes[index];
        if (&descendantInlineLevelBox.layoutBox().parent() == &inlineBoxParent) {
            // We are at the end of the descendant list.
            break;
        }
        if (!formattingGeometry.inlineLevelBoxAffectsLineBox(descendantInlineLevelBox) || descendantInlineLevelBox.hasLineBoxRelativeAlignment())
            continue;
        enclosingLayoutBounds.ascent = std::max(descendantInlineLevelBox.layoutBounds().ascent, enclosingLayoutBounds.ascent);
        enclosingLayoutBounds.descent = std::max(descendantInlineLevelBox.layoutBounds().descent, enclosingLayoutBounds.descent);
    }
    return enclosingLayoutBounds;
}

void LineBoxVerticalAligner::alignInlineLevelBoxes(LineBox& lineBox, InlineLayoutUnit lineBoxLogicalHeight) const
{
    Vector<size_t> lineBoxRelativeInlineLevelBoxes;
    auto& nonRootInlineLevelBoxes = lineBox.nonRootInlineLevelBoxes();
    for (size_t index = 0; index < nonRootInlineLevelBoxes.size(); ++index) {
        auto& inlineLevelBox = nonRootInlineLevelBoxes[index];
        if (inlineLevelBox.hasLineBoxRelativeAlignment()) {
            lineBoxRelativeInlineLevelBoxes.append(index);
            continue;
        }
        auto& parentInlineBox = lineBox.parentInlineBox(inlineLevelBox);
        auto logicalTop = InlineLayoutUnit { };
        auto verticalAlign = inlineLevelBox.verticalAlign();

        switch (verticalAlign.type) {
        case VerticalAlign::Baseline:
            logicalTop = parentInlineBox.ascent() - inlineLevelBox.ascent();
            break;
        case VerticalAlign::Middle: {
            auto logicalTopOffsetFromParentBaseline = (inlineLevelBox.logicalHeight() / 2 + parentInlineBox.primarymetricsOfPrimaryFont().xHeight() / 2);
            logicalTop = parentInlineBox.ascent() - logicalTopOffsetFromParentBaseline;
            break;
        }
        case VerticalAlign::BaselineMiddle: {
            auto logicalTopOffsetFromParentBaseline = inlineLevelBox.logicalHeight() / 2;
            logicalTop = parentInlineBox.ascent() - logicalTopOffsetFromParentBaseline;
            break;
        }
        case VerticalAlign::Length: {
            auto logicalTopOffsetFromParentBaseline = *verticalAlign.baselineOffset + inlineLevelBox.ascent();
            logicalTop = parentInlineBox.ascent() - logicalTopOffsetFromParentBaseline;
            break;
        }
        case VerticalAlign::Sub: {
            auto logicalTopOffsetFromParentBaseline = inlineLevelBox.ascent() - (parentInlineBox.fontSize() / 5 + 1);
            logicalTop = parentInlineBox.ascent() - logicalTopOffsetFromParentBaseline;
            break;
        }
        case VerticalAlign::Super: {
            auto logicalTopOffsetFromParentBaseline = inlineLevelBox.ascent() + parentInlineBox.fontSize() / 3 + 1;
            logicalTop = parentInlineBox.ascent() - logicalTopOffsetFromParentBaseline;
            break;
        }
        // Note that (text)top/bottom align their layout bounds.
        case VerticalAlign::TextTop:
            logicalTop = inlineLevelBox.layoutBounds().ascent - inlineLevelBox.ascent();
            break;
        case VerticalAlign::TextBottom:
            logicalTop = parentInlineBox.logicalHeight() - inlineLevelBox.layoutBounds().descent - inlineLevelBox.ascent();
            break;
        default:
            ASSERT_NOT_IMPLEMENTED_YET();
            break;
        }
        inlineLevelBox.setLogicalTop(logicalTop);
    }

    for (auto index : lineBoxRelativeInlineLevelBoxes) {
        auto& inlineLevelBox = nonRootInlineLevelBoxes[index];
        auto logicalTop = InlineLayoutUnit { };
        switch (inlineLevelBox.verticalAlign().type) {
        case VerticalAlign::Top: {
            auto ascent = inlineLevelBox.layoutBounds().ascent;
            if (inlineLevelBox.isInlineBox())
                ascent = std::max(layoutBoundsForInlineBoxSubtree(nonRootInlineLevelBoxes, index).ascent, ascent);
            // Note that this logical top is not relative to the parent inline box.
            logicalTop = ascent - inlineLevelBox.ascent();
            break;
        }
        case VerticalAlign::Bottom: {
            auto descent = inlineLevelBox.layoutBounds().descent;
            if (inlineLevelBox.isInlineBox())
                descent = std::max(layoutBoundsForInlineBoxSubtree(nonRootInlineLevelBoxes, index).descent, descent);
            // Note that this logical top is not relative to the parent inline box.
            logicalTop = lineBoxLogicalHeight - (inlineLevelBox.ascent() + descent);
            break;
        }
        default:
            ASSERT_NOT_REACHED();
            break;
        }
        inlineLevelBox.setLogicalTop(logicalTop);
    }
}

InlineLayoutUnit LineBoxVerticalAligner::adjustForAnnotationIfNeeded(LineBox& lineBox, InlineLayoutUnit lineBoxHeight) const
{
    auto lineBoxTop = InlineLayoutUnit { };
    auto lineBoxBottom = lineBoxHeight;
    // At this point we have a properly aligned set of inline level boxes. Let's find out if annotation marks have enough space.
    auto adjustLineBoxHeightIfNeeded = [&] {
        auto adjustLineBoxTopAndBottomForInlineBox = [&](const InlineLevelBox& inlineLevelBox) {
            ASSERT(inlineLevelBox.isInlineBox() || inlineLevelBox.isAtomicInlineLevelBox());
            auto inlineBoxTop = lineBox.inlineLevelBoxAbsoluteTop(inlineLevelBox);
            auto inlineBoxBottom = inlineBoxTop + inlineLevelBox.logicalHeight();

            switch (inlineLevelBox.verticalAlign().type) {
            case VerticalAlign::Baseline:
            case VerticalAlign::Middle:
            case VerticalAlign::BaselineMiddle:
            case VerticalAlign::Length:
            case VerticalAlign::Sub:
            case VerticalAlign::Super:
            case VerticalAlign::TextTop:
            case VerticalAlign::TextBottom:
            case VerticalAlign::Bottom:
                if (auto aboveSpace = inlineLevelBox.annotationAbove())
                    lineBoxTop = std::min(lineBoxTop, inlineBoxTop - *aboveSpace);
                if (auto belowSpace = inlineLevelBox.annotationBelow())
                    lineBoxBottom = std::max(lineBoxBottom, inlineBoxBottom + *belowSpace);
                break;
            case VerticalAlign::Top: {
                // FIXME: Check if horizontal vs. vertical writing mode should be taking into account.
                auto annotationSpace = inlineLevelBox.annotationAbove().value_or(0.f) + inlineLevelBox.annotationBelow().value_or(0.f);
                lineBoxBottom = std::max(lineBoxBottom, inlineBoxBottom + annotationSpace);
                break;
            }
            default:
                ASSERT_NOT_IMPLEMENTED_YET();
                break;
            }
        };

        adjustLineBoxTopAndBottomForInlineBox(lineBox.rootInlineBox());
        for (auto& inlineLevelBox : lineBox.nonRootInlineLevelBoxes()) {
            if (inlineLevelBox.isInlineBox() || inlineLevelBox.isAtomicInlineLevelBox())
                adjustLineBoxTopAndBottomForInlineBox(inlineLevelBox);
        }

        return lineBoxBottom - lineBoxTop;
    };
    auto adjustedLineBoxHeight = adjustLineBoxHeightIfNeeded();

    if (lineBoxHeight != adjustedLineBoxHeight) {
        // Annotations needs some space.
        auto adjustContentTopWithAnnotationSpace = [&] {
            auto& rootInlineBox = lineBox.rootInlineBox();
            auto rootInlineBoxTop = rootInlineBox.logicalTop();
            auto annotationOffset = -lineBoxTop;
            rootInlineBox.setLogicalTop(annotationOffset + rootInlineBoxTop);

            for (auto& inlineLevelBox : lineBox.nonRootInlineLevelBoxes()) {
                switch (inlineLevelBox.verticalAlign().type) {
                case VerticalAlign::Top: {
                    auto inlineBoxTop = inlineLevelBox.layoutBounds().ascent - inlineLevelBox.ascent();
                    inlineLevelBox.setLogicalTop(inlineLevelBox.annotationAbove().value_or(0.f) + inlineBoxTop);
                    break;
                }
                case VerticalAlign::Bottom: {
                    auto inlineBoxTop = adjustedLineBoxHeight - (inlineLevelBox.layoutBounds().descent + inlineLevelBox.ascent());
                    inlineLevelBox.setLogicalTop(inlineBoxTop - inlineLevelBox.annotationBelow().value_or(0.f));
                    break;
                }
                default:
                    // These alignment positions are relative to the root inline box's baseline.
                    break;
                }
            }
        };
        adjustContentTopWithAnnotationSpace();
    }
    return adjustedLineBoxHeight;
}

}
}