e3fea3fab29e4db722e8a8e9347f6421675318b0
[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 "DocumentMarkerController.h"
30 #include "FontCache.h"
31 #include "Frame.h"
32 #include "GraphicsContext.h"
33 #include "HTMLTextFormControlElement.h"
34 #include "HitTestLocation.h"
35 #include "HitTestRequest.h"
36 #include "HitTestResult.h"
37 #include "Hyphenation.h"
38 #include "InlineTextBox.h"
39 #include "LineWidth.h"
40 #include "Logging.h"
41 #include "PaintInfo.h"
42 #include "RenderBlockFlow.h"
43 #include "RenderChildIterator.h"
44 #include "RenderFragmentedFlow.h"
45 #include "RenderLineBreak.h"
46 #include "RenderMultiColumnFlow.h"
47 #include "RenderStyle.h"
48 #include "RenderText.h"
49 #include "RenderTextControl.h"
50 #include "RenderView.h"
51 #include "Settings.h"
52 #include "SimpleLineLayoutFlowContents.h"
53 #include "SimpleLineLayoutFunctions.h"
54 #include "SimpleLineLayoutResolver.h"
55 #include "SimpleLineLayoutTextFragmentIterator.h"
56 #include "Text.h"
57 #include "TextPaintStyle.h"
58 #include <pal/Logging.h>
59
60 namespace WebCore {
61 namespace SimpleLineLayout {
62
63 #ifndef NDEBUG
64 #define SET_REASON_AND_RETURN_IF_NEEDED(reason, reasons, includeReasons) { \
65         reasons |= reason; \
66         if (includeReasons == IncludeReasons::First) \
67             return reasons; \
68     }
69 #else
70 #define SET_REASON_AND_RETURN_IF_NEEDED(reason, reasons, includeReasons) { \
71         ASSERT_UNUSED(includeReasons, includeReasons == IncludeReasons::First); \
72         reasons |= reason; \
73         return reasons; \
74     }
75 #endif
76
77
78 template <typename CharacterType> AvoidanceReasonFlags canUseForCharacter(CharacterType, bool textIsJustified, IncludeReasons);
79
80 template<> AvoidanceReasonFlags canUseForCharacter(UChar character, bool textIsJustified, IncludeReasons includeReasons)
81 {
82     AvoidanceReasonFlags reasons = { };
83     if (textIsJustified) {
84         // Include characters up to Latin Extended-B and some punctuation range when text is justified.
85         bool isLatinIncludingExtendedB = character <= 0x01FF;
86         bool isPunctuationRange = character >= 0x2010 && character <= 0x2027;
87         if (!(isLatinIncludingExtendedB || isPunctuationRange))
88             SET_REASON_AND_RETURN_IF_NEEDED(FlowHasJustifiedNonLatinText, reasons, includeReasons);
89     }
90
91     if (U16_IS_SURROGATE(character))
92         SET_REASON_AND_RETURN_IF_NEEDED(FlowTextHasSurrogatePair, reasons, includeReasons);
93     
94     UCharDirection direction = u_charDirection(character);
95     if (direction == U_RIGHT_TO_LEFT || direction == U_RIGHT_TO_LEFT_ARABIC
96         || direction == U_RIGHT_TO_LEFT_EMBEDDING || direction == U_RIGHT_TO_LEFT_OVERRIDE
97         || direction == U_LEFT_TO_RIGHT_EMBEDDING || direction == U_LEFT_TO_RIGHT_OVERRIDE
98         || direction == U_POP_DIRECTIONAL_FORMAT || direction == U_BOUNDARY_NEUTRAL)
99         SET_REASON_AND_RETURN_IF_NEEDED(FlowTextHasDirectionCharacter, reasons, includeReasons);
100
101     return reasons;
102 }
103
104 template<> AvoidanceReasonFlags canUseForCharacter(LChar, bool, IncludeReasons)
105 {
106     return { };
107 }
108
109 template <typename CharacterType>
110 static AvoidanceReasonFlags canUseForText(const CharacterType* text, unsigned length, const FontCascade& fontCascade, std::optional<float> lineHeightConstraint,
111     bool textIsJustified, IncludeReasons includeReasons)
112 {
113     AvoidanceReasonFlags reasons = { };
114     auto& primaryFont = fontCascade.primaryFont();
115     auto& fontMetrics = primaryFont.fontMetrics();
116     auto availableSpaceForGlyphAscent = fontMetrics.ascent();
117     auto availableSpaceForGlyphDescent = fontMetrics.descent();
118     if (lineHeightConstraint) {
119         auto lineHeightPadding = *lineHeightConstraint - fontMetrics.height();
120         availableSpaceForGlyphAscent += lineHeightPadding / 2;
121         availableSpaceForGlyphDescent += lineHeightPadding / 2;
122     }
123
124     for (unsigned i = 0; i < length; ++i) {
125         auto character = text[i];
126         if (FontCascade::treatAsSpace(character))
127             continue;
128
129         if (character == softHyphen)
130             SET_REASON_AND_RETURN_IF_NEEDED(FlowTextHasSoftHyphen, reasons, includeReasons);
131
132         auto characterReasons = canUseForCharacter(character, textIsJustified, includeReasons);
133         if (characterReasons != NoReason)
134             SET_REASON_AND_RETURN_IF_NEEDED(characterReasons, reasons, includeReasons);
135
136         auto glyphData = fontCascade.glyphDataForCharacter(character, false);
137         if (!glyphData.isValid() || glyphData.font != &primaryFont)
138             SET_REASON_AND_RETURN_IF_NEEDED(FlowPrimaryFontIsInsufficient, reasons, includeReasons);
139
140         if (lineHeightConstraint) {
141             auto bounds = primaryFont.boundsForGlyph(glyphData.glyph);
142             if (ceilf(-bounds.y()) > availableSpaceForGlyphAscent || ceilf(bounds.maxY()) > availableSpaceForGlyphDescent)
143                 SET_REASON_AND_RETURN_IF_NEEDED(FlowFontHasOverflowGlyph, reasons, includeReasons);
144         }
145     }
146     return reasons;
147 }
148
149 static AvoidanceReasonFlags canUseForText(StringView text, const FontCascade& fontCascade, std::optional<float> lineHeightConstraint, bool textIsJustified, IncludeReasons includeReasons)
150 {
151     if (text.is8Bit())
152         return canUseForText(text.characters8(), text.length(), fontCascade, lineHeightConstraint, textIsJustified, includeReasons);
153     return canUseForText(text.characters16(), text.length(), fontCascade, lineHeightConstraint, textIsJustified, includeReasons);
154 }
155
156 static AvoidanceReasonFlags canUseForFontAndText(const RenderBlockFlow& flow, IncludeReasons includeReasons)
157 {
158     AvoidanceReasonFlags reasons = { };
159     // We assume that all lines have metrics based purely on the primary font.
160     const auto& style = flow.style();
161     auto& fontCascade = style.fontCascade();
162     if (fontCascade.primaryFont().isInterstitial())
163         SET_REASON_AND_RETURN_IF_NEEDED(FlowIsMissingPrimaryFont, reasons, includeReasons);
164     std::optional<float> lineHeightConstraint;
165     if (style.lineBoxContain() & LineBoxContainGlyphs)
166         lineHeightConstraint = lineHeightFromFlow(flow).toFloat();
167     bool flowIsJustified = style.textAlign() == TextAlignMode::Justify;
168     for (const auto& textRenderer : childrenOfType<RenderText>(flow)) {
169         // FIXME: Do not return until after checking all children.
170         if (textRenderer.text().isEmpty())
171             SET_REASON_AND_RETURN_IF_NEEDED(FlowTextIsEmpty, reasons, includeReasons);
172         if (textRenderer.isCombineText())
173             SET_REASON_AND_RETURN_IF_NEEDED(FlowTextIsCombineText, reasons, includeReasons);
174         if (textRenderer.isCounter())
175             SET_REASON_AND_RETURN_IF_NEEDED(FlowTextIsRenderCounter, reasons, includeReasons);
176         if (textRenderer.isQuote())
177             SET_REASON_AND_RETURN_IF_NEEDED(FlowTextIsRenderQuote, reasons, includeReasons);
178         if (textRenderer.isTextFragment())
179             SET_REASON_AND_RETURN_IF_NEEDED(FlowTextIsTextFragment, reasons, includeReasons);
180         if (textRenderer.isSVGInlineText())
181             SET_REASON_AND_RETURN_IF_NEEDED(FlowTextIsSVGInlineText, reasons, includeReasons);
182         if (!textRenderer.canUseSimpleFontCodePath()) {
183             // No need to check the code path at this point. We already know it can't be simple.
184             SET_REASON_AND_RETURN_IF_NEEDED(FlowHasComplexFontCodePath, reasons, includeReasons);
185         } else {
186             TextRun run(String(textRenderer.text()));
187             run.setCharacterScanForCodePath(false);
188             if (style.fontCascade().codePath(run) != FontCascade::Simple)
189                 SET_REASON_AND_RETURN_IF_NEEDED(FlowHasComplexFontCodePath, reasons, includeReasons);
190         }
191
192         auto textReasons = canUseForText(textRenderer.stringView(), fontCascade, lineHeightConstraint, flowIsJustified, includeReasons);
193         if (textReasons != NoReason)
194             SET_REASON_AND_RETURN_IF_NEEDED(textReasons, reasons, includeReasons);
195     }
196     return reasons;
197 }
198
199 static AvoidanceReasonFlags canUseForStyle(const RenderStyle& style, IncludeReasons includeReasons)
200 {
201     AvoidanceReasonFlags reasons = { };
202     if (style.textOverflow() == TextOverflow::Ellipsis)
203         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasTextOverflow, reasons, includeReasons);
204     if ((style.textDecorationsInEffect() & TextDecoration::Underline) && style.textUnderlinePosition() == TextUnderlinePosition::Under)
205         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasUnsupportedUnderlineDecoration, reasons, includeReasons);
206     // Non-visible overflow should be pretty easy to support.
207     if (style.overflowX() != Overflow::Visible || style.overflowY() != Overflow::Visible)
208         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasOverflowNotVisible, reasons, includeReasons);
209     if (!style.isLeftToRightDirection())
210         SET_REASON_AND_RETURN_IF_NEEDED(FlowIsNotLTR, reasons, includeReasons);
211     if (!(style.lineBoxContain() & LineBoxContainBlock))
212         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasLineBoxContainProperty, reasons, includeReasons);
213     if (style.writingMode() != TopToBottomWritingMode)
214         SET_REASON_AND_RETURN_IF_NEEDED(FlowIsNotTopToBottom, reasons, includeReasons);
215     if (style.lineBreak() != LineBreak::Auto)
216         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasLineBreak, reasons, includeReasons);
217     if (style.unicodeBidi() != UBNormal)
218         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasNonNormalUnicodeBiDi, reasons, includeReasons);
219     if (style.rtlOrdering() != Order::Logical)
220         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasRTLOrdering, reasons, includeReasons);
221     if (style.lineAlign() != LineAlign::None)
222         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasLineAlignEdges, reasons, includeReasons);
223     if (style.lineSnap() != LineSnap::None)
224         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasLineSnap, reasons, includeReasons);
225     if (style.textEmphasisFill() != TextEmphasisFill::Filled || style.textEmphasisMark() != TextEmphasisMark::None)
226         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasTextEmphasisFillOrMark, reasons, includeReasons);
227     if (style.textShadow())
228         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasTextShadow, reasons, includeReasons);
229     if (style.hasPseudoStyle(PseudoId::FirstLine))
230         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasPseudoFirstLine, reasons, includeReasons);
231     if (style.hasPseudoStyle(PseudoId::FirstLetter))
232         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasPseudoFirstLetter, reasons, includeReasons);
233     if (style.hasTextCombine())
234         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasTextCombine, reasons, includeReasons);
235     if (style.backgroundClip() == FillBox::Text)
236         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasTextFillBox, reasons, includeReasons);
237     if (style.borderFit() == BorderFit::Lines)
238         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasBorderFitLines, reasons, includeReasons);
239     if (style.lineBreak() != LineBreak::Auto)
240         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasNonAutoLineBreak, reasons, includeReasons);
241     if (style.nbspMode() != NBSPMode::Normal)
242         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasWebKitNBSPMode, reasons, includeReasons);
243 #if ENABLE(CSS_TRAILING_WORD)
244     if (style.trailingWord() != TrailingWord::Auto)
245         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasNonAutoTrailingWord, reasons, includeReasons);
246 #endif
247     if (style.hyphens() == Hyphens::Auto) {
248         auto textReasons = canUseForText(style.hyphenString(), style.fontCascade(), std::nullopt, false, includeReasons);
249         if (textReasons != NoReason)
250             SET_REASON_AND_RETURN_IF_NEEDED(textReasons, reasons, includeReasons);
251     }
252     return reasons;
253 }
254
255 AvoidanceReasonFlags canUseForWithReason(const RenderBlockFlow& flow, IncludeReasons includeReasons)
256 {
257 #ifndef NDEBUG
258     static std::once_flag onceFlag;
259     std::call_once(onceFlag, [] {
260         PAL::registerNotifyCallback("com.apple.WebKit.showSimpleLineLayoutCoverage", WTF::Function<void()> { printSimpleLineLayoutCoverage });
261         PAL::registerNotifyCallback("com.apple.WebKit.showSimpleLineLayoutReasons", WTF::Function<void()> { printSimpleLineLayoutBlockList });
262         PAL::registerNotifyCallback("com.apple.WebKit.toggleSimpleLineLayout", WTF::Function<void()> { toggleSimpleLineLayout });
263     });
264 #endif
265     AvoidanceReasonFlags reasons = { };
266     if (!flow.settings().simpleLineLayoutEnabled())
267         SET_REASON_AND_RETURN_IF_NEEDED(FeatureIsDisabled, reasons, includeReasons);
268     if (!flow.parent())
269         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasNoParent, reasons, includeReasons);
270     if (!flow.firstChild())
271         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasNoChild, reasons, includeReasons);
272     if (flow.fragmentedFlowState() != RenderObject::NotInsideFragmentedFlow) {
273         auto* fragmentedFlow = flow.enclosingFragmentedFlow();
274         if (!is<RenderMultiColumnFlow>(fragmentedFlow))
275             SET_REASON_AND_RETURN_IF_NEEDED(FlowIsInsideANonMultiColumnThread, reasons, includeReasons);
276         auto& columnThread = downcast<RenderMultiColumnFlow>(*fragmentedFlow);
277         if (columnThread.parent() != &flow.view())
278             SET_REASON_AND_RETURN_IF_NEEDED(MultiColumnFlowIsNotTopLevel, reasons, includeReasons);
279         if (columnThread.hasColumnSpanner())
280             SET_REASON_AND_RETURN_IF_NEEDED(MultiColumnFlowHasColumnSpanner, reasons, includeReasons);
281         auto& style = flow.style();
282         if (style.verticalAlign() != VerticalAlign::Baseline)
283             SET_REASON_AND_RETURN_IF_NEEDED(MultiColumnFlowVerticalAlign, reasons, includeReasons);
284         if (style.isFloating())
285             SET_REASON_AND_RETURN_IF_NEEDED(MultiColumnFlowIsFloating, reasons, includeReasons);
286     }
287     if (!flow.isHorizontalWritingMode())
288         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasHorizonalWritingMode, reasons, includeReasons);
289     if (flow.hasOutline())
290         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasOutline, reasons, includeReasons);
291     if (flow.isRubyText() || flow.isRubyBase())
292         SET_REASON_AND_RETURN_IF_NEEDED(FlowIsRuby, reasons, includeReasons);
293     if (!flow.style().hangingPunctuation().isEmpty())
294         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasHangingPunctuation, reasons, includeReasons);
295     
296     // Printing does pagination without a flow thread.
297     if (flow.document().paginated())
298         SET_REASON_AND_RETURN_IF_NEEDED(FlowIsPaginated, reasons, includeReasons);
299     if (flow.firstLineBlock())
300         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasPseudoFirstLine, reasons, includeReasons);
301     if (flow.isAnonymousBlock() && flow.parent()->style().textOverflow() == TextOverflow::Ellipsis)
302         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasTextOverflow, reasons, includeReasons);
303     if (flow.parent()->isDeprecatedFlexibleBox())
304         SET_REASON_AND_RETURN_IF_NEEDED(FlowIsDepricatedFlexBox, reasons, includeReasons);
305     // FIXME: Placeholders do something strange.
306     if (is<RenderTextControl>(*flow.parent()) && downcast<RenderTextControl>(*flow.parent()).textFormControlElement().placeholderElement())
307         SET_REASON_AND_RETURN_IF_NEEDED(FlowParentIsPlaceholderElement, reasons, includeReasons);
308     // FIXME: Implementation of wrap=hard looks into lineboxes.
309     if (flow.parent()->isTextArea() && flow.parent()->element()->hasAttributeWithoutSynchronization(HTMLNames::wrapAttr))
310         SET_REASON_AND_RETURN_IF_NEEDED(FlowParentIsTextAreaWithWrapping, reasons, includeReasons);
311     // This currently covers <blockflow>#text</blockflow>, <blockflow>#text<br></blockflow> and mutiple (sibling) RenderText cases.
312     // The <blockflow><inline>#text</inline></blockflow> case is also popular and should be relatively easy to cover.
313     for (const auto* child = flow.firstChild(); child;) {
314         if (child->selectionState() != RenderObject::SelectionNone)
315             SET_REASON_AND_RETURN_IF_NEEDED(FlowChildIsSelected, reasons, includeReasons);
316         if (is<RenderText>(*child)) {
317             const auto& renderText = downcast<RenderText>(*child);
318             if (!renderText.document().markers().markersFor(renderText.textNode()).isEmpty())
319                 SET_REASON_AND_RETURN_IF_NEEDED(FlowIncludesDocumentMarkers, reasons, includeReasons);
320             child = child->nextSibling();
321             continue;
322         }
323         if (is<RenderLineBreak>(child) && !downcast<RenderLineBreak>(*child).isWBR() && child->style().clear() == Clear::None) {
324             child = child->nextSibling();
325             continue;
326         }
327         SET_REASON_AND_RETURN_IF_NEEDED(FlowHasNonSupportedChild, reasons, includeReasons);
328         break;
329     }
330     auto styleReasons = canUseForStyle(flow.style(), includeReasons);
331     if (styleReasons != NoReason)
332         SET_REASON_AND_RETURN_IF_NEEDED(styleReasons, reasons, includeReasons);
333     // 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.
334     if (flow.containsFloats()) {
335         float minimumWidthNeeded = std::numeric_limits<float>::max();
336         for (const auto& textRenderer : childrenOfType<RenderText>(flow)) {
337             minimumWidthNeeded = std::min(minimumWidthNeeded, textRenderer.minLogicalWidth());
338
339             for (auto& floatingObject : *flow.floatingObjectSet()) {
340                 ASSERT(floatingObject);
341                 // if a float has a shape, we cannot tell if content will need to be shifted until after we lay it out,
342                 // since the amount of space is not uniform for the height of the float.
343                 if (floatingObject->renderer().shapeOutsideInfo())
344                     SET_REASON_AND_RETURN_IF_NEEDED(FlowHasUnsupportedFloat, reasons, includeReasons);
345                 float availableWidth = flow.availableLogicalWidthForLine(floatingObject->y(), DoNotIndentText);
346                 if (availableWidth < minimumWidthNeeded)
347                     SET_REASON_AND_RETURN_IF_NEEDED(FlowHasUnsupportedFloat, reasons, includeReasons);
348             }
349         }
350     }
351     auto fontAndTextReasons = canUseForFontAndText(flow, includeReasons);
352     if (fontAndTextReasons != NoReason)
353         SET_REASON_AND_RETURN_IF_NEEDED(fontAndTextReasons, reasons, includeReasons);
354     return reasons;
355 }
356
357 bool canUseFor(const RenderBlockFlow& flow)
358 {
359     return canUseForWithReason(flow, IncludeReasons::First) == NoReason;
360 }
361
362 static float computeLineLeft(TextAlignMode textAlign, float availableWidth, float committedWidth, float logicalLeftOffset)
363 {
364     float remainingWidth = availableWidth - committedWidth;
365     float left = logicalLeftOffset;
366     switch (textAlign) {
367     case TextAlignMode::Left:
368     case TextAlignMode::WebKitLeft:
369     case TextAlignMode::Start:
370         return left;
371     case TextAlignMode::Right:
372     case TextAlignMode::WebKitRight:
373     case TextAlignMode::End:
374         return left + std::max<float>(remainingWidth, 0);
375     case TextAlignMode::Center:
376     case TextAlignMode::WebKitCenter:
377         return left + std::max<float>(remainingWidth / 2, 0);
378     case TextAlignMode::Justify:
379         ASSERT_NOT_REACHED();
380         break;
381     }
382     ASSERT_NOT_REACHED();
383     return 0;
384 }
385
386 static void revertAllRunsOnCurrentLine(Layout::RunVector& runs)
387 {
388     while (!runs.isEmpty() && !runs.last().isEndOfLine)
389         runs.removeLast();
390 }
391
392 static void revertRuns(Layout::RunVector& runs, unsigned positionToRevertTo, float width)
393 {
394     while (runs.size()) {
395         auto& lastRun = runs.last();
396         if (lastRun.end <= positionToRevertTo)
397             break;
398         if (lastRun.start >= positionToRevertTo) {
399             // Revert this run completely.
400             width -= (lastRun.logicalRight - lastRun.logicalLeft);
401             runs.removeLast();
402         } else {
403             lastRun.logicalRight -= width;
404             width = 0;
405             lastRun.end = positionToRevertTo;
406             // Partial removal.
407             break;
408         }
409     }
410 }
411
412 class LineState {
413 public:
414     void setAvailableWidth(float width) { m_availableWidth = width; }
415     void setCollapedWhitespaceWidth(float width) { m_collapsedWhitespaceWidth = width; }
416     void setLogicalLeftOffset(float offset) { m_logicalLeftOffset = offset; }
417     void setOverflowedFragment(const TextFragmentIterator::TextFragment& fragment) { m_overflowedFragment = fragment; }
418     void setNeedsAllFragments()
419     {
420         ASSERT(!m_fragments);
421         m_fragments.emplace();
422     }
423     void setHyphenationDisabled() { m_hyphenationDisabled = true; }
424     bool isHyphenationDisabled() const { return m_hyphenationDisabled; }
425
426     float availableWidth() const { return m_availableWidth; }
427     float logicalLeftOffset() const { return m_logicalLeftOffset; }
428     const TextFragmentIterator::TextFragment& overflowedFragment() const { return m_overflowedFragment; }
429     bool hasTrailingWhitespace() const { return m_lastFragment.type() == TextFragmentIterator::TextFragment::Whitespace; }
430     TextFragmentIterator::TextFragment lastFragment() const { return m_lastFragment; }
431     bool isWhitespaceOnly() const { return m_trailingWhitespaceWidth && m_runsWidth == m_trailingWhitespaceWidth; }
432     bool fits(float extra) const { return m_availableWidth >= m_runsWidth + extra; }
433     bool firstCharacterFits() const { return m_firstCharacterFits; }
434     float width() const { return m_runsWidth; }
435     std::pair<unsigned, bool> expansionOpportunityCount(unsigned from, unsigned to) const
436     {
437         ASSERT(m_fragments);
438         // linebreak runs are special.
439         if (from == to)
440             return std::make_pair(0, false);
441         unsigned expansionOpportunityCount = 0;
442         auto previousFragmentType = TextFragmentIterator::TextFragment::ContentEnd;
443         for (const auto& fragment : *m_fragments) {
444             if (fragment.end() <= from)
445                 continue;
446             auto currentFragmentType = fragment.type();
447             auto expansionOpportunity = this->expansionOpportunity(currentFragmentType, previousFragmentType);
448             if (expansionOpportunity)
449                 ++expansionOpportunityCount;
450             previousFragmentType = currentFragmentType;
451             if (fragment.end() >= to)
452                 return std::make_pair(expansionOpportunityCount, expansionOpportunity);
453         }
454         ASSERT_NOT_REACHED();
455         return std::make_pair(expansionOpportunityCount, false);
456     }
457
458     bool isEmpty() const
459     {
460         if (!m_lastFragment.isValid())
461             return true;
462         if (!m_lastCompleteFragment.isEmpty())
463             return false;
464         return m_lastFragment.overlapsToNextRenderer();
465     }
466
467     static inline unsigned endPositionForCollapsedFragment(const TextFragmentIterator::TextFragment& fragment)
468     {
469         return fragment.isCollapsed() ? fragment.start() + 1 : fragment.end();
470     }
471
472     void appendFragmentAndCreateRunIfNeeded(const TextFragmentIterator::TextFragment& fragment, Layout::RunVector& runs)
473     {
474         // Adjust end position while collapsing.
475         unsigned endPosition = endPositionForCollapsedFragment(fragment);
476         // New line needs new run.
477         if (!m_runsWidth) {
478             ASSERT(!m_uncompletedWidth);
479             runs.append(Run(fragment.start(), endPosition, m_runsWidth, m_runsWidth + fragment.width(), false, fragment.hasHyphen()));
480         } else {
481             // Advance last completed fragment when the previous fragment is all set (including multiple parts across renderers)
482             if ((m_lastFragment.type() != fragment.type()) || !m_lastFragment.overlapsToNextRenderer()) {
483                 m_lastCompleteFragment = m_lastFragment;
484                 m_uncompletedWidth = fragment.width();
485             } else
486                 m_uncompletedWidth += fragment.width();
487             // Collapse neighbouring whitespace, if they are across multiple renderers and are not collapsed yet.
488             if (m_lastFragment.isCollapsible() && fragment.isCollapsible()) {
489                 ASSERT(m_lastFragment.isLastInRenderer());
490                 if (!m_lastFragment.isCollapsed()) {
491                     // Line width needs to be adjusted so that now it takes collapsing into consideration.
492                     m_runsWidth -= (m_lastFragment.width() - m_collapsedWhitespaceWidth);
493                 }
494                 // This fragment is collapsed completely. No run is needed.
495                 return;
496             }
497             if (m_lastFragment.isLastInRenderer() || m_lastFragment.isCollapsed())
498                 runs.append(Run(fragment.start(), endPosition, m_runsWidth, m_runsWidth + fragment.width(), false, fragment.hasHyphen()));
499             else {
500                 Run& lastRun = runs.last();
501                 lastRun.end = endPosition;
502                 lastRun.logicalRight += fragment.width();
503                 ASSERT(!lastRun.hasHyphen);
504                 lastRun.hasHyphen = fragment.hasHyphen();
505             }
506         }
507         m_runsWidth += fragment.width();
508         m_lastFragment = fragment;
509         if (m_fragments)
510             (*m_fragments).append(fragment);
511
512         if (fragment.type() == TextFragmentIterator::TextFragment::Whitespace)
513             m_trailingWhitespaceWidth += fragment.width();
514         else {
515             m_trailingWhitespaceWidth = 0;
516             m_lastNonWhitespaceFragment = fragment;
517         }
518
519         if (!m_firstCharacterFits)
520             m_firstCharacterFits = fragment.start() + 1 > endPosition || m_runsWidth <= m_availableWidth;
521     }
522
523     TextFragmentIterator::TextFragment revertToLastCompleteFragment(Layout::RunVector& runs)
524     {
525         if (!m_uncompletedWidth) {
526             ASSERT(m_lastFragment == m_lastCompleteFragment);
527             return m_lastFragment;
528         }
529         ASSERT(m_lastFragment.isValid());
530         m_runsWidth -= m_uncompletedWidth;
531         revertRuns(runs, endPositionForCollapsedFragment(m_lastCompleteFragment), m_uncompletedWidth);
532         m_uncompletedWidth = 0;
533         ASSERT(m_lastCompleteFragment.isValid());
534         return m_lastCompleteFragment;
535     }
536
537     void removeTrailingWhitespace(Layout::RunVector& runs)
538     {
539         if (m_lastFragment.type() != TextFragmentIterator::TextFragment::Whitespace)
540             return;
541         if (m_lastNonWhitespaceFragment) {
542             auto needsReverting = m_lastNonWhitespaceFragment->end() != m_lastFragment.end();
543             // Trailing whitespace fragment might actually have zero length.
544             ASSERT(needsReverting || !m_trailingWhitespaceWidth);
545             if (needsReverting) {
546                 revertRuns(runs, m_lastNonWhitespaceFragment->end(), m_trailingWhitespaceWidth);
547                 m_runsWidth -= m_trailingWhitespaceWidth;
548             }
549             m_trailingWhitespaceWidth = 0;
550             m_lastFragment = *m_lastNonWhitespaceFragment;
551             return;
552         }
553         // This line is all whitespace.
554         revertAllRunsOnCurrentLine(runs);
555         m_runsWidth = 0;
556         m_trailingWhitespaceWidth = 0;
557         // FIXME: Make m_lastFragment optional.
558         m_lastFragment = TextFragmentIterator::TextFragment();
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     std::optional<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     bool m_hyphenationDisabled { false };
582     std::optional<Vector<TextFragmentIterator::TextFragment, 30>> m_fragments;
583 };
584
585 static bool preWrap(const TextFragmentIterator::Style& style)
586 {
587     return style.wrapLines && !style.collapseWhitespace;
588 }
589     
590 static void removeTrailingWhitespace(LineState& lineState, Layout::RunVector& runs, const TextFragmentIterator& textFragmentIterator)
591 {
592     if (!lineState.hasTrailingWhitespace())
593         return;
594     // Remove collapsed whitespace, or non-collapsed pre-wrap whitespace, unless it's the only content on the line -so removing the whitesapce
595     // would produce an empty line.
596     const auto& style = textFragmentIterator.style();
597     bool collapseWhitespace = style.collapseWhitespace | preWrap(style);
598     if (!collapseWhitespace)
599         return;
600     if (preWrap(style) && lineState.isWhitespaceOnly())
601         return;
602     lineState.removeTrailingWhitespace(runs);
603 }
604
605 static void updateLineConstrains(const RenderBlockFlow& flow, LineState& line, const LineState& previousLine, unsigned& numberOfPrecedingLinesWithHyphen, const TextFragmentIterator::Style& style, bool isFirstLine)
606 {
607     bool shouldApplyTextIndent = !flow.isAnonymous() || flow.parent()->firstChild() == &flow;
608     LayoutUnit height = flow.logicalHeight();
609     LayoutUnit logicalHeight = flow.minLineHeightForReplacedRenderer(false, 0);
610     line.setLogicalLeftOffset(flow.logicalLeftOffsetForLine(height, DoNotIndentText, logicalHeight) + (shouldApplyTextIndent && isFirstLine ? flow.textIndentOffset() : LayoutUnit(0)));
611     float logicalRightOffset = flow.logicalRightOffsetForLine(height, DoNotIndentText, logicalHeight);
612     line.setAvailableWidth(std::max<float>(0, logicalRightOffset - line.logicalLeftOffset()));
613     if (style.textAlign == TextAlignMode::Justify)
614         line.setNeedsAllFragments();
615     numberOfPrecedingLinesWithHyphen = (previousLine.isEmpty() || !previousLine.lastFragment().hasHyphen()) ? 0 : numberOfPrecedingLinesWithHyphen + 1;
616     if (style.hyphenLimitLines && numberOfPrecedingLinesWithHyphen >= *style.hyphenLimitLines)
617         line.setHyphenationDisabled();
618     line.setCollapedWhitespaceWidth(style.font.spaceWidth() + style.wordSpacing);
619 }
620
621 struct SplitFragmentData {
622     unsigned position;
623     float width;
624 };
625 static std::optional<unsigned> hyphenPositionForFragment(SplitFragmentData splitData, const TextFragmentIterator::TextFragment& fragmentToSplit,
626     const LineState& line, const TextFragmentIterator& textFragmentIterator, float availableWidth)
627 {
628     auto& style = textFragmentIterator.style();
629     if (!style.shouldHyphenate || line.isHyphenationDisabled())
630         return std::nullopt;
631
632     // FIXME: This is a workaround for webkit.org/b/169613. See maxPrefixWidth computation in tryHyphenating().
633     // It does not work properly with non-collapsed leading tabs when font is enlarged.
634     auto adjustedAvailableWidth = availableWidth - style.hyphenStringWidth;
635     if (!line.isEmpty())
636         adjustedAvailableWidth += style.font.spaceWidth();
637     if (!enoughWidthForHyphenation(adjustedAvailableWidth, style.font.pixelSize()))
638         return std::nullopt;
639
640     // We might be able to fit the hyphen at the split position.
641     auto splitPositionWithHyphen = splitData.position;
642     // Find a splitting position where hyphen surely fits.
643     unsigned start = fragmentToSplit.start();
644     auto leftSideWidth = splitData.width;
645     while (leftSideWidth + style.hyphenStringWidth > availableWidth) {
646         if (--splitPositionWithHyphen <= start)
647             return std::nullopt; // No space for hyphen.
648         leftSideWidth -= textFragmentIterator.textWidth(splitPositionWithHyphen, splitPositionWithHyphen + 1, 0);
649     }
650     ASSERT(splitPositionWithHyphen > start);
651     return textFragmentIterator.lastHyphenPosition(fragmentToSplit, splitPositionWithHyphen + 1);
652 }
653
654 static SplitFragmentData split(const TextFragmentIterator::TextFragment& fragment, float availableWidth,
655     const TextFragmentIterator& textFragmentIterator)
656 {
657     ASSERT(availableWidth >= 0);
658     auto left = fragment.start();
659     // Pathological case of (extremely)long string and narrow lines.
660     // Adjust the range so that we can pick a reasonable midpoint.
661     auto averageCharacterWidth = fragment.width() / fragment.length();
662     auto right = std::min<unsigned>(left + (2 * availableWidth / averageCharacterWidth), fragment.end() - 1);
663     // Preserve the left width for the final split position so that we don't need to remeasure the left side again.
664     float leftSideWidth = 0;
665     while (left < right) {
666         auto middle = (left + right) / 2;
667         auto width = textFragmentIterator.textWidth(fragment.start(), middle + 1, 0);
668         if (width < availableWidth) {
669             left = middle + 1;
670             leftSideWidth = width;
671         } else if (width > availableWidth)
672             right = middle;
673         else {
674             right = middle + 1;
675             leftSideWidth = width;
676             break;
677         }
678     }
679     return { right, leftSideWidth };
680 }
681
682 static TextFragmentIterator::TextFragment splitFragmentToFitLine(TextFragmentIterator::TextFragment& fragmentToSplit,
683     const LineState& line, const TextFragmentIterator& textFragmentIterator)
684 {
685     auto availableWidth = line.availableWidth() - line.width();
686     auto splitFragmentData = split(fragmentToSplit, availableWidth, textFragmentIterator);
687     std::optional<unsigned> hyphenPosition = std::nullopt;
688     // Does first character fit this line?
689     if (splitFragmentData.position == fragmentToSplit.start()) {
690         // Keep at least one character on empty lines.
691         if (line.isEmpty())
692             splitFragmentData.width = textFragmentIterator.textWidth(fragmentToSplit.start(), ++splitFragmentData.position, 0);
693     } else {
694         hyphenPosition = hyphenPositionForFragment(splitFragmentData, fragmentToSplit, line, textFragmentIterator, availableWidth);
695         if (hyphenPosition) {
696             splitFragmentData.position = *hyphenPosition;
697             splitFragmentData.width = textFragmentIterator.textWidth(fragmentToSplit.start(), splitFragmentData.position, 0);
698         }
699     }
700     // If the right side surely does not fit the (next)line, we don't need the width to be kerning/ligature adjusted.
701     // Part of it gets re-measured as the left side during next split.
702     // This saves measuring long chunk of text repeatedly (see pathological case at ::split).
703     auto rightSideWidth = fragmentToSplit.width() - splitFragmentData.width;
704     if (rightSideWidth < 2 * availableWidth)
705         rightSideWidth = textFragmentIterator.textWidth(splitFragmentData.position, fragmentToSplit.end(), 0);
706     return hyphenPosition ? fragmentToSplit.splitWithHyphen(splitFragmentData.position, textFragmentIterator.style().hyphenStringWidth,
707         splitFragmentData.width, rightSideWidth) : fragmentToSplit.split(splitFragmentData.position, splitFragmentData.width, rightSideWidth);
708 }
709
710 enum PreWrapLineBreakRule { Preserve, Ignore };
711
712 static TextFragmentIterator::TextFragment consumeLineBreakIfNeeded(const TextFragmentIterator::TextFragment& fragment, TextFragmentIterator& textFragmentIterator, LineState& line, Layout::RunVector& runs,
713     PreWrapLineBreakRule preWrapLineBreakRule = PreWrapLineBreakRule::Preserve)
714 {
715     if (!fragment.isLineBreak())
716         return fragment;
717
718     bool isHardLinebreak = fragment.type() == TextFragmentIterator::TextFragment::HardLineBreak;
719     // <br> always produces a run. (required by testing output)
720     if (isHardLinebreak)
721         line.appendFragmentAndCreateRunIfNeeded(fragment, runs);
722
723     auto& style = textFragmentIterator.style();
724     if (style.preserveNewline && preWrapLineBreakRule == PreWrapLineBreakRule::Preserve) {
725         if (!isHardLinebreak)
726             return fragment;
727     }
728     return textFragmentIterator.nextTextFragment();
729 }
730
731 static TextFragmentIterator::TextFragment skipWhitespaceIfNeeded(const TextFragmentIterator::TextFragment& fragment, TextFragmentIterator& textFragmentIterator)
732 {
733     if (!textFragmentIterator.style().collapseWhitespace)
734         return fragment;
735
736     TextFragmentIterator::TextFragment firstNonWhitespaceFragment = fragment;
737     while (firstNonWhitespaceFragment.type() == TextFragmentIterator::TextFragment::Whitespace)
738         firstNonWhitespaceFragment = textFragmentIterator.nextTextFragment();
739     return firstNonWhitespaceFragment;
740 }
741
742 static TextFragmentIterator::TextFragment firstFragment(TextFragmentIterator& textFragmentIterator, LineState& currentLine, const LineState& previousLine, Layout::RunVector& runs)
743 {
744     // Handle overflow fragment from previous line.
745     auto overflowedFragment = previousLine.overflowedFragment();
746     if (overflowedFragment.isEmpty())
747         return skipWhitespaceIfNeeded(textFragmentIterator.nextTextFragment(), textFragmentIterator);
748
749     if (overflowedFragment.type() != TextFragmentIterator::TextFragment::Whitespace)
750         return overflowedFragment;
751
752     // Leading whitespace handling.
753     auto& style = textFragmentIterator.style();
754     // Special overflow pre-wrap whitespace handling: skip the overflowed whitespace (even when style says not-collapsible)
755     // if we manage to fit at least one character on the previous line.
756     auto preWrapIsOn = preWrap(style);
757     if ((style.collapseWhitespace || preWrapIsOn) && previousLine.firstCharacterFits()) {
758         // If skipping the whitespace puts us on a newline, skip the newline too as we already wrapped the line.
759         auto firstFragmentCandidate = consumeLineBreakIfNeeded(textFragmentIterator.nextTextFragment(), textFragmentIterator, currentLine, runs,
760             preWrapIsOn ? PreWrapLineBreakRule::Ignore : PreWrapLineBreakRule::Preserve);
761         return skipWhitespaceIfNeeded(firstFragmentCandidate, textFragmentIterator);
762     }
763     return skipWhitespaceIfNeeded(overflowedFragment, textFragmentIterator);
764 }
765
766 static void forceFragmentToLine(LineState& line, TextFragmentIterator& textFragmentIterator, Layout::RunVector& runs, const TextFragmentIterator::TextFragment& fragment)
767 {
768     line.appendFragmentAndCreateRunIfNeeded(fragment, runs);
769     // Check if there are more fragments to add to the current line.
770     auto nextFragment = textFragmentIterator.nextTextFragment();
771     if (fragment.overlapsToNextRenderer()) {
772         while (true) {
773             if (nextFragment.type() != fragment.type())
774                 break;
775             line.appendFragmentAndCreateRunIfNeeded(nextFragment, runs);
776             // Does it overlap to the next segment?
777             if (!nextFragment.overlapsToNextRenderer())
778                 return;
779             nextFragment = textFragmentIterator.nextTextFragment();
780         }
781     }
782     // 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.
783     nextFragment = skipWhitespaceIfNeeded(nextFragment, textFragmentIterator);
784     nextFragment = consumeLineBreakIfNeeded(nextFragment, textFragmentIterator, line, runs);
785     line.setOverflowedFragment(nextFragment);
786 }
787
788 static bool createLineRuns(LineState& line, const LineState& previousLine, Layout::RunVector& runs, TextFragmentIterator& textFragmentIterator)
789 {
790     const auto& style = textFragmentIterator.style();
791     bool lineCanBeWrapped = style.wrapLines || style.breakFirstWordOnOverflow || style.breakAnyWordOnOverflow;
792     auto fragment = firstFragment(textFragmentIterator, line, previousLine, runs);
793     while (fragment.type() != TextFragmentIterator::TextFragment::ContentEnd) {
794         // Hard and soft linebreaks.
795         if (fragment.isLineBreak()) {
796             // 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.)
797             if (line.isEmpty() || fragment.type() == TextFragmentIterator::TextFragment::HardLineBreak) {
798                 if (style.textAlign == TextAlignMode::Right || style.textAlign == TextAlignMode::WebKitRight)
799                     line.removeTrailingWhitespace(runs);
800                 line.appendFragmentAndCreateRunIfNeeded(fragment, runs);
801             }
802             break;
803         }
804         if (lineCanBeWrapped && !line.fits(fragment.width())) {
805             // Overflow wrapping behaviour:
806             // 1. Whitesapce collapse on: whitespace is skipped. Jump to next line.
807             // 2. Whitespace collapse off: whitespace is wrapped.
808             // 3. First, non-whitespace fragment is either wrapped or kept on the line. (depends on overflow-wrap)
809             // 5. Non-whitespace fragment when there's already another fragment on the line either gets wrapped (word-break: break-all)
810             // or gets pushed to the next line.
811             bool emptyLine = line.isEmpty();
812             // Whitespace fragment.
813             if (fragment.type() == TextFragmentIterator::TextFragment::Whitespace) {
814                 if (style.collapseWhitespace) {
815                     // Push collapased whitespace to the next line.
816                     line.setOverflowedFragment(fragment);
817                     break;
818                 }
819                 // Split the whitespace; left part stays on this line, right is pushed to next line.
820                 line.setOverflowedFragment(splitFragmentToFitLine(fragment, line, textFragmentIterator));
821                 line.appendFragmentAndCreateRunIfNeeded(fragment, runs);
822                 break;
823             }
824             // Non-whitespace fragment. (!style.wrapLines: bug138102(preserve existing behavior)
825             if (((emptyLine && style.breakFirstWordOnOverflow) || style.breakAnyWordOnOverflow) || !style.wrapLines) {
826                 // Split the fragment; (modified)fragment stays on this line, overflowedFragment is pushed to next line.
827                 line.setOverflowedFragment(splitFragmentToFitLine(fragment, line, textFragmentIterator));
828                 line.appendFragmentAndCreateRunIfNeeded(fragment, runs);
829                 break;
830             }
831             ASSERT(fragment.type() == TextFragmentIterator::TextFragment::NonWhitespace);
832             // Find out if this non-whitespace fragment has a hyphen where we can break.
833             if (style.shouldHyphenate) {
834                 auto fragmentToSplit = fragment;
835                 // Split and check if we actually ended up with a hyphen.
836                 auto overflowFragment = splitFragmentToFitLine(fragmentToSplit, line, textFragmentIterator);
837                 if (fragmentToSplit.hasHyphen()) {
838                     line.setOverflowedFragment(overflowFragment);
839                     line.appendFragmentAndCreateRunIfNeeded(fragmentToSplit, runs);
840                     break;
841                 }
842                 // No hyphen, no split.
843             }
844             // Non-breakable non-whitespace first fragment. Add it to the current line. -it overflows though.
845             if (emptyLine) {
846                 forceFragmentToLine(line, textFragmentIterator, runs, fragment);
847                 break;
848             }
849             // Non-breakable non-whitespace fragment when there's already content on the line. Push it to the next line.
850             ASSERT(line.lastFragment().isValid());
851             if (line.lastFragment().overlapsToNextRenderer()) {
852                 // Check if this fragment is a continuation of a previous segment. In such cases, we need to remove them all.
853                 textFragmentIterator.revertToEndOfFragment(line.revertToLastCompleteFragment(runs));
854                 break;
855             }
856             line.setOverflowedFragment(fragment);
857             break;
858         }
859         line.appendFragmentAndCreateRunIfNeeded(fragment, runs);
860         // Find the next text fragment.
861         fragment = textFragmentIterator.nextTextFragment(line.width());
862     }
863     return (fragment.type() == TextFragmentIterator::TextFragment::ContentEnd && line.overflowedFragment().isEmpty()) || line.overflowedFragment().type() == TextFragmentIterator::TextFragment::ContentEnd;
864 }
865
866 static ExpansionBehavior expansionBehavior(bool isAfterExpansion, bool lastRunOnLine)
867 {
868     ExpansionBehavior expansionBehavior;
869     expansionBehavior = isAfterExpansion ? ForbidLeadingExpansion : AllowLeadingExpansion;
870     expansionBehavior |= lastRunOnLine ? ForbidTrailingExpansion : AllowTrailingExpansion;
871     return expansionBehavior;
872 }
873
874 static void justifyRuns(const LineState& line, Layout::RunVector& runs, unsigned firstRunIndex)
875 {
876     ASSERT(runs.size());
877     auto widthToDistribute = line.availableWidth() - line.width();
878     if (widthToDistribute <= 0)
879         return;
880
881     auto lastRunIndex = runs.size() - 1;
882     ASSERT(firstRunIndex <= lastRunIndex);
883     Vector<std::pair<unsigned, ExpansionBehavior>> expansionOpportunityList;
884     unsigned expansionOpportunityCountOnThisLine = 0;
885     auto isAfterExpansion = true;
886     for (auto i = firstRunIndex; i <= lastRunIndex; ++i) {
887         const auto& run = runs.at(i);
888         unsigned opportunityCountInRun = 0;
889         std::tie(opportunityCountInRun, isAfterExpansion) = line.expansionOpportunityCount(run.start, run.end);
890         expansionOpportunityList.append(std::make_pair(opportunityCountInRun, expansionBehavior(isAfterExpansion, i == lastRunIndex)));
891         expansionOpportunityCountOnThisLine += opportunityCountInRun;
892     }
893     if (!expansionOpportunityCountOnThisLine)
894         return;
895
896     ASSERT(expansionOpportunityList.size() == lastRunIndex - firstRunIndex + 1);
897     auto expansion = widthToDistribute / expansionOpportunityCountOnThisLine;
898     float accumulatedExpansion = 0;
899     for (auto i = firstRunIndex; i <= lastRunIndex; ++i) {
900         auto& run = runs.at(i);
901         unsigned opportunityCountInRun;
902         std::tie(opportunityCountInRun, run.expansionBehavior) = expansionOpportunityList.at(i - firstRunIndex);
903         run.expansion = opportunityCountInRun * expansion;
904         run.logicalLeft += accumulatedExpansion;
905         run.logicalRight += (accumulatedExpansion + run.expansion);
906         accumulatedExpansion += run.expansion;
907     }
908 }
909
910 static TextAlignMode textAlignForLine(const TextFragmentIterator::Style& style, bool lastLine)
911 {
912     // Fallback to TextAlignMode::Left (START) alignment for non-collapsable content and for the last line before a forced break or the end of the block.
913     auto textAlign = style.textAlign;
914     if (textAlign == TextAlignMode::Justify && (!style.collapseWhitespace || lastLine))
915         textAlign = TextAlignMode::Left;
916     return textAlign;
917 }
918
919 static void closeLineEndingAndAdjustRuns(LineState& line, Layout::RunVector& runs, std::optional<unsigned> lastRunIndexOfPreviousLine, unsigned& lineCount,
920     const TextFragmentIterator& textFragmentIterator, bool lastLineInFlow)
921 {
922     if (!runs.size() || (lastRunIndexOfPreviousLine && runs.size() - 1 == lastRunIndexOfPreviousLine.value()))
923         return;
924     removeTrailingWhitespace(line, runs, textFragmentIterator);
925     if (!runs.size())
926         return;
927     // Adjust runs' position by taking line's alignment into account.
928     const auto& style = textFragmentIterator.style();
929     auto firstRunIndex = lastRunIndexOfPreviousLine ? lastRunIndexOfPreviousLine.value() + 1 : 0;
930     auto lineLogicalLeft = line.logicalLeftOffset();
931     auto textAlign = textAlignForLine(style, lastLineInFlow || (line.lastFragment().isValid() && line.lastFragment().type() == TextFragmentIterator::TextFragment::HardLineBreak));
932     if (textAlign == TextAlignMode::Justify)
933         justifyRuns(line, runs, firstRunIndex);
934     else
935         lineLogicalLeft = computeLineLeft(textAlign, line.availableWidth(), line.width(), line.logicalLeftOffset());
936     for (auto i = firstRunIndex; i < runs.size(); ++i) {
937         runs[i].logicalLeft += lineLogicalLeft;
938         runs[i].logicalRight += lineLogicalLeft;
939     }
940     runs.last().isEndOfLine = true;
941     ++lineCount;
942 }
943
944 static void createTextRuns(Layout::RunVector& runs, RenderBlockFlow& flow, unsigned& lineCount)
945 {
946     LayoutUnit borderAndPaddingBefore = flow.borderAndPaddingBefore();
947     LayoutUnit lineHeight = lineHeightFromFlow(flow);
948     LineState line;
949     unsigned numberOfPrecedingLinesWithHyphen = 0;
950     bool isEndOfContent = false;
951     TextFragmentIterator textFragmentIterator = TextFragmentIterator(flow);
952     std::optional<unsigned> lastRunIndexOfPreviousLine;
953     do {
954         flow.setLogicalHeight(lineHeight * lineCount + borderAndPaddingBefore);
955         LineState previousLine = line;
956         line = LineState();
957         updateLineConstrains(flow, line, previousLine, numberOfPrecedingLinesWithHyphen, textFragmentIterator.style(), !lineCount);
958         isEndOfContent = createLineRuns(line, previousLine, runs, textFragmentIterator);
959         closeLineEndingAndAdjustRuns(line, runs, lastRunIndexOfPreviousLine, lineCount, textFragmentIterator, isEndOfContent);
960         if (runs.size())
961             lastRunIndexOfPreviousLine = runs.size() - 1;
962     } while (!isEndOfContent);
963 }
964
965 std::unique_ptr<Layout> create(RenderBlockFlow& flow)
966 {
967     unsigned lineCount = 0;
968     Layout::RunVector runs;
969     createTextRuns(runs, flow, lineCount);
970     return Layout::create(runs, lineCount, flow);
971 }
972
973 std::unique_ptr<Layout> Layout::create(const RunVector& runVector, unsigned lineCount, const RenderBlockFlow& blockFlow)
974 {
975     void* slot = WTF::fastMalloc(sizeof(Layout) + sizeof(Run) * runVector.size());
976     return std::unique_ptr<Layout>(new (NotNull, slot) Layout(runVector, lineCount, blockFlow));
977 }
978
979 Layout::Layout(const RunVector& runVector, unsigned lineCount, const RenderBlockFlow& blockFlow)
980     : m_lineCount(lineCount)
981     , m_runCount(runVector.size())
982     , m_blockFlowRenderer(blockFlow)
983 {
984     memcpy(m_runs, runVector.data(), m_runCount * sizeof(Run));
985 }
986
987 const RunResolver& Layout::runResolver() const
988 {
989     if (!m_runResolver)
990         m_runResolver = std::make_unique<RunResolver>(m_blockFlowRenderer, *this);
991     return *m_runResolver;
992 }
993
994 Layout::~Layout()
995 {
996     simpleLineLayoutWillBeDeleted(*this);
997 }
998
999 }
1000 }