Simple line layout: Bail out from Simple Line Layout on surrogate pairs.
[WebKit-https.git] / Source / WebCore / rendering / SimpleLineLayout.cpp
1 /*
2  * Copyright (C) 2013 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "SimpleLineLayout.h"
28
29 #include "FontCache.h"
30 #include "Frame.h"
31 #include "GraphicsContext.h"
32 #include "HTMLTextFormControlElement.h"
33 #include "HitTestLocation.h"
34 #include "HitTestRequest.h"
35 #include "HitTestResult.h"
36 #include "Hyphenation.h"
37 #include "InlineTextBox.h"
38 #include "LineWidth.h"
39 #include "Logging.h"
40 #include "PaintInfo.h"
41 #include "RenderBlockFlow.h"
42 #include "RenderChildIterator.h"
43 #include "RenderLineBreak.h"
44 #include "RenderStyle.h"
45 #include "RenderText.h"
46 #include "RenderTextControl.h"
47 #include "RenderView.h"
48 #include "Settings.h"
49 #include "SimpleLineLayoutFlowContents.h"
50 #include "SimpleLineLayoutFunctions.h"
51 #include "SimpleLineLayoutTextFragmentIterator.h"
52 #include "Text.h"
53 #include "TextPaintStyle.h"
54 #include "TextStream.h"
55
56 namespace WebCore {
57 namespace SimpleLineLayout {
58
59 #ifndef NDEBUG
60 void printSimpleLineLayoutCoverage();
61 void printSimpleLineLayoutBlockList();
62 void toggleSimpleLineLayout();
63 #endif
64
65 enum AvoidanceReason_ : uint64_t {
66     FlowIsInsideRegion                    = 1LLU  << 0,
67     FlowHasHorizonalWritingMode           = 1LLU  << 1,
68     FlowHasOutline                        = 1LLU  << 2,
69     FlowIsRuby                            = 1LLU  << 3,
70     FlowIsPaginated                       = 1LLU  << 4,
71     FlowHasTextOverflow                   = 1LLU  << 5,
72     FlowIsDepricatedFlexBox               = 1LLU  << 6,
73     FlowParentIsPlaceholderElement        = 1LLU  << 7,
74     FlowParentIsTextAreaWithWrapping      = 1LLU  << 8,
75     FlowHasNonSupportedChild              = 1LLU  << 9,
76     FlowHasUnsupportedFloat               = 1LLU  << 10,
77     FlowHasUnsupportedUnderlineDecoration = 1LLU  << 11,
78     FlowHasJustifiedNonLatinText          = 1LLU  << 12,
79     FlowHasOverflowVisible                = 1LLU  << 13,
80     FlowHasWebKitNBSPMode                 = 1LLU  << 14,
81     FlowIsNotLTR                          = 1LLU  << 15,
82     FlowHasLineBoxContainProperty         = 1LLU  << 16,
83     FlowIsNotTopToBottom                  = 1LLU  << 17,
84     FlowHasLineBreak                      = 1LLU  << 18,
85     FlowHasNonNormalUnicodeBiDi           = 1LLU  << 19,
86     FlowHasRTLOrdering                    = 1LLU  << 20,
87     FlowHasLineAlignEdges                 = 1LLU  << 21,
88     FlowHasLineSnap                       = 1LLU  << 22,
89     FlowHasTextEmphasisFillOrMark         = 1LLU  << 23,
90     FlowHasTextShadow                     = 1LLU  << 24,
91     FlowHasPseudoFirstLine                = 1LLU  << 25,
92     FlowHasPseudoFirstLetter              = 1LLU  << 26,
93     FlowHasTextCombine                    = 1LLU  << 27,
94     FlowHasTextFillBox                    = 1LLU  << 28,
95     FlowHasBorderFitLines                 = 1LLU  << 29,
96     FlowHasNonAutoLineBreak               = 1LLU  << 30,
97     FlowHasNonAutoTrailingWord            = 1LLU  << 31,
98     FlowHasSVGFont                        = 1LLU  << 32,
99     FlowTextIsEmpty                       = 1LLU  << 33,
100     FlowTextHasSoftHyphen                 = 1LLU  << 34,
101     FlowTextHasDirectionCharacter         = 1LLU  << 35,
102     FlowIsMissingPrimaryFont              = 1LLU  << 36,
103     FlowPrimaryFontIsInsufficient         = 1LLU  << 37,
104     FlowTextIsCombineText                 = 1LLU  << 38,
105     FlowTextIsRenderCounter               = 1LLU  << 39,
106     FlowTextIsRenderQuote                 = 1LLU  << 40,
107     FlowTextIsTextFragment                = 1LLU  << 41,
108     FlowTextIsSVGInlineText               = 1LLU  << 42,
109     FlowHasComplexFontCodePath            = 1LLU  << 43,
110     FeatureIsDisabled                     = 1LLU  << 44,
111     FlowHasNoParent                       = 1LLU  << 45,
112     FlowHasNoChild                        = 1LLU  << 46,
113     FlowChildIsSelected                   = 1LLU  << 47,
114     FlowHasHangingPunctuation             = 1LLU  << 48,
115     FlowFontHasOverflowGlyph              = 1LLU  << 49,
116     FlowTextHasSurrogatePair              = 1LLU  << 50,
117     EndOfReasons                          = 1LLU  << 51
118 };
119 const unsigned NoReason = 0;
120
121 typedef uint64_t AvoidanceReason;
122 typedef uint64_t AvoidanceReasonFlags;
123
124 enum class IncludeReasons { First , All };
125
126 #ifndef NDEBUG
127 #define SET_REASON_AND_RETURN_IF_NEEDED(reason, reasons, includeReasons) { \
128         reasons |= reason; \
129         if (includeReasons == IncludeReasons::First) \
130             return reasons; \
131     }
132 #else
133 #define SET_REASON_AND_RETURN_IF_NEEDED(reason, reasons, includeReasons) { \
134         ASSERT_UNUSED(includeReasons, includeReasons == IncludeReasons::First); \
135         reasons |= reason; \
136         return reasons; \
137     }
138 #endif
139
140
141 template <typename CharacterType> AvoidanceReasonFlags canUseForCharacter(CharacterType, bool textIsJustified, IncludeReasons);
142
143 template<> AvoidanceReasonFlags canUseForCharacter(UChar character, bool textIsJustified, IncludeReasons includeReasons)
144 {
145     AvoidanceReasonFlags reasons = { };
146     if (textIsJustified) {
147         // Include characters up to Latin Extended-B and some punctuation range when text is justified.
148         bool isLatinIncludingExtendedB = character <= 0x01FF;
149         bool isPunctuationRange = character >= 0x2010 && character <= 0x2027;
150         if (!(isLatinIncludingExtendedB || isPunctuationRange))
151             SET_REASON_AND_RETURN_IF_NEEDED(FlowHasJustifiedNonLatinText, reasons, includeReasons);
152     }
153
154     if (U16_IS_SURROGATE(character))
155         SET_REASON_AND_RETURN_IF_NEEDED(FlowTextHasSurrogatePair, reasons, includeReasons);
156     
157     UCharDirection direction = u_charDirection(character);
158     if (direction == U_RIGHT_TO_LEFT || direction == U_RIGHT_TO_LEFT_ARABIC
159         || direction == U_RIGHT_TO_LEFT_EMBEDDING || direction == U_RIGHT_TO_LEFT_OVERRIDE
160         || direction == U_LEFT_TO_RIGHT_EMBEDDING || direction == U_LEFT_TO_RIGHT_OVERRIDE
161         || direction == U_POP_DIRECTIONAL_FORMAT || direction == U_BOUNDARY_NEUTRAL)
162         SET_REASON_AND_RETURN_IF_NEEDED(FlowTextHasDirectionCharacter, reasons, includeReasons);
163
164     return reasons;
165 }
166
167 template<> AvoidanceReasonFlags canUseForCharacter(LChar, bool, IncludeReasons)
168 {
169     return { };
170 }
171
172 template <typename CharacterType>
173 static AvoidanceReasonFlags canUseForText(const CharacterType* text, unsigned length, const FontCascade& fontCascade, std::optional<float> lineHeightConstraint,
174     bool textIsJustified, IncludeReasons includeReasons)
175 {
176     AvoidanceReasonFlags reasons = { };
177     auto& primaryFont = fontCascade.primaryFont();
178     for (unsigned i = 0; i < length; ++i) {
179         auto character = text[i];
180         if (FontCascade::treatAsSpace(character))
181             continue;
182
183         if (character == softHyphen)
184             SET_REASON_AND_RETURN_IF_NEEDED(FlowTextHasSoftHyphen, reasons, includeReasons);
185
186         auto characterReasons = canUseForCharacter(character, textIsJustified, includeReasons);
187         if (characterReasons != NoReason)
188             SET_REASON_AND_RETURN_IF_NEEDED(characterReasons, reasons, includeReasons);
189
190         auto glyphData = fontCascade.glyphDataForCharacter(character, false);
191         if (!glyphData.isValid() || glyphData.font != &primaryFont)
192             SET_REASON_AND_RETURN_IF_NEEDED(FlowPrimaryFontIsInsufficient, reasons, includeReasons);
193
194         if (lineHeightConstraint && primaryFont.boundsForGlyph(glyphData.glyph).height() > *lineHeightConstraint)
195             SET_REASON_AND_RETURN_IF_NEEDED(FlowFontHasOverflowGlyph, reasons, includeReasons);
196     }
197     return reasons;
198 }
199
200 static AvoidanceReasonFlags canUseForText(StringView text, const FontCascade& fontCascade, std::optional<float> lineHeightConstraint, bool textIsJustified, IncludeReasons includeReasons)
201 {
202     if (text.is8Bit())
203         return canUseForText(text.characters8(), text.length(), fontCascade, lineHeightConstraint, textIsJustified, includeReasons);
204     return canUseForText(text.characters16(), text.length(), fontCascade, lineHeightConstraint, textIsJustified, includeReasons);
205 }
206
207 static AvoidanceReasonFlags canUseForFontAndText(const RenderBlockFlow& flow, IncludeReasons includeReasons)
208 {
209     AvoidanceReasonFlags reasons = { };
210     // We assume that all lines have metrics based purely on the primary font.
211     const auto& style = flow.style();
212     auto& fontCascade = style.fontCascade();
213     if (fontCascade.primaryFont().isLoading())
214         SET_REASON_AND_RETURN_IF_NEEDED(FlowIsMissingPrimaryFont, reasons, includeReasons);
215     std::optional<float> lineHeightConstraint;
216     if (style.lineBoxContain() & LineBoxContainGlyphs)
217         lineHeightConstraint = lineHeightFromFlow(flow).toFloat();
218     bool flowIsJustified = style.textAlign() == JUSTIFY;
219     for (const auto& textRenderer : childrenOfType<RenderText>(flow)) {
220         // FIXME: Do not return until after checking all children.
221         if (!textRenderer.textLength())
222             SET_REASON_AND_RETURN_IF_NEEDED(FlowTextIsEmpty, reasons, includeReasons);
223         if (textRenderer.isCombineText())
224             SET_REASON_AND_RETURN_IF_NEEDED(FlowTextIsCombineText, reasons, includeReasons);
225         if (textRenderer.isCounter())
226             SET_REASON_AND_RETURN_IF_NEEDED(FlowTextIsRenderCounter, reasons, includeReasons);
227         if (textRenderer.isQuote())
228             SET_REASON_AND_RETURN_IF_NEEDED(FlowTextIsRenderQuote, reasons, includeReasons);
229         if (textRenderer.isTextFragment())
230             SET_REASON_AND_RETURN_IF_NEEDED(FlowTextIsTextFragment, reasons, includeReasons);
231         if (textRenderer.isSVGInlineText())
232             SET_REASON_AND_RETURN_IF_NEEDED(FlowTextIsSVGInlineText, reasons, includeReasons);
233         if (!textRenderer.canUseSimpleFontCodePath())
234             SET_REASON_AND_RETURN_IF_NEEDED(FlowHasComplexFontCodePath, reasons, includeReasons);
235
236         auto textReasons = canUseForText(textRenderer.stringView(), fontCascade, lineHeightConstraint, flowIsJustified, includeReasons);
237         if (textReasons != NoReason)
238             SET_REASON_AND_RETURN_IF_NEEDED(textReasons, reasons, includeReasons);
239     }
240     return reasons;
241 }
242
243 static AvoidanceReasonFlags canUseForStyle(const RenderStyle& style, IncludeReasons includeReasons)
244 {
245     AvoidanceReasonFlags reasons = { };
246     if (style.textOverflow())
247         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasTextOverflow, reasons, includeReasons);
248     if ((style.textDecorationsInEffect() & TextDecorationUnderline) && style.textUnderlinePosition() == TextUnderlinePositionUnder)
249         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasUnsupportedUnderlineDecoration, reasons, includeReasons);
250     // Non-visible overflow should be pretty easy to support.
251     if (style.overflowX() != OVISIBLE || style.overflowY() != OVISIBLE)
252         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasOverflowVisible, reasons, includeReasons);
253     if (!style.isLeftToRightDirection())
254         SET_REASON_AND_RETURN_IF_NEEDED(FlowIsNotLTR, reasons, includeReasons);
255     if (!(style.lineBoxContain() & LineBoxContainBlock))
256         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasLineBoxContainProperty, reasons, includeReasons);
257     if (style.writingMode() != TopToBottomWritingMode)
258         SET_REASON_AND_RETURN_IF_NEEDED(FlowIsNotTopToBottom, reasons, includeReasons);
259     if (style.lineBreak() != LineBreakAuto)
260         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasLineBreak, reasons, includeReasons);
261     if (style.unicodeBidi() != UBNormal)
262         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasNonNormalUnicodeBiDi, reasons, includeReasons);
263     if (style.rtlOrdering() != LogicalOrder)
264         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasRTLOrdering, reasons, includeReasons);
265     if (style.lineAlign() != LineAlignNone)
266         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasLineAlignEdges, reasons, includeReasons);
267     if (style.lineSnap() != LineSnapNone)
268         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasLineSnap, reasons, includeReasons);
269     if (style.textEmphasisFill() != TextEmphasisFillFilled || style.textEmphasisMark() != TextEmphasisMarkNone)
270         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasTextEmphasisFillOrMark, reasons, includeReasons);
271     if (style.textShadow())
272         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasTextShadow, reasons, includeReasons);
273     if (style.hasPseudoStyle(FIRST_LINE))
274         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasPseudoFirstLine, reasons, includeReasons);
275     if (style.hasPseudoStyle(FIRST_LETTER))
276         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasPseudoFirstLetter, reasons, includeReasons);
277     if (style.hasTextCombine())
278         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasTextCombine, reasons, includeReasons);
279     if (style.backgroundClip() == TextFillBox)
280         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasTextFillBox, reasons, includeReasons);
281     if (style.borderFit() == BorderFitLines)
282         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasBorderFitLines, reasons, includeReasons);
283     if (style.lineBreak() != LineBreakAuto)
284         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasNonAutoLineBreak, reasons, includeReasons);
285     if (style.nbspMode() != NBNORMAL)
286         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasWebKitNBSPMode, reasons, includeReasons);
287 #if ENABLE(CSS_TRAILING_WORD)
288     if (style.trailingWord() != TrailingWord::Auto)
289         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasNonAutoTrailingWord, reasons, includeReasons);
290 #endif
291     return reasons;
292 }
293
294 static AvoidanceReasonFlags canUseForWithReason(const RenderBlockFlow& flow, IncludeReasons includeReasons)
295 {
296 #ifndef NDEBUG
297     static std::once_flag onceFlag;
298     std::call_once(onceFlag, [] {
299         registerNotifyCallback("com.apple.WebKit.showSimpleLineLayoutCoverage", printSimpleLineLayoutCoverage);
300         registerNotifyCallback("com.apple.WebKit.showSimpleLineLayoutReasons", printSimpleLineLayoutBlockList);
301         registerNotifyCallback("com.apple.WebKit.toggleSimpleLineLayout", toggleSimpleLineLayout);
302     });
303 #endif
304     AvoidanceReasonFlags reasons = { };
305     if (!flow.settings().simpleLineLayoutEnabled())
306         SET_REASON_AND_RETURN_IF_NEEDED(FeatureIsDisabled, reasons, includeReasons);
307     if (!flow.parent())
308         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasNoParent, reasons, includeReasons);
309     if (!flow.firstChild())
310         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasNoChild, reasons, includeReasons);
311     if (flow.flowThreadState() != RenderObject::NotInsideFlowThread)
312         SET_REASON_AND_RETURN_IF_NEEDED(FlowIsInsideRegion, reasons, includeReasons);
313     if (!flow.isHorizontalWritingMode())
314         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasHorizonalWritingMode, reasons, includeReasons);
315     if (flow.hasOutline())
316         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasOutline, reasons, includeReasons);
317     if (flow.isRubyText() || flow.isRubyBase())
318         SET_REASON_AND_RETURN_IF_NEEDED(FlowIsRuby, reasons, includeReasons);
319     if (flow.style().hangingPunctuation() != NoHangingPunctuation)
320         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasHangingPunctuation, reasons, includeReasons);
321     
322     // Printing does pagination without a flow thread.
323     if (flow.document().paginated())
324         SET_REASON_AND_RETURN_IF_NEEDED(FlowIsPaginated, reasons, includeReasons);
325     if (flow.firstLineBlock())
326         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasPseudoFirstLine, reasons, includeReasons);
327     if (flow.isAnonymousBlock() && flow.parent()->style().textOverflow())
328         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasTextOverflow, reasons, includeReasons);
329     if (flow.parent()->isDeprecatedFlexibleBox())
330         SET_REASON_AND_RETURN_IF_NEEDED(FlowIsDepricatedFlexBox, reasons, includeReasons);
331     // FIXME: Placeholders do something strange.
332     if (is<RenderTextControl>(*flow.parent()) && downcast<RenderTextControl>(*flow.parent()).textFormControlElement().placeholderElement())
333         SET_REASON_AND_RETURN_IF_NEEDED(FlowParentIsPlaceholderElement, reasons, includeReasons);
334     // FIXME: Implementation of wrap=hard looks into lineboxes.
335     if (flow.parent()->isTextArea() && flow.parent()->element()->hasAttributeWithoutSynchronization(HTMLNames::wrapAttr))
336         SET_REASON_AND_RETURN_IF_NEEDED(FlowParentIsTextAreaWithWrapping, reasons, includeReasons);
337     // This currently covers <blockflow>#text</blockflow>, <blockflow>#text<br></blockflow> and mutiple (sibling) RenderText cases.
338     // The <blockflow><inline>#text</inline></blockflow> case is also popular and should be relatively easy to cover.
339     for (const auto* child = flow.firstChild(); child;) {
340         if (child->selectionState() != RenderObject::SelectionNone)
341             SET_REASON_AND_RETURN_IF_NEEDED(FlowChildIsSelected, reasons, includeReasons);
342         if (is<RenderText>(*child)) {
343             child = child->nextSibling();
344             continue;
345         }
346         if (is<RenderLineBreak>(child) && !downcast<RenderLineBreak>(*child).isWBR() && child->style().clear() == CNONE) {
347             child = child->nextSibling();
348             continue;
349         }
350         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasNonSupportedChild, reasons, includeReasons);
351         break;
352     }
353     auto styleReasons = canUseForStyle(flow.style(), includeReasons);
354     if (styleReasons != NoReason)
355         SET_REASON_AND_RETURN_IF_NEEDED(styleReasons, reasons, includeReasons);
356     // We can't use the code path if any lines would need to be shifted below floats. This is because we don't keep per-line y coordinates.
357     if (flow.containsFloats()) {
358         float minimumWidthNeeded = std::numeric_limits<float>::max();
359         for (const auto& textRenderer : childrenOfType<RenderText>(flow)) {
360             minimumWidthNeeded = std::min(minimumWidthNeeded, textRenderer.minLogicalWidth());
361
362             for (auto& floatingObject : *flow.floatingObjectSet()) {
363                 ASSERT(floatingObject);
364                 // if a float has a shape, we cannot tell if content will need to be shifted until after we lay it out,
365                 // since the amount of space is not uniform for the height of the float.
366                 if (floatingObject->renderer().shapeOutsideInfo())
367                     SET_REASON_AND_RETURN_IF_NEEDED(FlowHasUnsupportedFloat, reasons, includeReasons);
368                 float availableWidth = flow.availableLogicalWidthForLine(floatingObject->y(), DoNotIndentText);
369                 if (availableWidth < minimumWidthNeeded)
370                     SET_REASON_AND_RETURN_IF_NEEDED(FlowHasUnsupportedFloat, reasons, includeReasons);
371             }
372         }
373     }
374     auto fontAndTextReasons = canUseForFontAndText(flow, includeReasons);
375     if (fontAndTextReasons != NoReason)
376         SET_REASON_AND_RETURN_IF_NEEDED(fontAndTextReasons, reasons, includeReasons);
377     return reasons;
378 }
379
380 bool canUseFor(const RenderBlockFlow& flow)
381 {
382     return canUseForWithReason(flow, IncludeReasons::First) == NoReason;
383 }
384
385 static float computeLineLeft(ETextAlign textAlign, float availableWidth, float committedWidth, float logicalLeftOffset)
386 {
387     float remainingWidth = availableWidth - committedWidth;
388     float left = logicalLeftOffset;
389     switch (textAlign) {
390     case LEFT:
391     case WEBKIT_LEFT:
392     case TASTART:
393         return left;
394     case RIGHT:
395     case WEBKIT_RIGHT:
396     case TAEND:
397         return left + std::max<float>(remainingWidth, 0);
398     case CENTER:
399     case WEBKIT_CENTER:
400         return left + std::max<float>(remainingWidth / 2, 0);
401     case JUSTIFY:
402         ASSERT_NOT_REACHED();
403         break;
404     }
405     ASSERT_NOT_REACHED();
406     return 0;
407 }
408
409 static void revertRuns(Layout::RunVector& runs, unsigned positionToRevertTo, float width)
410 {
411     while (runs.size()) {
412         auto& lastRun = runs.last();
413         if (lastRun.end <= positionToRevertTo)
414             break;
415         if (lastRun.start >= positionToRevertTo) {
416             // Revert this run completely.
417             width -= (lastRun.logicalRight - lastRun.logicalLeft);
418             runs.removeLast();
419         } else {
420             lastRun.logicalRight -= width;
421             width = 0;
422             lastRun.end = positionToRevertTo;
423             // Partial removal.
424             break;
425         }
426     }
427 }
428
429 class LineState {
430 public:
431     void setAvailableWidth(float width) { m_availableWidth = width; }
432     void setCollapedWhitespaceWidth(float width) { m_collapsedWhitespaceWidth = width; }
433     void setLogicalLeftOffset(float offset) { m_logicalLeftOffset = offset; }
434     void setOverflowedFragment(const TextFragmentIterator::TextFragment& fragment) { m_overflowedFragment = fragment; }
435     void setNeedsAllFragments()
436     {
437         ASSERT(!m_fragments);
438         m_fragments.emplace();
439     }
440
441     float availableWidth() const { return m_availableWidth; }
442     float logicalLeftOffset() const { return m_logicalLeftOffset; }
443     const TextFragmentIterator::TextFragment& overflowedFragment() const { return m_overflowedFragment; }
444     bool hasTrailingWhitespace() const { return m_lastFragment.type() == TextFragmentIterator::TextFragment::Whitespace; }
445     TextFragmentIterator::TextFragment lastFragment() const { return m_lastFragment; }
446     bool isWhitespaceOnly() const { return m_trailingWhitespaceWidth && m_runsWidth == m_trailingWhitespaceWidth; }
447     bool fits(float extra) const { return m_availableWidth >= m_runsWidth + extra; }
448     bool firstCharacterFits() const { return m_firstCharacterFits; }
449     float width() const { return m_runsWidth; }
450     std::pair<unsigned, bool> expansionOpportunityCount(unsigned from, unsigned to) const
451     {
452         ASSERT(m_fragments);
453         // linebreak runs are special.
454         if (from == to)
455             return std::make_pair(0, false);
456         unsigned expansionOpportunityCount = 0;
457         auto previousFragmentType = TextFragmentIterator::TextFragment::ContentEnd;
458         for (const auto& fragment : *m_fragments) {
459             if (fragment.end() <= from)
460                 continue;
461             auto currentFragmentType = fragment.type();
462             auto expansionOpportunity = this->expansionOpportunity(currentFragmentType, previousFragmentType);
463             if (expansionOpportunity)
464                 ++expansionOpportunityCount;
465             previousFragmentType = currentFragmentType;
466             if (fragment.end() >= to)
467                 return std::make_pair(expansionOpportunityCount, expansionOpportunity);
468         }
469         ASSERT_NOT_REACHED();
470         return std::make_pair(expansionOpportunityCount, false);
471     }
472
473     bool isEmpty() const
474     {
475         if (!m_lastFragment.isValid())
476             return true;
477         if (!m_lastCompleteFragment.isEmpty())
478             return false;
479         return m_lastFragment.overlapsToNextRenderer();
480     }
481
482     static inline unsigned endPositionForCollapsedFragment(const TextFragmentIterator::TextFragment& fragment)
483     {
484         return fragment.isCollapsed() ? fragment.start() + 1 : fragment.end();
485     }
486
487     void appendFragmentAndCreateRunIfNeeded(const TextFragmentIterator::TextFragment& fragment, Layout::RunVector& runs)
488     {
489         // Adjust end position while collapsing.
490         unsigned endPosition = endPositionForCollapsedFragment(fragment);
491         // New line needs new run.
492         if (!m_runsWidth) {
493             ASSERT(!m_uncompletedWidth);
494             runs.append(Run(fragment.start(), endPosition, m_runsWidth, m_runsWidth + fragment.width(), false, fragment.hasHyphen()));
495         } else {
496             // Advance last completed fragment when the previous fragment is all set (including multiple parts across renderers)
497             if ((m_lastFragment.type() != fragment.type()) || !m_lastFragment.overlapsToNextRenderer()) {
498                 m_lastCompleteFragment = m_lastFragment;
499                 m_uncompletedWidth = fragment.width();
500             } else
501                 m_uncompletedWidth += fragment.width();
502             // Collapse neighbouring whitespace, if they are across multiple renderers and are not collapsed yet.
503             if (m_lastFragment.isCollapsible() && fragment.isCollapsible()) {
504                 ASSERT(m_lastFragment.isLastInRenderer());
505                 if (!m_lastFragment.isCollapsed()) {
506                     // Line width needs to be adjusted so that now it takes collapsing into consideration.
507                     m_runsWidth -= (m_lastFragment.width() - m_collapsedWhitespaceWidth);
508                 }
509                 // This fragment is collapsed completely. No run is needed.
510                 return;
511             }
512             if (m_lastFragment.isLastInRenderer() || m_lastFragment.isCollapsed())
513                 runs.append(Run(fragment.start(), endPosition, m_runsWidth, m_runsWidth + fragment.width(), false, fragment.hasHyphen()));
514             else {
515                 Run& lastRun = runs.last();
516                 lastRun.end = endPosition;
517                 lastRun.logicalRight += fragment.width();
518                 ASSERT(!lastRun.hasHyphen);
519                 lastRun.hasHyphen = fragment.hasHyphen();
520             }
521         }
522         m_runsWidth += fragment.width();
523         m_lastFragment = fragment;
524         if (m_fragments)
525             (*m_fragments).append(fragment);
526
527         if (fragment.type() == TextFragmentIterator::TextFragment::Whitespace)
528             m_trailingWhitespaceWidth += fragment.width();
529         else {
530             m_trailingWhitespaceWidth = 0;
531             m_lastNonWhitespaceFragment = fragment;
532         }
533
534         if (!m_firstCharacterFits)
535             m_firstCharacterFits = fragment.start() + 1 > endPosition || m_runsWidth <= m_availableWidth;
536     }
537
538     TextFragmentIterator::TextFragment revertToLastCompleteFragment(Layout::RunVector& runs)
539     {
540         if (!m_uncompletedWidth) {
541             ASSERT(m_lastFragment == m_lastCompleteFragment);
542             return m_lastFragment;
543         }
544         ASSERT(m_lastFragment.isValid());
545         m_runsWidth -= m_uncompletedWidth;
546         revertRuns(runs, endPositionForCollapsedFragment(m_lastCompleteFragment), m_uncompletedWidth);
547         m_uncompletedWidth = 0;
548         ASSERT(m_lastCompleteFragment.isValid());
549         return m_lastCompleteFragment;
550     }
551
552     void removeTrailingWhitespace(Layout::RunVector& runs)
553     {
554         if (m_lastFragment.type() != TextFragmentIterator::TextFragment::Whitespace || m_lastFragment.end() == m_lastNonWhitespaceFragment.end())
555             return;
556         revertRuns(runs, m_lastNonWhitespaceFragment.end(), m_trailingWhitespaceWidth);
557         m_runsWidth -= m_trailingWhitespaceWidth;
558         m_lastFragment = m_lastNonWhitespaceFragment;
559     }
560
561 private:
562     bool expansionOpportunity(TextFragmentIterator::TextFragment::Type currentFragmentType, TextFragmentIterator::TextFragment::Type previousFragmentType) const
563     {
564         return (currentFragmentType == TextFragmentIterator::TextFragment::Whitespace
565             || (currentFragmentType == TextFragmentIterator::TextFragment::NonWhitespace && previousFragmentType == TextFragmentIterator::TextFragment::NonWhitespace));
566     }
567
568     float m_availableWidth { 0 };
569     float m_logicalLeftOffset { 0 };
570     float m_runsWidth { 0 };
571     TextFragmentIterator::TextFragment m_overflowedFragment;
572     TextFragmentIterator::TextFragment m_lastFragment;
573     TextFragmentIterator::TextFragment m_lastNonWhitespaceFragment;
574     TextFragmentIterator::TextFragment m_lastCompleteFragment;
575     float m_uncompletedWidth { 0 };
576     float m_trailingWhitespaceWidth { 0 }; // Use this to remove trailing whitespace without re-mesuring the text.
577     float m_collapsedWhitespaceWidth { 0 };
578     // Having one character on the line does not necessarily mean it actually fits.
579     // First character of the first fragment might be forced on to the current line even if it does not fit.
580     bool m_firstCharacterFits { false };
581     std::optional<Vector<TextFragmentIterator::TextFragment, 30>> m_fragments;
582 };
583
584 class FragmentForwardIterator : public std::iterator<std::forward_iterator_tag, unsigned> {
585 public:
586     FragmentForwardIterator(unsigned fragmentIndex)
587         : m_fragmentIndex(fragmentIndex)
588     {
589     }
590
591     FragmentForwardIterator& operator++()
592     {
593         ++m_fragmentIndex;
594         return *this;
595     }
596
597     bool operator!=(const FragmentForwardIterator& other) const { return m_fragmentIndex != other.m_fragmentIndex; }
598     bool operator==(const FragmentForwardIterator& other) const { return m_fragmentIndex == other.m_fragmentIndex; }
599     unsigned operator*() const { return m_fragmentIndex; }
600
601 private:
602     unsigned m_fragmentIndex { 0 };
603 };
604
605 static FragmentForwardIterator begin(const TextFragmentIterator::TextFragment& fragment)  { return FragmentForwardIterator(fragment.start()); }
606 static FragmentForwardIterator end(const TextFragmentIterator::TextFragment& fragment)  { return FragmentForwardIterator(fragment.end()); }
607
608 static bool preWrap(const TextFragmentIterator::Style& style)
609 {
610     return style.wrapLines && !style.collapseWhitespace;
611 }
612     
613 static void removeTrailingWhitespace(LineState& lineState, Layout::RunVector& runs, const TextFragmentIterator& textFragmentIterator)
614 {
615     if (!lineState.hasTrailingWhitespace())
616         return;
617     // Remove collapsed whitespace, or non-collapsed pre-wrap whitespace, unless it's the only content on the line -so removing the whitesapce
618     // would produce an empty line.
619     const auto& style = textFragmentIterator.style();
620     bool collapseWhitespace = style.collapseWhitespace | preWrap(style);
621     if (!collapseWhitespace)
622         return;
623     if (preWrap(style) && lineState.isWhitespaceOnly())
624         return;
625     lineState.removeTrailingWhitespace(runs);
626 }
627
628 static void updateLineConstrains(const RenderBlockFlow& flow, LineState& line, const TextFragmentIterator::Style& style, bool isFirstLine)
629 {
630     bool shouldApplyTextIndent = !flow.isAnonymous() || flow.parent()->firstChild() == &flow;
631     LayoutUnit height = flow.logicalHeight();
632     line.setLogicalLeftOffset(flow.logicalLeftOffsetForLine(height, DoNotIndentText) + (shouldApplyTextIndent && isFirstLine ? flow.textIndentOffset() : LayoutUnit(0)));
633     float logicalRightOffset = flow.logicalRightOffsetForLine(height, DoNotIndentText);
634     line.setAvailableWidth(std::max<float>(0, logicalRightOffset - line.logicalLeftOffset()));
635     if (style.textAlign == JUSTIFY)
636         line.setNeedsAllFragments();
637 }
638
639 static std::optional<unsigned> hyphenPositionForFragment(unsigned splitPosition, TextFragmentIterator::TextFragment& fragmentToSplit,
640     const TextFragmentIterator& textFragmentIterator, float availableWidth)
641 {
642     auto& style = textFragmentIterator.style();
643     bool shouldHyphenate = style.shouldHyphenate && (!style.hyphenLimitLines || fragmentToSplit.wrappingWithHyphenCounter() < *style.hyphenLimitLines);
644     if (!shouldHyphenate)
645         return std::nullopt;
646
647     if (!enoughWidthForHyphenation(availableWidth, style.font.pixelSize()))
648         return std::nullopt;
649
650     // We might be able to fit the hyphen at the split position.
651     auto splitPositionWithHyphen = splitPosition;
652     // Find a splitting position where hyphen surely fits.
653     unsigned start = fragmentToSplit.start();
654     auto leftSideWidth = textFragmentIterator.textWidth(start, splitPosition, 0);
655     while (leftSideWidth + style.hyphenStringWidth > availableWidth) {
656         if (--splitPositionWithHyphen <= start)
657             return std::nullopt; // No space for hyphen.
658         leftSideWidth -= textFragmentIterator.textWidth(splitPositionWithHyphen, splitPositionWithHyphen + 1, 0);
659     }
660     ASSERT(splitPositionWithHyphen > start);
661     return textFragmentIterator.lastHyphenPosition(fragmentToSplit, splitPositionWithHyphen + 1);
662 }
663
664 static TextFragmentIterator::TextFragment splitFragmentToFitLine(TextFragmentIterator::TextFragment& fragmentToSplit, float availableWidth, bool keepAtLeastOneCharacter, const TextFragmentIterator& textFragmentIterator)
665 {
666     // FIXME: add surrogate pair support.
667     unsigned start = fragmentToSplit.start();
668     auto it = std::upper_bound(begin(fragmentToSplit), end(fragmentToSplit), availableWidth, [&textFragmentIterator, start](float availableWidth, unsigned index) {
669         // FIXME: use the actual left position of the line (instead of 0) to calculated width. It might give false width for tab characters.
670         return availableWidth < textFragmentIterator.textWidth(start, index + 1, 0);
671     });
672     unsigned splitPosition = (*it);
673     // Does first character fit this line?
674     if (splitPosition == start) {
675         if (keepAtLeastOneCharacter)
676             ++splitPosition;
677     } else if (auto hyphenPosition = hyphenPositionForFragment(splitPosition, fragmentToSplit, textFragmentIterator, availableWidth))
678         return fragmentToSplit.splitWithHyphen(*hyphenPosition, textFragmentIterator);
679     return fragmentToSplit.split(splitPosition, textFragmentIterator);
680 }
681
682 enum PreWrapLineBreakRule { Preserve, Ignore };
683
684 static TextFragmentIterator::TextFragment consumeLineBreakIfNeeded(const TextFragmentIterator::TextFragment& fragment, TextFragmentIterator& textFragmentIterator, LineState& line, Layout::RunVector& runs,
685     PreWrapLineBreakRule preWrapLineBreakRule = PreWrapLineBreakRule::Preserve)
686 {
687     if (!fragment.isLineBreak())
688         return fragment;
689
690     if (preWrap(textFragmentIterator.style()) && preWrapLineBreakRule != PreWrapLineBreakRule::Ignore)
691         return fragment;
692
693     // <br> always produces a run. (required by testing output)
694     if (fragment.type() == TextFragmentIterator::TextFragment::HardLineBreak)
695         line.appendFragmentAndCreateRunIfNeeded(fragment, runs);
696     return textFragmentIterator.nextTextFragment();
697 }
698
699 static TextFragmentIterator::TextFragment skipWhitespaceIfNeeded(const TextFragmentIterator::TextFragment& fragment, TextFragmentIterator& textFragmentIterator)
700 {
701     if (!textFragmentIterator.style().collapseWhitespace)
702         return fragment;
703
704     TextFragmentIterator::TextFragment firstNonWhitespaceFragment = fragment;
705     while (firstNonWhitespaceFragment.type() == TextFragmentIterator::TextFragment::Whitespace)
706         firstNonWhitespaceFragment = textFragmentIterator.nextTextFragment();
707     return firstNonWhitespaceFragment;
708 }
709
710 static TextFragmentIterator::TextFragment firstFragment(TextFragmentIterator& textFragmentIterator, LineState& currentLine, const LineState& previousLine, Layout::RunVector& runs)
711 {
712     // Handle overflowed fragment from previous line.
713     TextFragmentIterator::TextFragment firstFragment(previousLine.overflowedFragment());
714
715     if (firstFragment.isEmpty())
716         firstFragment = textFragmentIterator.nextTextFragment();
717     else if (firstFragment.type() == TextFragmentIterator::TextFragment::Whitespace && preWrap(textFragmentIterator.style()) && previousLine.firstCharacterFits()) {
718         // Special overflow pre-wrap whitespace handling: skip the overflowed whitespace (even when style says not-collapsible) if we managed to fit at least one character on the previous line.
719         firstFragment = textFragmentIterator.nextTextFragment();
720         // If skipping the whitespace puts us on a newline, skip the newline too as we already wrapped the line.
721         firstFragment = consumeLineBreakIfNeeded(firstFragment, textFragmentIterator, currentLine, runs, PreWrapLineBreakRule::Ignore);
722     }
723     return skipWhitespaceIfNeeded(firstFragment, textFragmentIterator);
724 }
725
726 static void forceFragmentToLine(LineState& line, TextFragmentIterator& textFragmentIterator, Layout::RunVector& runs, const TextFragmentIterator::TextFragment& fragment)
727 {
728     line.appendFragmentAndCreateRunIfNeeded(fragment, runs);
729     // Check if there are more fragments to add to the current line.
730     auto nextFragment = textFragmentIterator.nextTextFragment();
731     if (fragment.overlapsToNextRenderer()) {
732         while (true) {
733             if (nextFragment.type() != fragment.type())
734                 break;
735             line.appendFragmentAndCreateRunIfNeeded(nextFragment, runs);
736             // Does it overlap to the next segment?
737             if (!nextFragment.overlapsToNextRenderer())
738                 return;
739             nextFragment = textFragmentIterator.nextTextFragment();
740         }
741     }
742     // When the forced fragment is followed by either whitespace and/or line break, consume them too, otherwise we end up with an extra whitespace and/or line break.
743     nextFragment = skipWhitespaceIfNeeded(nextFragment, textFragmentIterator);
744     nextFragment = consumeLineBreakIfNeeded(nextFragment, textFragmentIterator, line, runs);
745     line.setOverflowedFragment(nextFragment);
746 }
747
748 static bool createLineRuns(LineState& line, const LineState& previousLine, Layout::RunVector& runs, TextFragmentIterator& textFragmentIterator)
749 {
750     const auto& style = textFragmentIterator.style();
751     line.setCollapedWhitespaceWidth(style.spaceWidth + style.wordSpacing);
752     bool lineCanBeWrapped = style.wrapLines || style.breakFirstWordOnOverflow || style.breakAnyWordOnOverflow;
753     auto fragment = firstFragment(textFragmentIterator, line, previousLine, runs);
754     while (fragment.type() != TextFragmentIterator::TextFragment::ContentEnd) {
755         // Hard linebreak.
756         if (fragment.isLineBreak()) {
757             // Add the new line fragment only if there's nothing on the line. (otherwise the extra new line character would show up at the end of the content.)
758             if (line.isEmpty() || fragment.type() == TextFragmentIterator::TextFragment::HardLineBreak) {
759                 if (style.textAlign == RIGHT || style.textAlign == WEBKIT_RIGHT)
760                     line.removeTrailingWhitespace(runs);
761                 line.appendFragmentAndCreateRunIfNeeded(fragment, runs);
762             }
763             break;
764         }
765         if (lineCanBeWrapped && !line.fits(fragment.width())) {
766             // Overflow wrapping behaviour:
767             // 1. Whitesapce collapse on: whitespace is skipped. Jump to next line.
768             // 2. Whitespace collapse off: whitespace is wrapped.
769             // 3. First, non-whitespace fragment is either wrapped or kept on the line. (depends on overflow-wrap)
770             // 5. Non-whitespace fragment when there's already another fragment on the line either gets wrapped (word-break: break-all)
771             // or gets pushed to the next line.
772             bool emptyLine = line.isEmpty();
773             // Whitespace fragment.
774             if (fragment.type() == TextFragmentIterator::TextFragment::Whitespace) {
775                 if (!style.collapseWhitespace) {
776                     // Split the fragment; (modified)fragment stays on this line, overflowedFragment is pushed to next line.
777                     line.setOverflowedFragment(splitFragmentToFitLine(fragment, line.availableWidth() - line.width(), emptyLine, textFragmentIterator));
778                     line.appendFragmentAndCreateRunIfNeeded(fragment, runs);
779                 }
780                 // When whitespace collapse is on, whitespace that doesn't fit is simply skipped.
781                 break;
782             }
783             // Non-whitespace fragment. (!style.wrapLines: bug138102(preserve existing behavior)
784             if (((emptyLine && style.breakFirstWordOnOverflow) || style.breakAnyWordOnOverflow) || !style.wrapLines) {
785                 // Split the fragment; (modified)fragment stays on this line, overflowedFragment is pushed to next line.
786                 line.setOverflowedFragment(splitFragmentToFitLine(fragment, line.availableWidth() - line.width(), emptyLine, textFragmentIterator));
787                 line.appendFragmentAndCreateRunIfNeeded(fragment, runs);
788                 break;
789             }
790             ASSERT(fragment.type() == TextFragmentIterator::TextFragment::NonWhitespace);
791             // Find out if this non-whitespace fragment has a hyphen where we can break.
792             if (style.shouldHyphenate) {
793                 auto fragmentToSplit = fragment;
794                 // Split and check if we actually ended up with a hyphen.
795                 auto overflowFragment = splitFragmentToFitLine(fragmentToSplit, line.availableWidth() - line.width(), emptyLine, textFragmentIterator);
796                 if (fragmentToSplit.hasHyphen()) {
797                     line.setOverflowedFragment(overflowFragment);
798                     line.appendFragmentAndCreateRunIfNeeded(fragmentToSplit, runs);
799                     break;
800                 }
801                 // No hyphen, no split.
802             }
803             // Non-breakable non-whitespace first fragment. Add it to the current line. -it overflows though.
804             if (emptyLine) {
805                 forceFragmentToLine(line, textFragmentIterator, runs, fragment);
806                 break;
807             }
808             // Non-breakable non-whitespace fragment when there's already content on the line. Push it to the next line.
809             ASSERT(line.lastFragment().isValid());
810             if (line.lastFragment().overlapsToNextRenderer()) {
811                 // Check if this fragment is a continuation of a previous segment. In such cases, we need to remove them all.
812                 textFragmentIterator.revertToEndOfFragment(line.revertToLastCompleteFragment(runs));
813                 break;
814             }
815             line.setOverflowedFragment(fragment);
816             break;
817         }
818         line.appendFragmentAndCreateRunIfNeeded(fragment, runs);
819         // Find the next text fragment.
820         fragment = textFragmentIterator.nextTextFragment(line.width());
821     }
822     return (fragment.type() == TextFragmentIterator::TextFragment::ContentEnd && line.overflowedFragment().isEmpty()) || line.overflowedFragment().type() == TextFragmentIterator::TextFragment::ContentEnd;
823 }
824
825 static ExpansionBehavior expansionBehavior(bool isAfterExpansion, bool lastRunOnLine)
826 {
827     ExpansionBehavior expansionBehavior;
828     expansionBehavior = isAfterExpansion ? ForbidLeadingExpansion : AllowLeadingExpansion;
829     expansionBehavior |= lastRunOnLine ? ForbidTrailingExpansion : AllowTrailingExpansion;
830     return expansionBehavior;
831 }
832
833 static void justifyRuns(const LineState& line, Layout::RunVector& runs, unsigned firstRunIndex)
834 {
835     ASSERT(runs.size());
836     auto widthToDistribute = line.availableWidth() - line.width();
837     if (widthToDistribute <= 0)
838         return;
839
840     auto lastRunIndex = runs.size() - 1;
841     ASSERT(firstRunIndex <= lastRunIndex);
842     Vector<std::pair<unsigned, ExpansionBehavior>> expansionOpportunityList;
843     unsigned expansionOpportunityCountOnThisLine = 0;
844     auto isAfterExpansion = true;
845     for (auto i = firstRunIndex; i <= lastRunIndex; ++i) {
846         const auto& run = runs.at(i);
847         unsigned opportunityCountInRun = 0;
848         std::tie(opportunityCountInRun, isAfterExpansion) = line.expansionOpportunityCount(run.start, run.end);
849         expansionOpportunityList.append(std::make_pair(opportunityCountInRun, expansionBehavior(isAfterExpansion, i == lastRunIndex)));
850         expansionOpportunityCountOnThisLine += opportunityCountInRun;
851     }
852     if (!expansionOpportunityCountOnThisLine)
853         return;
854
855     ASSERT(expansionOpportunityList.size() == lastRunIndex - firstRunIndex + 1);
856     auto expansion = widthToDistribute / expansionOpportunityCountOnThisLine;
857     float accumulatedExpansion = 0;
858     for (auto i = firstRunIndex; i <= lastRunIndex; ++i) {
859         auto& run = runs.at(i);
860         unsigned opportunityCountInRun;
861         std::tie(opportunityCountInRun, run.expansionBehavior) = expansionOpportunityList.at(i - firstRunIndex);
862         run.expansion = opportunityCountInRun * expansion;
863         run.logicalLeft += accumulatedExpansion;
864         run.logicalRight += (accumulatedExpansion + run.expansion);
865         accumulatedExpansion += run.expansion;
866     }
867 }
868
869 static ETextAlign textAlignForLine(const TextFragmentIterator::Style& style, bool lastLine)
870 {
871     // Fallback to LEFT (START) alignment for non-collapsable content and for the last line before a forced break or the end of the block.
872     auto textAlign = style.textAlign;
873     if (textAlign == JUSTIFY && (!style.collapseWhitespace || lastLine))
874         textAlign = LEFT;
875     return textAlign;
876 }
877
878 static void closeLineEndingAndAdjustRuns(LineState& line, Layout::RunVector& runs, std::optional<unsigned> lastRunIndexOfPreviousLine, unsigned& lineCount,
879     const TextFragmentIterator& textFragmentIterator, bool lastLineInFlow)
880 {
881     if (!runs.size() || (lastRunIndexOfPreviousLine && runs.size() - 1 == lastRunIndexOfPreviousLine.value()))
882         return;
883     removeTrailingWhitespace(line, runs, textFragmentIterator);
884     if (!runs.size())
885         return;
886     // Adjust runs' position by taking line's alignment into account.
887     const auto& style = textFragmentIterator.style();
888     auto firstRunIndex = lastRunIndexOfPreviousLine ? lastRunIndexOfPreviousLine.value() + 1 : 0;
889     auto lineLogicalLeft = line.logicalLeftOffset();
890     auto textAlign = textAlignForLine(style, lastLineInFlow || (line.lastFragment().isValid() && line.lastFragment().type() == TextFragmentIterator::TextFragment::HardLineBreak));
891     if (textAlign == JUSTIFY)
892         justifyRuns(line, runs, firstRunIndex);
893     else
894         lineLogicalLeft = computeLineLeft(textAlign, line.availableWidth(), line.width(), line.logicalLeftOffset());
895     for (auto i = firstRunIndex; i < runs.size(); ++i) {
896         runs[i].logicalLeft += lineLogicalLeft;
897         runs[i].logicalRight += lineLogicalLeft;
898     }
899     runs.last().isEndOfLine = true;
900     ++lineCount;
901 }
902
903 static void createTextRuns(Layout::RunVector& runs, RenderBlockFlow& flow, unsigned& lineCount)
904 {
905     LayoutUnit borderAndPaddingBefore = flow.borderAndPaddingBefore();
906     LayoutUnit lineHeight = lineHeightFromFlow(flow);
907     LineState line;
908     bool isEndOfContent = false;
909     TextFragmentIterator textFragmentIterator = TextFragmentIterator(flow);
910     std::optional<unsigned> lastRunIndexOfPreviousLine;
911     do {
912         flow.setLogicalHeight(lineHeight * lineCount + borderAndPaddingBefore);
913         LineState previousLine = line;
914         line = LineState();
915         updateLineConstrains(flow, line, textFragmentIterator.style(), !lineCount);
916         isEndOfContent = createLineRuns(line, previousLine, runs, textFragmentIterator);
917         closeLineEndingAndAdjustRuns(line, runs, lastRunIndexOfPreviousLine, lineCount, textFragmentIterator, isEndOfContent);
918         if (runs.size())
919             lastRunIndexOfPreviousLine = runs.size() - 1;
920     } while (!isEndOfContent);
921 }
922
923 std::unique_ptr<Layout> create(RenderBlockFlow& flow)
924 {
925     unsigned lineCount = 0;
926     Layout::RunVector runs;
927
928     createTextRuns(runs, flow, lineCount);
929     return Layout::create(runs, lineCount);
930 }
931
932 std::unique_ptr<Layout> Layout::create(const RunVector& runVector, unsigned lineCount)
933 {
934     void* slot = WTF::fastMalloc(sizeof(Layout) + sizeof(Run) * runVector.size());
935     return std::unique_ptr<Layout>(new (NotNull, slot) Layout(runVector, lineCount));
936 }
937
938 Layout::Layout(const RunVector& runVector, unsigned lineCount)
939     : m_lineCount(lineCount)
940     , m_runCount(runVector.size())
941 {
942     memcpy(m_runs, runVector.data(), m_runCount * sizeof(Run));
943 }
944
945 #ifndef NDEBUG
946 static void printReason(AvoidanceReason reason, TextStream& stream)
947 {
948     switch (reason) {
949     case FlowIsInsideRegion:
950         stream << "flow is inside region";
951         break;
952     case FlowHasHorizonalWritingMode:
953         stream << "horizontal writing mode";
954         break;
955     case FlowHasOutline:
956         stream << "outline";
957         break;
958     case FlowIsRuby:
959         stream << "ruby";
960         break;
961     case FlowHasHangingPunctuation:
962         stream << "hanging punctuation";
963         break;
964     case FlowIsPaginated:
965         stream << "paginated";
966         break;
967     case FlowHasTextOverflow:
968         stream << "text-overflow";
969         break;
970     case FlowIsDepricatedFlexBox:
971         stream << "depricatedFlexBox";
972         break;
973     case FlowParentIsPlaceholderElement:
974         stream << "placeholder element";
975         break;
976     case FlowParentIsTextAreaWithWrapping:
977         stream << "wrapping textarea";
978         break;
979     case FlowHasNonSupportedChild:
980         stream << "nested renderers";
981         break;
982     case FlowHasUnsupportedFloat:
983         stream << "complicated float";
984         break;
985     case FlowHasUnsupportedUnderlineDecoration:
986         stream << "text-underline-position: under";
987         break;
988     case FlowHasJustifiedNonLatinText:
989         stream << "text-align: justify with non-latin text";
990         break;
991     case FlowHasOverflowVisible:
992         stream << "overflow: visible";
993         break;
994     case FlowHasWebKitNBSPMode:
995         stream << "-webkit-nbsp-mode: space";
996         break;
997     case FlowIsNotLTR:
998         stream << "dir is not LTR";
999         break;
1000     case FlowHasLineBoxContainProperty:
1001         stream << "line-box-contain value indicates variable line height";
1002         break;
1003     case FlowIsNotTopToBottom:
1004         stream << "non top-to-bottom flow";
1005         break;
1006     case FlowHasLineBreak:
1007         stream << "line-break property";
1008         break;
1009     case FlowHasNonNormalUnicodeBiDi:
1010         stream << "non-normal Unicode bidi";
1011         break;
1012     case FlowHasRTLOrdering:
1013         stream << "-webkit-rtl-ordering";
1014         break;
1015     case FlowHasLineAlignEdges:
1016         stream << "-webkit-line-align edges";
1017         break;
1018     case FlowHasLineSnap:
1019         stream << "-webkit-line-snap property";
1020         break;
1021     case FlowHasTextEmphasisFillOrMark:
1022         stream << "text-emphasis (fill/mark)";
1023         break;
1024     case FlowHasPseudoFirstLine:
1025         stream << "first-line";
1026         break;
1027     case FlowHasPseudoFirstLetter:
1028         stream << "first-letter";
1029         break;
1030     case FlowHasTextCombine:
1031         stream << "text combine";
1032         break;
1033     case FlowHasTextFillBox:
1034         stream << "background-color (text-fill)";
1035         break;
1036     case FlowHasBorderFitLines:
1037         stream << "-webkit-border-fit";
1038         break;
1039     case FlowHasNonAutoLineBreak:
1040         stream << "line-break is not auto";
1041         break;
1042     case FlowHasNonAutoTrailingWord:
1043         stream << "-apple-trailing-word is not auto";
1044         break;
1045     case FlowHasSVGFont:
1046         stream << "SVG font";
1047         break;
1048     case FlowTextHasSoftHyphen:
1049         stream << "soft hyphen character";
1050         break;
1051     case FlowTextHasDirectionCharacter:
1052         stream << "direction character";
1053         break;
1054     case FlowIsMissingPrimaryFont:
1055         stream << "missing primary font";
1056         break;
1057     case FlowPrimaryFontIsInsufficient:
1058         stream << "missing glyph or glyph needs another font";
1059         break;
1060     case FlowTextIsCombineText:
1061         stream << "text is combine";
1062         break;
1063     case FlowTextIsRenderCounter:
1064         stream << "unsupported RenderCounter";
1065         break;
1066     case FlowTextIsRenderQuote:
1067         stream << "unsupported RenderQuote";
1068         break;
1069     case FlowTextIsTextFragment:
1070         stream << "unsupported TextFragment";
1071         break;
1072     case FlowTextIsSVGInlineText:
1073         stream << "unsupported SVGInlineText";
1074         break;
1075     case FlowHasComplexFontCodePath:
1076         stream << "text with complex font codepath";
1077         break;
1078     case FlowHasTextShadow:
1079         stream << "text-shadow";
1080         break;
1081     case FlowChildIsSelected:
1082         stream << "selected content";
1083         break;
1084     case FlowFontHasOverflowGlyph:
1085         stream << "-webkit-line-box-contain: glyphs with overflowing text.";
1086         break;
1087     case FlowTextHasSurrogatePair:
1088         stream << "surrogate pair";
1089         break;
1090     case FlowTextIsEmpty:
1091     case FlowHasNoChild:
1092     case FlowHasNoParent:
1093     case FeatureIsDisabled:
1094     default:
1095         break;
1096     }
1097 }
1098
1099 static void printReasons(AvoidanceReasonFlags reasons, TextStream& stream)
1100 {
1101     bool first = true;
1102     for (auto reasonItem = EndOfReasons >> 1; reasonItem != NoReason; reasonItem >>= 1) {
1103         if (!(reasons & reasonItem))
1104             continue;
1105         stream << (first ? " " : ", ");
1106         first = false;
1107         printReason(reasonItem, stream);
1108     }
1109 }
1110
1111 static void printTextForSubtree(const RenderObject& renderer, unsigned& charactersLeft, TextStream& stream)
1112 {
1113     if (!charactersLeft)
1114         return;
1115     if (is<RenderText>(renderer)) {
1116         String text = downcast<RenderText>(renderer).text();
1117         text = text.stripWhiteSpace();
1118         unsigned len = std::min(charactersLeft, text.length());
1119         stream << text.left(len);
1120         charactersLeft -= len;
1121         return;
1122     }
1123     if (!is<RenderElement>(renderer))
1124         return;
1125     for (const auto* child = downcast<RenderElement>(renderer).firstChild(); child; child = child->nextSibling())
1126         printTextForSubtree(*child, charactersLeft, stream);
1127 }
1128
1129 static unsigned textLengthForSubtree(const RenderObject& renderer)
1130 {
1131     if (is<RenderText>(renderer))
1132         return downcast<RenderText>(renderer).textLength();
1133     if (!is<RenderElement>(renderer))
1134         return 0;
1135     unsigned textLength = 0;
1136     for (const auto* child = downcast<RenderElement>(renderer).firstChild(); child; child = child->nextSibling())
1137         textLength += textLengthForSubtree(*child);
1138     return textLength;
1139 }
1140
1141 static void collectNonEmptyLeafRenderBlockFlows(const RenderObject& renderer, HashSet<const RenderBlockFlow*>& leafRenderers)
1142 {
1143     if (is<RenderText>(renderer)) {
1144         if (!downcast<RenderText>(renderer).textLength())
1145             return;
1146         // Find RenderBlockFlow ancestor.
1147         for (const auto* current = renderer.parent(); current; current = current->parent()) {
1148             if (!is<RenderBlockFlow>(current))
1149                 continue;
1150             leafRenderers.add(downcast<RenderBlockFlow>(current));
1151             break;
1152         }
1153         return;
1154     }
1155     if (!is<RenderElement>(renderer))
1156         return;
1157     for (const auto* child = downcast<RenderElement>(renderer).firstChild(); child; child = child->nextSibling())
1158         collectNonEmptyLeafRenderBlockFlows(*child, leafRenderers);
1159 }
1160
1161 static void collectNonEmptyLeafRenderBlockFlowsForCurrentPage(HashSet<const RenderBlockFlow*>& leafRenderers)
1162 {
1163     for (const auto* document : Document::allDocuments()) {
1164         if (!document->renderView() || document->pageCacheState() != Document::NotInPageCache)
1165             continue;
1166         if (!document->isHTMLDocument() && !document->isXHTMLDocument())
1167             continue;
1168         collectNonEmptyLeafRenderBlockFlows(*document->renderView(), leafRenderers);
1169     }
1170 }
1171
1172 void toggleSimpleLineLayout()
1173 {
1174     for (const auto* document : Document::allDocuments()) {
1175         auto* settings = document->settings();
1176         if (!settings)
1177             continue;
1178         settings->setSimpleLineLayoutEnabled(!settings->simpleLineLayoutEnabled());
1179     }
1180 }
1181
1182 void printSimpleLineLayoutBlockList()
1183 {
1184     HashSet<const RenderBlockFlow*> leafRenderers;
1185     collectNonEmptyLeafRenderBlockFlowsForCurrentPage(leafRenderers);
1186     if (!leafRenderers.size()) {
1187         WTFLogAlways("No text found in this document\n");
1188         return;
1189     }
1190     TextStream stream;
1191     stream << "---------------------------------------------------\n";
1192     for (const auto* flow : leafRenderers) {
1193         auto reason = canUseForWithReason(*flow, IncludeReasons::All);
1194         if (reason == NoReason)
1195             continue;
1196         unsigned printedLength = 30;
1197         stream << "\"";
1198         printTextForSubtree(*flow, printedLength, stream);
1199         for (;printedLength > 0; --printedLength)
1200             stream << " ";
1201         stream << "\"(" << textLengthForSubtree(*flow) << "):";
1202         printReasons(reason, stream);
1203         stream << "\n";
1204     }
1205     stream << "---------------------------------------------------\n";
1206     WTFLogAlways("%s", stream.release().utf8().data());
1207 }
1208
1209 void printSimpleLineLayoutCoverage()
1210 {
1211     HashSet<const RenderBlockFlow*> leafRenderers;
1212     collectNonEmptyLeafRenderBlockFlowsForCurrentPage(leafRenderers);
1213     if (!leafRenderers.size()) {
1214         WTFLogAlways("No text found in this document\n");
1215         return;
1216     }
1217     TextStream stream;
1218     HashMap<AvoidanceReason, unsigned> flowStatistics;
1219     unsigned textLength = 0;
1220     unsigned unsupportedTextLength = 0;
1221     unsigned numberOfUnsupportedLeafBlocks = 0;
1222     for (const auto* flow : leafRenderers) {
1223         auto flowLength = textLengthForSubtree(*flow);
1224         textLength += flowLength;
1225         auto reasons = canUseForWithReason(*flow, IncludeReasons::All);
1226         if (reasons == NoReason)
1227             continue;
1228         ++numberOfUnsupportedLeafBlocks;
1229         unsupportedTextLength += flowLength;
1230         for (auto reasonItem = EndOfReasons >> 1; reasonItem != NoReason; reasonItem >>= 1) {
1231             if (!(reasons & reasonItem))
1232                 continue;
1233             auto result = flowStatistics.add(reasonItem, flowLength);
1234             if (!result.isNewEntry)
1235                 result.iterator->value += flowLength;
1236         }
1237     }
1238     stream << "---------------------------------------------------\n";
1239     stream << "Number of text blocks: total(" <<  leafRenderers.size() << ") non-simple(" << numberOfUnsupportedLeafBlocks << ")\nText length: total(" <<
1240         textLength << ") non-simple(" << unsupportedTextLength << ")\n";
1241     for (const auto reasonEntry : flowStatistics) {
1242         printReason(reasonEntry.key, stream);
1243         stream << ": " << (float)reasonEntry.value / (float)textLength * 100 << "%\n";
1244     }
1245     stream << "simple line layout coverage: " << (float)(textLength - unsupportedTextLength) / (float)textLength * 100 << "%\n";
1246     stream << "---------------------------------------------------\n";
1247     WTFLogAlways("%s", stream.release().utf8().data());
1248 }
1249 #endif
1250 }
1251 }