ab9d2bd8dcfe1fa94c978bf1bcdfd4cd73e2e17c
[WebKit-https.git] / Source / WebCore / rendering / RenderBlockLineLayout.cpp
1 /*
2  * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
3  * Copyright (C) 2003, 2004, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All right reserved.
4  * Copyright (C) 2010 Google Inc. All rights reserved.
5  * Copyright (C) 2013 ChangSeok Oh <shivamidow@gmail.com>
6  * Copyright (C) 2013 Adobe Systems Inc. All right reserved.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public License
19  * along with this library; see the file COPYING.LIB.  If not, write to
20  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  *
23  */
24
25 #include "config.h"
26
27 #include "AXObjectCache.h"
28 #include "BidiResolver.h"
29 #include "BreakingContext.h"
30 #include "FloatingObjects.h"
31 #include "InlineElementBox.h"
32 #include "InlineIterator.h"
33 #include "InlineTextBox.h"
34 #include "InlineTextBoxStyle.h"
35 #include "LineLayoutState.h"
36 #include "Logging.h"
37 #include "RenderBlockFlow.h"
38 #include "RenderFlowThread.h"
39 #include "RenderLineBreak.h"
40 #include "RenderRegion.h"
41 #include "RenderRubyBase.h"
42 #include "RenderRubyText.h"
43 #include "RenderView.h"
44 #include "SVGRootInlineBox.h"
45 #include "Settings.h"
46 #include "SimpleLineLayoutFunctions.h"
47 #include "TrailingFloatsRootInlineBox.h"
48 #include "VerticalPositionCache.h"
49 #include <wtf/RefCountedLeakCounter.h>
50 #include <wtf/StdLibExtras.h>
51
52 namespace WebCore {
53
54 static void determineDirectionality(TextDirection& dir, InlineIterator iter)
55 {
56     while (!iter.atEnd()) {
57         if (iter.atParagraphSeparator())
58             return;
59         if (UChar current = iter.current()) {
60             UCharDirection charDirection = u_charDirection(current);
61             if (charDirection == U_LEFT_TO_RIGHT) {
62                 dir = LTR;
63                 return;
64             }
65             if (charDirection == U_RIGHT_TO_LEFT || charDirection == U_RIGHT_TO_LEFT_ARABIC) {
66                 dir = RTL;
67                 return;
68             }
69         }
70         iter.increment();
71     }
72 }
73
74 inline BidiRun* createRun(int start, int end, RenderObject* obj, InlineBidiResolver& resolver)
75 {
76     ASSERT(obj);
77     return new BidiRun(start, end, *obj, resolver.context(), resolver.dir());
78 }
79
80 void RenderBlockFlow::appendRunsForObject(BidiRunList<BidiRun>& runs, int start, int end, RenderObject* obj, InlineBidiResolver& resolver)
81 {
82     if (start > end || shouldSkipCreatingRunsForObject(obj))
83         return;
84
85     LineMidpointState& lineMidpointState = resolver.midpointState();
86     bool haveNextMidpoint = (lineMidpointState.currentMidpoint() < lineMidpointState.numMidpoints());
87     InlineIterator nextMidpoint;
88     if (haveNextMidpoint)
89         nextMidpoint = lineMidpointState.midpoints()[lineMidpointState.currentMidpoint()];
90     if (lineMidpointState.betweenMidpoints()) {
91         if (!(haveNextMidpoint && nextMidpoint.renderer() == obj))
92             return;
93         // This is a new start point. Stop ignoring objects and
94         // adjust our start.
95         lineMidpointState.setBetweenMidpoints(false);
96         start = nextMidpoint.offset();
97         lineMidpointState.incrementCurrentMidpoint();
98         if (start < end)
99             return appendRunsForObject(runs, start, end, obj, resolver);
100     } else {
101         if (!haveNextMidpoint || (obj != nextMidpoint.renderer())) {
102             runs.addRun(createRun(start, end, obj, resolver));
103             return;
104         }
105
106         // An end midpoint has been encountered within our object.  We
107         // need to go ahead and append a run with our endpoint.
108         if (static_cast<int>(nextMidpoint.offset() + 1) <= end) {
109             lineMidpointState.setBetweenMidpoints(true);
110             lineMidpointState.incrementCurrentMidpoint();
111             // The end of the line is before the object we're inspecting. Skip everything and return
112             if (nextMidpoint.refersToEndOfPreviousNode())
113                 return;
114             if (static_cast<int>(nextMidpoint.offset() + 1) > start)
115                 runs.addRun(createRun(start, nextMidpoint.offset() + 1, obj, resolver));
116             appendRunsForObject(runs, nextMidpoint.offset() + 1, end, obj, resolver);
117         } else
118            runs.addRun(createRun(start, end, obj, resolver));
119     }
120 }
121
122 std::unique_ptr<RootInlineBox> RenderBlockFlow::createRootInlineBox()
123 {
124     return std::make_unique<RootInlineBox>(*this);
125 }
126
127 RootInlineBox* RenderBlockFlow::createAndAppendRootInlineBox()
128 {
129     auto newRootBox = createRootInlineBox();
130     RootInlineBox* rootBox = newRootBox.get();
131     m_lineBoxes.appendLineBox(WTF::move(newRootBox));
132
133     if (UNLIKELY(AXObjectCache::accessibilityEnabled()) && firstRootBox() == rootBox) {
134         if (AXObjectCache* cache = document().existingAXObjectCache())
135             cache->recomputeIsIgnored(this);
136     }
137
138     return rootBox;
139 }
140
141 static inline InlineBox* createInlineBoxForRenderer(RenderObject* renderer, bool isRootLineBox, bool isOnlyRun = false)
142 {
143     if (isRootLineBox)
144         return downcast<RenderBlockFlow>(*renderer).createAndAppendRootInlineBox();
145
146     if (is<RenderText>(*renderer))
147         return downcast<RenderText>(*renderer).createInlineTextBox();
148
149     if (is<RenderBox>(*renderer)) {
150         // FIXME: This is terrible. This branch returns an *owned* pointer!
151         return downcast<RenderBox>(*renderer).createInlineBox().release();
152     }
153
154     if (is<RenderLineBreak>(*renderer)) {
155         // FIXME: This is terrible. This branch returns an *owned* pointer!
156         auto inlineBox = downcast<RenderLineBreak>(*renderer).createInlineBox().release();
157         // We only treat a box as text for a <br> if we are on a line by ourself or in strict mode
158         // (Note the use of strict mode. In "almost strict" mode, we don't treat the box for <br> as text.)
159         inlineBox->setBehavesLikeText(isOnlyRun || renderer->document().inNoQuirksMode() || renderer->isLineBreakOpportunity());
160         return inlineBox;
161     }
162
163     return downcast<RenderInline>(*renderer).createAndAppendInlineFlowBox();
164 }
165
166 static inline void dirtyLineBoxesForRenderer(RenderObject& renderer, bool fullLayout)
167 {
168     if (is<RenderText>(renderer)) {
169         RenderText& renderText = downcast<RenderText>(renderer);
170         updateCounterIfNeeded(renderText);
171         renderText.dirtyLineBoxes(fullLayout);
172     } else if (is<RenderLineBreak>(renderer))
173         downcast<RenderLineBreak>(renderer).dirtyLineBoxes(fullLayout);
174     else
175         downcast<RenderInline>(renderer).dirtyLineBoxes(fullLayout);
176 }
177
178 static bool parentIsConstructedOrHaveNext(InlineFlowBox* parentBox)
179 {
180     do {
181         if (parentBox->isConstructed() || parentBox->nextOnLine())
182             return true;
183         parentBox = parentBox->parent();
184     } while (parentBox);
185     return false;
186 }
187
188 InlineFlowBox* RenderBlockFlow::createLineBoxes(RenderObject* obj, const LineInfo& lineInfo, InlineBox* childBox)
189 {
190     // See if we have an unconstructed line box for this object that is also
191     // the last item on the line.
192     unsigned lineDepth = 1;
193     InlineFlowBox* parentBox = nullptr;
194     InlineFlowBox* result = nullptr;
195     bool hasDefaultLineBoxContain = style().lineBoxContain() == RenderStyle::initialLineBoxContain();
196     bool isBlockInsideInline = childBox->renderer().isAnonymousInlineBlock();
197     do {
198         ASSERT_WITH_SECURITY_IMPLICATION(is<RenderInline>(*obj) || obj == this);
199
200         RenderInline* inlineFlow = obj != this ? downcast<RenderInline>(obj) : nullptr;
201
202         // Get the last box we made for this render object.
203         parentBox = inlineFlow ? inlineFlow->lastLineBox() : downcast<RenderBlockFlow>(*obj).lastRootBox();
204
205         // If this box or its ancestor is constructed then it is from a previous line, and we need
206         // to make a new box for our line.  If this box or its ancestor is unconstructed but it has
207         // something following it on the line, then we know we have to make a new box
208         // as well.  In this situation our inline has actually been split in two on
209         // the same line (this can happen with very fancy language mixtures).
210         bool constructedNewBox = false;
211         bool allowedToConstructNewBox = !hasDefaultLineBoxContain || !inlineFlow || inlineFlow->alwaysCreateLineBoxes();
212         bool canUseExistingParentBox = parentBox && !parentIsConstructedOrHaveNext(parentBox);
213         if (allowedToConstructNewBox && !canUseExistingParentBox) {
214             // We need to make a new box for this render object.  Once
215             // made, we need to place it at the end of the current line.
216             InlineBox* newBox = createInlineBoxForRenderer(obj, obj == this);
217             parentBox = downcast<InlineFlowBox>(newBox);
218             parentBox->setIsFirstLine(lineInfo.isFirstLine());
219             parentBox->setIsHorizontal(isHorizontalWritingMode());
220             parentBox->setHasAnonymousInlineBlock(isBlockInsideInline);
221             if (!hasDefaultLineBoxContain)
222                 parentBox->clearDescendantsHaveSameLineHeightAndBaseline();
223             constructedNewBox = true;
224         }
225
226         if (constructedNewBox || canUseExistingParentBox) {
227             if (!result)
228                 result = parentBox;
229
230             // If we have hit the block itself, then |box| represents the root
231             // inline box for the line, and it doesn't have to be appended to any parent
232             // inline.
233             if (childBox)
234                 parentBox->addToLine(childBox);
235
236             if (!constructedNewBox || obj == this)
237                 break;
238
239             childBox = parentBox;
240         }
241
242         // If we've exceeded our line depth, then jump straight to the root and skip all the remaining
243         // intermediate inline flows.
244         obj = (++lineDepth >= cMaxLineDepth) ? this : obj->parent();
245
246     } while (true);
247
248     return result;
249 }
250
251 template <typename CharacterType>
252 static inline bool endsWithASCIISpaces(const CharacterType* characters, unsigned pos, unsigned end)
253 {
254     while (isASCIISpace(characters[pos])) {
255         pos++;
256         if (pos >= end)
257             return true;
258     }
259     return false;
260 }
261
262 static bool reachedEndOfTextRenderer(const BidiRunList<BidiRun>& bidiRuns)
263 {
264     BidiRun* run = bidiRuns.logicallyLastRun();
265     if (!run)
266         return true;
267     unsigned pos = run->stop();
268     const RenderObject& renderer = run->renderer();
269     if (!is<RenderText>(renderer))
270         return false;
271     const RenderText& renderText = downcast<RenderText>(renderer);
272     unsigned length = renderText.textLength();
273     if (pos >= length)
274         return true;
275
276     if (renderText.is8Bit())
277         return endsWithASCIISpaces(renderText.characters8(), pos, length);
278     return endsWithASCIISpaces(renderText.characters16(), pos, length);
279 }
280
281 RootInlineBox* RenderBlockFlow::constructLine(BidiRunList<BidiRun>& bidiRuns, const LineInfo& lineInfo)
282 {
283     ASSERT(bidiRuns.firstRun());
284
285     bool rootHasSelectedChildren = false;
286     InlineFlowBox* parentBox = 0;
287     int runCount = bidiRuns.runCount() - lineInfo.runsFromLeadingWhitespace();
288     
289     for (BidiRun* r = bidiRuns.firstRun(); r; r = r->next()) {
290         // Create a box for our object.
291         bool isOnlyRun = (runCount == 1);
292         if (runCount == 2 && !r->renderer().isListMarker())
293             isOnlyRun = (!style().isLeftToRightDirection() ? bidiRuns.lastRun() : bidiRuns.firstRun())->renderer().isListMarker();
294
295         if (lineInfo.isEmpty())
296             continue;
297
298         InlineBox* box = createInlineBoxForRenderer(&r->renderer(), false, isOnlyRun);
299         r->setBox(*box);
300
301         if (!rootHasSelectedChildren && box->renderer().selectionState() != RenderObject::SelectionNone)
302             rootHasSelectedChildren = true;
303         
304         // If we have no parent box yet, or if the run is not simply a sibling,
305         // then we need to construct inline boxes as necessary to properly enclose the
306         // run's inline box. Segments can only be siblings at the root level, as
307         // they are positioned separately.
308         if (!parentBox || &parentBox->renderer() != r->renderer().parent()) {
309             // Create new inline boxes all the way back to the appropriate insertion point.
310             RenderObject* parentToUse = r->renderer().parent();
311             parentBox = createLineBoxes(parentToUse, lineInfo, box);
312         } else {
313             // Append the inline box to this line.
314             parentBox->addToLine(box);
315         }
316
317         bool visuallyOrdered = r->renderer().style().rtlOrdering() == VisualOrder;
318         box->setBidiLevel(r->level());
319
320         if (is<InlineTextBox>(*box)) {
321             auto& textBox = downcast<InlineTextBox>(*box);
322             textBox.setStart(r->m_start);
323             textBox.setLen(r->m_stop - r->m_start);
324             textBox.setDirOverride(r->dirOverride(visuallyOrdered));
325             if (r->m_hasHyphen)
326                 textBox.setHasHyphen(true);
327         }
328     }
329
330     // We should have a root inline box.  It should be unconstructed and
331     // be the last continuation of our line list.
332     ASSERT(lastRootBox() && !lastRootBox()->isConstructed());
333
334     // Set the m_selectedChildren flag on the root inline box if one of the leaf inline box
335     // from the bidi runs walk above has a selection state.
336     if (rootHasSelectedChildren)
337         lastRootBox()->root().setHasSelectedChildren(true);
338
339     // Set bits on our inline flow boxes that indicate which sides should
340     // paint borders/margins/padding.  This knowledge will ultimately be used when
341     // we determine the horizontal positions and widths of all the inline boxes on
342     // the line.
343     bool isLogicallyLastRunWrapped = bidiRuns.logicallyLastRun()->renderer().isText() ? !reachedEndOfTextRenderer(bidiRuns) : true;
344     lastRootBox()->determineSpacingForFlowBoxes(lineInfo.isLastLine(), isLogicallyLastRunWrapped, &bidiRuns.logicallyLastRun()->renderer());
345
346     // Now mark the line boxes as being constructed.
347     lastRootBox()->setConstructed();
348
349     // Return the last line.
350     return lastRootBox();
351 }
352
353 ETextAlign RenderBlockFlow::textAlignmentForLine(bool endsWithSoftBreak) const
354 {
355     ETextAlign alignment = style().textAlign();
356 #if ENABLE(CSS3_TEXT)
357     TextJustify textJustify = style().textJustify();
358     if (alignment == JUSTIFY && textJustify == TextJustifyNone)
359         return style().direction() == LTR ? LEFT : RIGHT;
360 #endif
361
362     if (endsWithSoftBreak)
363         return alignment;
364
365 #if !ENABLE(CSS3_TEXT)
366     return (alignment == JUSTIFY) ? TASTART : alignment;
367 #else
368     if (alignment != JUSTIFY)
369         return alignment;
370
371     TextAlignLast alignmentLast = style().textAlignLast();
372     switch (alignmentLast) {
373     case TextAlignLastStart:
374         return TASTART;
375     case TextAlignLastEnd:
376         return TAEND;
377     case TextAlignLastLeft:
378         return LEFT;
379     case TextAlignLastRight:
380         return RIGHT;
381     case TextAlignLastCenter:
382         return CENTER;
383     case TextAlignLastJustify:
384         return JUSTIFY;
385     case TextAlignLastAuto:
386         if (textJustify == TextJustifyDistribute)
387             return JUSTIFY;
388         return TASTART;
389     }
390     return alignment;
391 #endif
392 }
393
394 static void updateLogicalWidthForLeftAlignedBlock(bool isLeftToRightDirection, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float availableLogicalWidth)
395 {
396     // The direction of the block should determine what happens with wide lines.
397     // In particular with RTL blocks, wide lines should still spill out to the left.
398     if (isLeftToRightDirection) {
399         if (totalLogicalWidth > availableLogicalWidth && trailingSpaceRun)
400             trailingSpaceRun->box()->setLogicalWidth(std::max<float>(0, trailingSpaceRun->box()->logicalWidth() - totalLogicalWidth + availableLogicalWidth));
401         return;
402     }
403
404     if (trailingSpaceRun)
405         trailingSpaceRun->box()->setLogicalWidth(0);
406     else if (totalLogicalWidth > availableLogicalWidth)
407         logicalLeft -= (totalLogicalWidth - availableLogicalWidth);
408 }
409
410 static void updateLogicalWidthForRightAlignedBlock(bool isLeftToRightDirection, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float availableLogicalWidth)
411 {
412     // Wide lines spill out of the block based off direction.
413     // So even if text-align is right, if direction is LTR, wide lines should overflow out of the right
414     // side of the block.
415     if (isLeftToRightDirection) {
416         if (trailingSpaceRun) {
417             totalLogicalWidth -= trailingSpaceRun->box()->logicalWidth();
418             trailingSpaceRun->box()->setLogicalWidth(0);
419         }
420         if (totalLogicalWidth < availableLogicalWidth)
421             logicalLeft += availableLogicalWidth - totalLogicalWidth;
422         return;
423     }
424
425     if (totalLogicalWidth > availableLogicalWidth && trailingSpaceRun) {
426         trailingSpaceRun->box()->setLogicalWidth(std::max<float>(0, trailingSpaceRun->box()->logicalWidth() - totalLogicalWidth + availableLogicalWidth));
427         totalLogicalWidth -= trailingSpaceRun->box()->logicalWidth();
428     } else
429         logicalLeft += availableLogicalWidth - totalLogicalWidth;
430 }
431
432 static void updateLogicalWidthForCenterAlignedBlock(bool isLeftToRightDirection, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float availableLogicalWidth)
433 {
434     float trailingSpaceWidth = 0;
435     if (trailingSpaceRun) {
436         totalLogicalWidth -= trailingSpaceRun->box()->logicalWidth();
437         trailingSpaceWidth = std::min(trailingSpaceRun->box()->logicalWidth(), (availableLogicalWidth - totalLogicalWidth + 1) / 2);
438         trailingSpaceRun->box()->setLogicalWidth(std::max<float>(0, trailingSpaceWidth));
439     }
440     if (isLeftToRightDirection)
441         logicalLeft += std::max<float>((availableLogicalWidth - totalLogicalWidth) / 2, 0);
442     else
443         logicalLeft += totalLogicalWidth > availableLogicalWidth ? (availableLogicalWidth - totalLogicalWidth) : (availableLogicalWidth - totalLogicalWidth) / 2 - trailingSpaceWidth;
444 }
445
446 void RenderBlockFlow::setMarginsForRubyRun(BidiRun* run, RenderRubyRun& renderer, RenderObject* previousObject, const LineInfo& lineInfo)
447 {
448     float startOverhang;
449     float endOverhang;
450     RenderObject* nextObject = 0;
451     for (BidiRun* runWithNextObject = run->next(); runWithNextObject; runWithNextObject = runWithNextObject->next()) {
452         if (!runWithNextObject->renderer().isOutOfFlowPositioned() && !runWithNextObject->box()->isLineBreak()) {
453             nextObject = &runWithNextObject->renderer();
454             break;
455         }
456     }
457     renderer.getOverhang(lineInfo.isFirstLine(), renderer.style().isLeftToRightDirection() ? previousObject : nextObject, renderer.style().isLeftToRightDirection() ? nextObject : previousObject, startOverhang, endOverhang);
458     setMarginStartForChild(renderer, -startOverhang);
459     setMarginEndForChild(renderer, -endOverhang);
460 }
461
462 static inline void setLogicalWidthForTextRun(RootInlineBox* lineBox, BidiRun* run, RenderText& renderer, float xPos, const LineInfo& lineInfo,
463     GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache, WordMeasurements& wordMeasurements)
464 {
465     HashSet<const Font*> fallbackFonts;
466     GlyphOverflow glyphOverflow;
467
468     const FontCascade& font = lineStyle(*renderer.parent(), lineInfo).fontCascade();
469     // Always compute glyph overflow if the block's line-box-contain value is "glyphs".
470     if (lineBox->fitsToGlyphs()) {
471         // If we don't stick out of the root line's font box, then don't bother computing our glyph overflow. This optimization
472         // will keep us from computing glyph bounds in nearly all cases.
473         bool includeRootLine = lineBox->includesRootLineBoxFontOrLeading();
474         int baselineShift = lineBox->verticalPositionForBox(run->box(), verticalPositionCache);
475         int rootDescent = includeRootLine ? font.fontMetrics().descent() : 0;
476         int rootAscent = includeRootLine ? font.fontMetrics().ascent() : 0;
477         int boxAscent = font.fontMetrics().ascent() - baselineShift;
478         int boxDescent = font.fontMetrics().descent() + baselineShift;
479         if (boxAscent > rootDescent ||  boxDescent > rootAscent)
480             glyphOverflow.computeBounds = true; 
481     }
482     
483     LayoutUnit hyphenWidth = 0;
484     if (downcast<InlineTextBox>(*run->box()).hasHyphen())
485         hyphenWidth = measureHyphenWidth(renderer, font, &fallbackFonts);
486
487     float measuredWidth = 0;
488
489     bool kerningIsEnabled = font.typesettingFeatures() & Kerning;
490     bool canUseSimpleFontCodePath = renderer.canUseSimpleFontCodePath();
491     
492     // Since we don't cache glyph overflows, we need to re-measure the run if
493     // the style is linebox-contain: glyph.
494     
495     if (!lineBox->fitsToGlyphs() && canUseSimpleFontCodePath) {
496         int lastEndOffset = run->m_start;
497         for (size_t i = 0, size = wordMeasurements.size(); i < size && lastEndOffset < run->m_stop; ++i) {
498             WordMeasurement& wordMeasurement = wordMeasurements[i];
499             if (wordMeasurement.width <= 0 || wordMeasurement.startOffset == wordMeasurement.endOffset)
500                 continue;
501             if (wordMeasurement.renderer != &renderer || wordMeasurement.startOffset != lastEndOffset || wordMeasurement.endOffset > run->m_stop)
502                 continue;
503
504             lastEndOffset = wordMeasurement.endOffset;
505             if (kerningIsEnabled && lastEndOffset == run->m_stop) {
506                 int wordLength = lastEndOffset - wordMeasurement.startOffset;
507                 GlyphOverflow overflow;
508                 measuredWidth += renderer.width(wordMeasurement.startOffset, wordLength, xPos + measuredWidth, lineInfo.isFirstLine(),
509                     &wordMeasurement.fallbackFonts, &overflow);
510                 UChar c = renderer.characterAt(wordMeasurement.startOffset);
511                 if (i > 0 && wordLength == 1 && (c == ' ' || c == '\t'))
512                     measuredWidth += renderer.style().fontCascade().wordSpacing();
513             } else
514                 measuredWidth += wordMeasurement.width;
515             if (!wordMeasurement.fallbackFonts.isEmpty()) {
516                 HashSet<const Font*>::const_iterator end = wordMeasurement.fallbackFonts.end();
517                 for (HashSet<const Font*>::const_iterator it = wordMeasurement.fallbackFonts.begin(); it != end; ++it)
518                     fallbackFonts.add(*it);
519             }
520         }
521         if (measuredWidth && lastEndOffset != run->m_stop) {
522             // If we don't have enough cached data, we'll measure the run again.
523             measuredWidth = 0;
524             fallbackFonts.clear();
525         }
526     }
527
528     if (!measuredWidth)
529         measuredWidth = renderer.width(run->m_start, run->m_stop - run->m_start, xPos, lineInfo.isFirstLine(), &fallbackFonts, &glyphOverflow);
530
531     run->box()->setLogicalWidth(measuredWidth + hyphenWidth);
532     if (!fallbackFonts.isEmpty()) {
533         ASSERT(run->box()->behavesLikeText());
534         GlyphOverflowAndFallbackFontsMap::iterator it = textBoxDataMap.add(downcast<InlineTextBox>(run->box()), std::make_pair(Vector<const Font*>(), GlyphOverflow())).iterator;
535         ASSERT(it->value.first.isEmpty());
536         copyToVector(fallbackFonts, it->value.first);
537         run->box()->parent()->clearDescendantsHaveSameLineHeightAndBaseline();
538     }
539
540     // Include text decoration visual overflow as part of the glyph overflow.
541     if (renderer.style().textDecorationsInEffect() != TextDecorationNone)
542         glyphOverflow.extendTo(visualOverflowForDecorations(run->box()->lineStyle(), downcast<InlineTextBox>(run->box())));
543
544     if (!glyphOverflow.isEmpty()) {
545         ASSERT(run->box()->behavesLikeText());
546         GlyphOverflowAndFallbackFontsMap::iterator it = textBoxDataMap.add(downcast<InlineTextBox>(run->box()), std::make_pair(Vector<const Font*>(), GlyphOverflow())).iterator;
547         it->value.second = glyphOverflow;
548         run->box()->clearKnownToHaveNoOverflow();
549     }
550 }
551
552 void RenderBlockFlow::updateRubyForJustifiedText(RenderRubyRun& rubyRun, BidiRun& r, const Vector<unsigned, 16>& expansionOpportunities, unsigned& expansionOpportunityCount, float& totalLogicalWidth, float availableLogicalWidth, size_t& i)
553 {
554     if (!rubyRun.rubyBase() || !rubyRun.rubyBase()->firstRootBox() || rubyRun.rubyBase()->firstRootBox()->nextRootBox() || !r.renderer().style().collapseWhiteSpace())
555         return;
556
557     auto& rubyBase = *rubyRun.rubyBase();
558     auto& rootBox = *rubyBase.firstRootBox();
559
560     float totalExpansion = 0;
561     unsigned totalOpportunitiesInRun = 0;
562     for (auto* leafChild = rootBox.firstLeafChild(); leafChild; leafChild = leafChild->nextLeafChild()) {
563         if (!leafChild->isInlineTextBox())
564             continue;
565
566         unsigned opportunitiesInRun = expansionOpportunities[i++];
567         ASSERT(opportunitiesInRun <= expansionOpportunityCount);
568         auto expansion = (availableLogicalWidth - totalLogicalWidth) * opportunitiesInRun / expansionOpportunityCount;
569         totalExpansion += expansion;
570         totalOpportunitiesInRun += opportunitiesInRun;
571     }
572
573     if (totalOpportunitiesInRun) {
574         ASSERT(!rubyRun.hasOverrideWidth());
575         float newBaseWidth = rubyRun.logicalWidth() + totalExpansion + marginStartForChild(rubyRun) + marginEndForChild(rubyRun);
576         float newRubyRunWidth = rubyRun.logicalWidth() + totalExpansion;
577         rubyBase.setInitialOffset((newRubyRunWidth - newBaseWidth) / 2);
578         rubyRun.setOverrideLogicalContentWidth(newRubyRunWidth);
579         rubyRun.setNeedsLayout(MarkOnlyThis);
580         rootBox.markDirty();
581         if (RenderRubyText* rubyText = rubyRun.rubyText()) {
582             if (RootInlineBox* textRootBox = rubyText->firstRootBox())
583                 textRootBox->markDirty();
584         }
585         rubyRun.layoutBlock(true);
586         rubyRun.clearOverrideLogicalContentWidth();
587         r.box()->setExpansion(newRubyRunWidth - r.box()->logicalWidth());
588
589         // This relayout caused the size of the RenderRubyText and the RenderRubyBase to change, dependent on the line's current expansion. Next time we relayout the
590         // RenderRubyRun, make sure that we relayout the RenderRubyBase and RenderRubyText as well.
591         rubyBase.setNeedsLayout(MarkOnlyThis);
592         if (RenderRubyText* rubyText = rubyRun.rubyText())
593             rubyText->setNeedsLayout(MarkOnlyThis);
594         if (rubyBase.lastLeafChild() && is<RenderText>(rubyBase.lastLeafChild()) && r.box() && r.box()->nextLeafChild() && !r.box()->nextLeafChild()->isLineBreak())
595             downcast<RenderText>(rubyBase.lastLeafChild())->setContentIsKnownToFollow(true);
596
597         totalLogicalWidth += totalExpansion;
598         expansionOpportunityCount -= totalOpportunitiesInRun;
599     }
600 }
601
602 void RenderBlockFlow::computeExpansionForJustifiedText(BidiRun* firstRun, BidiRun* trailingSpaceRun, const Vector<unsigned, 16>& expansionOpportunities, unsigned expansionOpportunityCount, float totalLogicalWidth, float availableLogicalWidth)
603 {
604     if (!expansionOpportunityCount || availableLogicalWidth <= totalLogicalWidth)
605         return;
606
607     size_t i = 0;
608     for (BidiRun* run = firstRun; run; run = run->next()) {
609         if (!run->box() || run == trailingSpaceRun)
610             continue;
611         
612         if (is<RenderText>(run->renderer())) {
613             unsigned opportunitiesInRun = expansionOpportunities[i++];
614             
615             ASSERT(opportunitiesInRun <= expansionOpportunityCount);
616             
617             // Only justify text if whitespace is collapsed.
618             if (run->renderer().style().collapseWhiteSpace()) {
619                 InlineTextBox& textBox = downcast<InlineTextBox>(*run->box());
620                 float expansion = (availableLogicalWidth - totalLogicalWidth) * opportunitiesInRun / expansionOpportunityCount;
621                 textBox.setExpansion(expansion);
622                 totalLogicalWidth += expansion;
623             }
624             expansionOpportunityCount -= opportunitiesInRun;
625         } else if (is<RenderRubyRun>(run->renderer()))
626             updateRubyForJustifiedText(downcast<RenderRubyRun>(run->renderer()), *run, expansionOpportunities, expansionOpportunityCount, totalLogicalWidth, availableLogicalWidth, i);
627
628         if (!expansionOpportunityCount)
629             break;
630     }
631 }
632
633 void RenderBlockFlow::updateLogicalWidthForAlignment(const ETextAlign& textAlign, const RootInlineBox* rootInlineBox, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float& availableLogicalWidth, int expansionOpportunityCount)
634 {
635     TextDirection direction;
636     if (rootInlineBox && style().unicodeBidi() == Plaintext)
637         direction = rootInlineBox->direction();
638     else
639         direction = style().direction();
640
641     // Armed with the total width of the line (without justification),
642     // we now examine our text-align property in order to determine where to position the
643     // objects horizontally. The total width of the line can be increased if we end up
644     // justifying text.
645     switch (textAlign) {
646     case LEFT:
647     case WEBKIT_LEFT:
648         updateLogicalWidthForLeftAlignedBlock(style().isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
649         break;
650     case RIGHT:
651     case WEBKIT_RIGHT:
652         updateLogicalWidthForRightAlignedBlock(style().isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
653         break;
654     case CENTER:
655     case WEBKIT_CENTER:
656         updateLogicalWidthForCenterAlignedBlock(style().isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
657         break;
658     case JUSTIFY:
659         adjustInlineDirectionLineBounds(expansionOpportunityCount, logicalLeft, availableLogicalWidth);
660         if (expansionOpportunityCount) {
661             if (trailingSpaceRun) {
662                 totalLogicalWidth -= trailingSpaceRun->box()->logicalWidth();
663                 trailingSpaceRun->box()->setLogicalWidth(0);
664             }
665             break;
666         }
667         FALLTHROUGH;
668     case TASTART:
669         if (direction == LTR)
670             updateLogicalWidthForLeftAlignedBlock(style().isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
671         else
672             updateLogicalWidthForRightAlignedBlock(style().isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
673         break;
674     case TAEND:
675         if (direction == LTR)
676             updateLogicalWidthForRightAlignedBlock(style().isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
677         else
678             updateLogicalWidthForLeftAlignedBlock(style().isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
679         break;
680     }
681 }
682
683 static void updateLogicalInlinePositions(RenderBlockFlow& block, float& lineLogicalLeft, float& lineLogicalRight, float& availableLogicalWidth, bool firstLine, IndentTextOrNot shouldIndentText, LayoutUnit boxLogicalHeight,
684     RootInlineBox* rootBox)
685 {
686     LayoutUnit lineLogicalHeight = block.minLineHeightForReplacedRenderer(firstLine, boxLogicalHeight);
687     if (rootBox->hasAnonymousInlineBlock()) {
688         lineLogicalLeft = block.logicalLeftOffsetForContent(block.logicalHeight());
689         lineLogicalRight = block.logicalRightOffsetForContent(block.logicalHeight());
690     } else {
691         lineLogicalLeft = block.logicalLeftOffsetForLine(block.logicalHeight(), shouldIndentText == IndentText, lineLogicalHeight);
692         lineLogicalRight = block.logicalRightOffsetForLine(block.logicalHeight(), shouldIndentText == IndentText, lineLogicalHeight);
693     }
694     availableLogicalWidth = lineLogicalRight - lineLogicalLeft;
695 }
696
697 void RenderBlockFlow::computeInlineDirectionPositionsForLine(RootInlineBox* lineBox, const LineInfo& lineInfo, BidiRun* firstRun, BidiRun* trailingSpaceRun, bool reachedEnd, GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache, WordMeasurements& wordMeasurements)
698 {
699     ETextAlign textAlign = textAlignmentForLine(!reachedEnd && !lineBox->endsWithBreak());
700     
701     // CSS 2.1: "'Text-indent' only affects a line if it is the first formatted line of an element. For example, the first line of an anonymous block 
702     // box is only affected if it is the first child of its parent element."
703     // CSS3 "text-indent", "-webkit-each-line" affects the first line of the block container as well as each line after a forced line break,
704     // but does not affect lines after a soft wrap break.
705     bool isFirstLine = lineInfo.isFirstLine() && !(isAnonymousBlock() && parent()->firstChild() != this);
706     bool isAfterHardLineBreak = lineBox->prevRootBox() && lineBox->prevRootBox()->endsWithBreak();
707     IndentTextOrNot shouldIndentText = requiresIndent(isFirstLine, isAfterHardLineBreak, style());
708     float lineLogicalLeft;
709     float lineLogicalRight;
710     float availableLogicalWidth;
711     updateLogicalInlinePositions(*this, lineLogicalLeft, lineLogicalRight, availableLogicalWidth, isFirstLine, shouldIndentText, 0, lineBox);
712     bool needsWordSpacing;
713
714     if (firstRun && firstRun->renderer().isReplaced()) {
715         RenderBox& renderBox = downcast<RenderBox>(firstRun->renderer());
716         updateLogicalInlinePositions(*this, lineLogicalLeft, lineLogicalRight, availableLogicalWidth, isFirstLine, shouldIndentText, renderBox.logicalHeight(), lineBox);
717     }
718
719     computeInlineDirectionPositionsForSegment(lineBox, lineInfo, textAlign, lineLogicalLeft, availableLogicalWidth, firstRun, trailingSpaceRun, textBoxDataMap, verticalPositionCache, wordMeasurements);
720     // The widths of all runs are now known. We can now place every inline box (and
721     // compute accurate widths for the inline flow boxes).
722     needsWordSpacing = false;
723     lineBox->placeBoxesInInlineDirection(lineLogicalLeft, needsWordSpacing);
724 }
725
726 static inline ExpansionBehavior expansionBehaviorForInlineTextBox(bool isAfterExpansion)
727 {
728     ExpansionBehavior result = AllowTrailingExpansion;
729     result |= isAfterExpansion ? ForbidLeadingExpansion : AllowLeadingExpansion;
730     return result;
731 }
732
733 static inline void applyExpansionBehavior(InlineTextBox& textBox, ExpansionBehavior expansionBehavior)
734 {
735     switch (expansionBehavior & LeadingExpansionMask) {
736     case ForceLeadingExpansion:
737         textBox.setForceLeadingExpansion();
738         break;
739     case ForbidLeadingExpansion:
740         textBox.setCanHaveLeadingExpansion(false);
741         break;
742     case AllowLeadingExpansion:
743         textBox.setCanHaveLeadingExpansion(true);
744         break;
745     default:
746         ASSERT_NOT_REACHED();
747         break;
748     }
749     switch (expansionBehavior & TrailingExpansionMask) {
750     case ForceTrailingExpansion:
751         textBox.setForceTrailingExpansion();
752         break;
753     case ForbidTrailingExpansion:
754         textBox.setCanHaveTrailingExpansion(false);
755         break;
756     case AllowTrailingExpansion:
757         textBox.setCanHaveTrailingExpansion(true);
758         break;
759     default:
760         ASSERT_NOT_REACHED();
761         break;
762     }
763 }
764
765 BidiRun* RenderBlockFlow::computeInlineDirectionPositionsForSegment(RootInlineBox* lineBox, const LineInfo& lineInfo, ETextAlign textAlign, float& logicalLeft, 
766     float& availableLogicalWidth, BidiRun* firstRun, BidiRun* trailingSpaceRun, GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache,
767     WordMeasurements& wordMeasurements)
768 {
769     bool needsWordSpacing = false;
770     float totalLogicalWidth = lineBox->getFlowSpacingLogicalWidth();
771     unsigned expansionOpportunityCount = 0;
772     bool isAfterExpansion = is<RenderRubyBase>(*this) ? downcast<RenderRubyBase>(*this).isAfterExpansion() : true;
773     Vector<unsigned, 16> expansionOpportunities;
774     RenderObject* previousObject = nullptr;
775
776     BidiRun* run = firstRun;
777     for (; run; run = run->next()) {
778         if (!run->box() || run->renderer().isOutOfFlowPositioned() || run->box()->isLineBreak()) {
779             continue; // Positioned objects are only participating to figure out their
780                       // correct static x position.  They have no effect on the width.
781                       // Similarly, line break boxes have no effect on the width.
782         }
783         if (is<RenderText>(run->renderer())) {
784             auto& renderText = downcast<RenderText>(run->renderer());
785             auto& textBox = downcast<InlineTextBox>(*run->box());
786             if (textAlign == JUSTIFY && run != trailingSpaceRun) {
787                 ExpansionBehavior expansionBehavior = expansionBehaviorForInlineTextBox(isAfterExpansion);
788                 applyExpansionBehavior(textBox, expansionBehavior);
789                 unsigned opportunitiesInRun;
790                 std::tie(opportunitiesInRun, isAfterExpansion) = FontCascade::expansionOpportunityCount(renderText.stringView(run->m_start, run->m_stop), run->box()->direction(), expansionBehavior);
791                 expansionOpportunities.append(opportunitiesInRun);
792                 expansionOpportunityCount += opportunitiesInRun;
793             }
794
795             if (int length = renderText.textLength()) {
796                 if (!run->m_start && needsWordSpacing && isSpaceOrNewline(renderText.characterAt(run->m_start)))
797                     totalLogicalWidth += lineStyle(*renderText.parent(), lineInfo).fontCascade().wordSpacing();
798                 needsWordSpacing = !isSpaceOrNewline(renderText.characterAt(run->m_stop - 1)) && run->m_stop == length;
799             }
800
801             setLogicalWidthForTextRun(lineBox, run, renderText, totalLogicalWidth, lineInfo, textBoxDataMap, verticalPositionCache, wordMeasurements);
802         } else {
803             bool encounteredJustifiedRuby = false;
804             if (is<RenderRubyRun>(run->renderer()) && textAlign == JUSTIFY && run != trailingSpaceRun && downcast<RenderRubyRun>(run->renderer()).rubyBase()) {
805                 auto* rubyBase = downcast<RenderRubyRun>(run->renderer()).rubyBase();
806                 if (rubyBase->firstRootBox() && !rubyBase->firstRootBox()->nextRootBox() && run->renderer().style().collapseWhiteSpace()) {
807                     rubyBase->setIsAfterExpansion(isAfterExpansion);
808                     for (auto* leafChild = rubyBase->firstRootBox()->firstLeafChild(); leafChild; leafChild = leafChild->nextLeafChild()) {
809                         if (!is<InlineTextBox>(*leafChild))
810                             continue;
811                         auto& textBox = downcast<InlineTextBox>(*leafChild);
812                         encounteredJustifiedRuby = true;
813                         auto& renderText = downcast<RenderText>(leafChild->renderer());
814                         ExpansionBehavior expansionBehavior = expansionBehaviorForInlineTextBox(isAfterExpansion);
815                         applyExpansionBehavior(textBox, expansionBehavior);
816                         unsigned opportunitiesInRun;
817                         std::tie(opportunitiesInRun, isAfterExpansion) = FontCascade::expansionOpportunityCount(renderText.stringView(), leafChild->direction(), expansionBehavior);
818                         expansionOpportunities.append(opportunitiesInRun);
819                         expansionOpportunityCount += opportunitiesInRun;
820                     }
821                 }
822             }
823
824             if (!encounteredJustifiedRuby)
825                 isAfterExpansion = false;
826
827             if (!is<RenderInline>(run->renderer())) {
828                 auto& renderBox = downcast<RenderBox>(run->renderer());
829                 if (is<RenderRubyRun>(renderBox))
830                     setMarginsForRubyRun(run, downcast<RenderRubyRun>(renderBox), previousObject, lineInfo);
831                 run->box()->setLogicalWidth(logicalWidthForChild(renderBox));
832                 totalLogicalWidth += marginStartForChild(renderBox) + marginEndForChild(renderBox);
833             }
834         }
835
836         totalLogicalWidth += run->box()->logicalWidth();
837         previousObject = &run->renderer();
838     }
839
840     if (isAfterExpansion && !expansionOpportunities.isEmpty()) {
841         bool shouldShareExpansionsWithContainingLine = true;
842         if (is<RenderRubyBase>(*this)) {
843             if (RenderRubyRun* rubyRun = downcast<RenderRubyBase>(*this).rubyRun()) {
844                 if (RenderElement* rubyElement = rubyRun->parent()) {
845                     if (rubyElement->style().display() == INLINE) {
846                         if (RenderBlock* containingBlock = rubyElement->containingBlock()) {
847                             if (containingBlock->style().textAlign() == JUSTIFY)
848                                 shouldShareExpansionsWithContainingLine = false;
849                         }
850                     }
851                 }
852             }
853         }
854         if (shouldShareExpansionsWithContainingLine) {
855             expansionOpportunities.last()--;
856             expansionOpportunityCount--;
857         }
858     }
859
860     updateLogicalWidthForAlignment(textAlign, lineBox, trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth, expansionOpportunityCount);
861
862     computeExpansionForJustifiedText(firstRun, trailingSpaceRun, expansionOpportunities, expansionOpportunityCount, totalLogicalWidth, availableLogicalWidth);
863
864     return run;
865 }
866
867 void RenderBlockFlow::computeBlockDirectionPositionsForLine(RootInlineBox* lineBox, BidiRun* firstRun, GlyphOverflowAndFallbackFontsMap& textBoxDataMap,
868                                                         VerticalPositionCache& verticalPositionCache)
869 {
870     setLogicalHeight(lineBox->alignBoxesInBlockDirection(logicalHeight(), textBoxDataMap, verticalPositionCache));
871
872     // Now make sure we place replaced render objects correctly.
873     for (BidiRun* run = firstRun; run; run = run->next()) {
874         ASSERT(run->box());
875         if (!run->box())
876             continue; // Skip runs with no line boxes.
877
878         InlineBox& box = *run->box();
879
880         // Align positioned boxes with the top of the line box.  This is
881         // a reasonable approximation of an appropriate y position.
882         if (run->renderer().isOutOfFlowPositioned())
883             box.setLogicalTop(logicalHeight());
884
885         // Position is used to properly position both replaced elements and
886         // to update the static normal flow x/y of positioned elements.
887         if (is<RenderText>(run->renderer()))
888             downcast<RenderText>(run->renderer()).positionLineBox(downcast<InlineTextBox>(box));
889         else if (is<RenderBox>(run->renderer()))
890             downcast<RenderBox>(run->renderer()).positionLineBox(downcast<InlineElementBox>(box));
891         else if (is<RenderLineBreak>(run->renderer()))
892             downcast<RenderLineBreak>(run->renderer()).replaceInlineBoxWrapper(downcast<InlineElementBox>(box));
893     }
894     // Positioned objects and zero-length text nodes destroy their boxes in
895     // position(), which unnecessarily dirties the line.
896     lineBox->markDirty(false);
897 }
898
899 static inline bool isCollapsibleSpace(UChar character, const RenderText& renderer)
900 {
901     if (character == ' ' || character == '\t' || character == softHyphen)
902         return true;
903     if (character == '\n')
904         return !renderer.style().preserveNewline();
905     if (character == noBreakSpace)
906         return renderer.style().nbspMode() == SPACE;
907     return false;
908 }
909
910 template <typename CharacterType>
911 static inline int findFirstTrailingSpace(const RenderText& lastText, const CharacterType* characters, int start, int stop)
912 {
913     int firstSpace = stop;
914     while (firstSpace > start) {
915         UChar current = characters[firstSpace - 1];
916         if (!isCollapsibleSpace(current, lastText))
917             break;
918         firstSpace--;
919     }
920
921     return firstSpace;
922 }
923
924 inline BidiRun* RenderBlockFlow::handleTrailingSpaces(BidiRunList<BidiRun>& bidiRuns, BidiContext* currentContext)
925 {
926     if (!bidiRuns.runCount()
927         || !bidiRuns.logicallyLastRun()->renderer().style().breakOnlyAfterWhiteSpace()
928         || !bidiRuns.logicallyLastRun()->renderer().style().autoWrap())
929         return nullptr;
930
931     BidiRun* trailingSpaceRun = bidiRuns.logicallyLastRun();
932     const RenderObject& lastObject = trailingSpaceRun->renderer();
933     if (!is<RenderText>(lastObject))
934         return nullptr;
935
936     const RenderText& lastText = downcast<RenderText>(lastObject);
937     int firstSpace;
938     if (lastText.is8Bit())
939         firstSpace = findFirstTrailingSpace(lastText, lastText.characters8(), trailingSpaceRun->start(), trailingSpaceRun->stop());
940     else
941         firstSpace = findFirstTrailingSpace(lastText, lastText.characters16(), trailingSpaceRun->start(), trailingSpaceRun->stop());
942
943     if (firstSpace == trailingSpaceRun->stop())
944         return nullptr;
945
946     TextDirection direction = style().direction();
947     bool shouldReorder = trailingSpaceRun != (direction == LTR ? bidiRuns.lastRun() : bidiRuns.firstRun());
948     if (firstSpace != trailingSpaceRun->start()) {
949         BidiContext* baseContext = currentContext;
950         while (BidiContext* parent = baseContext->parent())
951             baseContext = parent;
952
953         BidiRun* newTrailingRun = new BidiRun(firstSpace, trailingSpaceRun->m_stop, trailingSpaceRun->renderer(), baseContext, U_OTHER_NEUTRAL);
954         trailingSpaceRun->m_stop = firstSpace;
955         if (direction == LTR)
956             bidiRuns.addRun(newTrailingRun);
957         else
958             bidiRuns.prependRun(newTrailingRun);
959         trailingSpaceRun = newTrailingRun;
960         return trailingSpaceRun;
961     }
962     if (!shouldReorder)
963         return trailingSpaceRun;
964
965     if (direction == LTR) {
966         bidiRuns.moveRunToEnd(trailingSpaceRun);
967         trailingSpaceRun->m_level = 0;
968     } else {
969         bidiRuns.moveRunToBeginning(trailingSpaceRun);
970         trailingSpaceRun->m_level = 1;
971     }
972     return trailingSpaceRun;
973 }
974
975 void RenderBlockFlow::appendFloatingObjectToLastLine(FloatingObject* floatingObject)
976 {
977     ASSERT(!floatingObject->originatingLine());
978     floatingObject->setOriginatingLine(lastRootBox());
979     lastRootBox()->appendFloat(floatingObject->renderer());
980 }
981
982 static inline void setUpResolverToResumeInIsolate(InlineBidiResolver& resolver, RenderObject* root, RenderObject* startObject)
983 {
984     if (root != startObject) {
985         RenderObject* parent = startObject->parent();
986         setUpResolverToResumeInIsolate(resolver, root, parent);
987         notifyObserverEnteredObject(&resolver, startObject);
988     }
989 }
990
991 // FIXME: BidiResolver should have this logic.
992 static inline void constructBidiRunsForSegment(InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfRuns, VisualDirectionOverride override, bool previousLineBrokeCleanly)
993 {
994     // FIXME: We should pass a BidiRunList into createBidiRunsForLine instead
995     // of the resolver owning the runs.
996     ASSERT(&topResolver.runs() == &bidiRuns);
997     ASSERT(topResolver.position() != endOfRuns);
998     RenderObject* currentRoot = topResolver.position().root();
999     topResolver.createBidiRunsForLine(endOfRuns, override, previousLineBrokeCleanly);
1000
1001     while (!topResolver.isolatedRuns().isEmpty()) {
1002         // It does not matter which order we resolve the runs as long as we resolve them all.
1003         BidiRun* isolatedRun = topResolver.isolatedRuns().last();
1004         topResolver.isolatedRuns().removeLast();
1005
1006         RenderObject& startObject = isolatedRun->renderer();
1007
1008         // Only inlines make sense with unicode-bidi: isolate (blocks are already isolated).
1009         // FIXME: Because enterIsolate is not passed a RenderObject, we have to crawl up the
1010         // tree to see which parent inline is the isolate. We could change enterIsolate
1011         // to take a RenderObject and do this logic there, but that would be a layering
1012         // violation for BidiResolver (which knows nothing about RenderObject).
1013         RenderInline* isolatedInline = downcast<RenderInline>(highestContainingIsolateWithinRoot(startObject, currentRoot));
1014         ASSERT(isolatedInline);
1015
1016         InlineBidiResolver isolatedResolver;
1017         EUnicodeBidi unicodeBidi = isolatedInline->style().unicodeBidi();
1018         TextDirection direction;
1019         if (unicodeBidi == Plaintext)
1020             determineDirectionality(direction, InlineIterator(isolatedInline, &isolatedRun->renderer(), 0));
1021         else {
1022             ASSERT(unicodeBidi == Isolate || unicodeBidi == IsolateOverride);
1023             direction = isolatedInline->style().direction();
1024         }
1025         isolatedResolver.setStatus(BidiStatus(direction, isOverride(unicodeBidi)));
1026
1027         setUpResolverToResumeInIsolate(isolatedResolver, isolatedInline, &startObject);
1028
1029         // The starting position is the beginning of the first run within the isolate that was identified
1030         // during the earlier call to createBidiRunsForLine. This can be but is not necessarily the
1031         // first run within the isolate.
1032         InlineIterator iter = InlineIterator(isolatedInline, &startObject, isolatedRun->m_start);
1033         isolatedResolver.setPositionIgnoringNestedIsolates(iter);
1034
1035         // We stop at the next end of line; we may re-enter this isolate in the next call to constructBidiRuns().
1036         // FIXME: What should end and previousLineBrokeCleanly be?
1037         // rniwa says previousLineBrokeCleanly is just a WinIE hack and could always be false here?
1038         isolatedResolver.createBidiRunsForLine(endOfRuns, NoVisualOverride, previousLineBrokeCleanly);
1039         // Note that we do not delete the runs from the resolver.
1040         // We're not guaranteed to get any BidiRuns in the previous step. If we don't, we allow the placeholder
1041         // itself to be turned into an InlineBox. We can't remove it here without potentially losing track of
1042         // the logically last run.
1043         if (isolatedResolver.runs().runCount())
1044             bidiRuns.replaceRunWithRuns(isolatedRun, isolatedResolver.runs());
1045
1046         // If we encountered any nested isolate runs, just move them
1047         // to the top resolver's list for later processing.
1048         if (!isolatedResolver.isolatedRuns().isEmpty()) {
1049             topResolver.isolatedRuns().appendVector(isolatedResolver.isolatedRuns());
1050             isolatedResolver.isolatedRuns().clear();
1051             currentRoot = isolatedInline;
1052         }
1053     }
1054 }
1055
1056 // This function constructs line boxes for all of the text runs in the resolver and computes their position.
1057 RootInlineBox* RenderBlockFlow::createLineBoxesFromBidiRuns(unsigned bidiLevel, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& end, LineInfo& lineInfo, VerticalPositionCache& verticalPositionCache, BidiRun* trailingSpaceRun, WordMeasurements& wordMeasurements)
1058 {
1059     if (!bidiRuns.runCount())
1060         return 0;
1061
1062     // FIXME: Why is this only done when we had runs?
1063     lineInfo.setLastLine(!end.renderer());
1064
1065     RootInlineBox* lineBox = constructLine(bidiRuns, lineInfo);
1066     if (!lineBox)
1067         return 0;
1068
1069     lineBox->setBidiLevel(bidiLevel);
1070     lineBox->setEndsWithBreak(lineInfo.previousLineBrokeCleanly());
1071     
1072     bool isSVGRootInlineBox = is<SVGRootInlineBox>(*lineBox);
1073     
1074     GlyphOverflowAndFallbackFontsMap textBoxDataMap;
1075     
1076     // Now we position all of our text runs horizontally.
1077     if (!isSVGRootInlineBox)
1078         computeInlineDirectionPositionsForLine(lineBox, lineInfo, bidiRuns.firstRun(), trailingSpaceRun, end.atEnd(), textBoxDataMap, verticalPositionCache, wordMeasurements);
1079     
1080     // Now position our text runs vertically.
1081     computeBlockDirectionPositionsForLine(lineBox, bidiRuns.firstRun(), textBoxDataMap, verticalPositionCache);
1082     
1083     // SVG text layout code computes vertical & horizontal positions on its own.
1084     // Note that we still need to execute computeVerticalPositionsForLine() as
1085     // it calls InlineTextBox::positionLineBox(), which tracks whether the box
1086     // contains reversed text or not. If we wouldn't do that editing and thus
1087     // text selection in RTL boxes would not work as expected.
1088     if (isSVGRootInlineBox) {
1089         ASSERT_WITH_SECURITY_IMPLICATION(isSVGText());
1090         downcast<SVGRootInlineBox>(*lineBox).computePerCharacterLayoutInformation();
1091     }
1092     
1093     // Compute our overflow now.
1094     lineBox->computeOverflow(lineBox->lineTop(), lineBox->lineBottom(), textBoxDataMap);
1095     
1096     return lineBox;
1097 }
1098
1099 static void deleteLineRange(LineLayoutState& layoutState, RootInlineBox* startLine, RootInlineBox* stopLine = 0)
1100 {
1101     RootInlineBox* boxToDelete = startLine;
1102     while (boxToDelete && boxToDelete != stopLine) {
1103         layoutState.updateRepaintRangeFromBox(boxToDelete);
1104         // Note: deleteLineRange(firstRootBox()) is not identical to deleteLineBoxTree().
1105         // deleteLineBoxTree uses nextLineBox() instead of nextRootBox() when traversing.
1106         RootInlineBox* next = boxToDelete->nextRootBox();
1107         boxToDelete->deleteLine();
1108         boxToDelete = next;
1109     }
1110 }
1111
1112 void RenderBlockFlow::layoutRunsAndFloats(LineLayoutState& layoutState, bool hasInlineChild)
1113 {
1114     // We want to skip ahead to the first dirty line
1115     InlineBidiResolver resolver;
1116     RootInlineBox* startLine = determineStartPosition(layoutState, resolver);
1117
1118     unsigned consecutiveHyphenatedLines = 0;
1119     if (startLine) {
1120         for (RootInlineBox* line = startLine->prevRootBox(); line && line->isHyphenated(); line = line->prevRootBox())
1121             consecutiveHyphenatedLines++;
1122     }
1123
1124     // FIXME: This would make more sense outside of this function, but since
1125     // determineStartPosition can change the fullLayout flag we have to do this here. Failure to call
1126     // determineStartPosition first will break fast/repaint/line-flow-with-floats-9.html.
1127     if (layoutState.isFullLayout() && hasInlineChild && !selfNeedsLayout()) {
1128         setNeedsLayout(MarkOnlyThis); // Mark as needing a full layout to force us to repaint.
1129         if (!view().doingFullRepaint() && hasLayer()) {
1130             // Because we waited until we were already inside layout to discover
1131             // that the block really needed a full layout, we missed our chance to repaint the layer
1132             // before layout started.  Luckily the layer has cached the repaint rect for its original
1133             // position and size, and so we can use that to make a repaint happen now.
1134             repaintUsingContainer(containerForRepaint(), layer()->repaintRect());
1135         }
1136     }
1137
1138     if (containsFloats())
1139         layoutState.setLastFloat(m_floatingObjects->set().last().get());
1140
1141     // We also find the first clean line and extract these lines.  We will add them back
1142     // if we determine that we're able to synchronize after handling all our dirty lines.
1143     InlineIterator cleanLineStart;
1144     BidiStatus cleanLineBidiStatus;
1145     if (!layoutState.isFullLayout() && startLine)
1146         determineEndPosition(layoutState, startLine, cleanLineStart, cleanLineBidiStatus);
1147
1148     if (startLine) {
1149         if (!layoutState.usesRepaintBounds())
1150             layoutState.setRepaintRange(logicalHeight());
1151         deleteLineRange(layoutState, startLine);
1152     }
1153
1154     if (!layoutState.isFullLayout() && lastRootBox() && lastRootBox()->endsWithBreak()) {
1155         // If the last line before the start line ends with a line break that clear floats,
1156         // adjust the height accordingly.
1157         // A line break can be either the first or the last object on a line, depending on its direction.
1158         if (InlineBox* lastLeafChild = lastRootBox()->lastLeafChild()) {
1159             RenderObject* lastObject = &lastLeafChild->renderer();
1160             if (!lastObject->isBR())
1161                 lastObject = &lastRootBox()->firstLeafChild()->renderer();
1162             if (lastObject->isBR()) {
1163                 EClear clear = lastObject->style().clear();
1164                 if (clear != CNONE)
1165                     clearFloats(clear);
1166             }
1167         }
1168     }
1169
1170     layoutRunsAndFloatsInRange(layoutState, resolver, cleanLineStart, cleanLineBidiStatus, consecutiveHyphenatedLines);
1171     linkToEndLineIfNeeded(layoutState);
1172     repaintDirtyFloats(layoutState.floats());
1173 }
1174
1175 RenderTextInfo::RenderTextInfo()
1176     : m_text(0)
1177     , m_font(0)
1178 {
1179 }
1180
1181 RenderTextInfo::~RenderTextInfo()
1182 {
1183 }
1184
1185 // Before restarting the layout loop with a new logicalHeight, remove all floats that were added and reset the resolver.
1186 inline const InlineIterator& RenderBlockFlow::restartLayoutRunsAndFloatsInRange(LayoutUnit oldLogicalHeight, LayoutUnit newLogicalHeight,  FloatingObject* lastFloatFromPreviousLine, InlineBidiResolver& resolver,  const InlineIterator& oldEnd)
1187 {
1188     removeFloatingObjectsBelow(lastFloatFromPreviousLine, oldLogicalHeight);
1189     setLogicalHeight(newLogicalHeight);
1190     resolver.setPositionIgnoringNestedIsolates(oldEnd);
1191     return oldEnd;
1192 }
1193
1194 void RenderBlockFlow::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, InlineBidiResolver& resolver, const InlineIterator& cleanLineStart, const BidiStatus& cleanLineBidiStatus, unsigned consecutiveHyphenatedLines)
1195 {
1196     const RenderStyle& styleToUse = style();
1197     bool paginated = view().layoutState() && view().layoutState()->isPaginated();
1198     LineMidpointState& lineMidpointState = resolver.midpointState();
1199     InlineIterator end = resolver.position();
1200     bool checkForEndLineMatch = layoutState.endLine();
1201     RenderTextInfo renderTextInfo;
1202     VerticalPositionCache verticalPositionCache;
1203
1204     LineBreaker lineBreaker(*this);
1205
1206     while (!end.atEnd()) {
1207         // FIXME: Is this check necessary before the first iteration or can it be moved to the end?
1208         if (checkForEndLineMatch) {
1209             layoutState.setEndLineMatched(matchedEndLine(layoutState, resolver, cleanLineStart, cleanLineBidiStatus));
1210             if (layoutState.endLineMatched()) {
1211                 resolver.setPosition(InlineIterator(resolver.position().root(), 0, 0), 0);
1212                 break;
1213             }
1214         }
1215
1216         lineMidpointState.reset();
1217
1218         layoutState.lineInfo().setEmpty(true);
1219         layoutState.lineInfo().resetRunsFromLeadingWhitespace();
1220
1221         const InlineIterator oldEnd = end;
1222         bool isNewUBAParagraph = layoutState.lineInfo().previousLineBrokeCleanly();
1223         FloatingObject* lastFloatFromPreviousLine = (containsFloats()) ? m_floatingObjects->set().last().get() : 0;
1224
1225         WordMeasurements wordMeasurements;
1226         end = lineBreaker.nextLineBreak(resolver, layoutState.lineInfo(), renderTextInfo, lastFloatFromPreviousLine, consecutiveHyphenatedLines, wordMeasurements);
1227         cachePriorCharactersIfNeeded(renderTextInfo.m_lineBreakIterator);
1228         renderTextInfo.m_lineBreakIterator.resetPriorContext();
1229         if (resolver.position().atEnd()) {
1230             // FIXME: We shouldn't be creating any runs in nextLineBreak to begin with!
1231             // Once BidiRunList is separated from BidiResolver this will not be needed.
1232             resolver.runs().deleteRuns();
1233             resolver.markCurrentRunEmpty(); // FIXME: This can probably be replaced by an ASSERT (or just removed).
1234             layoutState.setCheckForFloatsFromLastLine(true);
1235             resolver.setPosition(InlineIterator(resolver.position().root(), 0, 0), 0);
1236             break;
1237         }
1238
1239         ASSERT(end != resolver.position());
1240
1241         // This is a short-cut for empty lines.
1242         if (layoutState.lineInfo().isEmpty()) {
1243             if (lastRootBox())
1244                 lastRootBox()->setLineBreakInfo(end.renderer(), end.offset(), resolver.status());
1245         } else {
1246             VisualDirectionOverride override = (styleToUse.rtlOrdering() == VisualOrder ? (styleToUse.direction() == LTR ? VisualLeftToRightOverride : VisualRightToLeftOverride) : NoVisualOverride);
1247
1248             if (isNewUBAParagraph && styleToUse.unicodeBidi() == Plaintext && !resolver.context()->parent()) {
1249                 TextDirection direction = styleToUse.direction();
1250                 determineDirectionality(direction, resolver.position());
1251                 resolver.setStatus(BidiStatus(direction, isOverride(styleToUse.unicodeBidi())));
1252             }
1253             // FIXME: This ownership is reversed. We should own the BidiRunList and pass it to createBidiRunsForLine.
1254             BidiRunList<BidiRun>& bidiRuns = resolver.runs();
1255             constructBidiRunsForSegment(resolver, bidiRuns, end, override, layoutState.lineInfo().previousLineBrokeCleanly());
1256             ASSERT(resolver.position() == end);
1257
1258             BidiRun* trailingSpaceRun = !layoutState.lineInfo().previousLineBrokeCleanly() ? handleTrailingSpaces(bidiRuns, resolver.context()) : 0;
1259
1260             if (bidiRuns.runCount() && lineBreaker.lineWasHyphenated()) {
1261                 bidiRuns.logicallyLastRun()->m_hasHyphen = true;
1262                 consecutiveHyphenatedLines++;
1263             } else
1264                 consecutiveHyphenatedLines = 0;
1265
1266             // Now that the runs have been ordered, we create the line boxes.
1267             // At the same time we figure out where border/padding/margin should be applied for
1268             // inline flow boxes.
1269
1270             LayoutUnit oldLogicalHeight = logicalHeight();
1271             RootInlineBox* lineBox = createLineBoxesFromBidiRuns(resolver.status().context->level(), bidiRuns, end, layoutState.lineInfo(), verticalPositionCache, trailingSpaceRun, wordMeasurements);
1272
1273             bidiRuns.deleteRuns();
1274             resolver.markCurrentRunEmpty(); // FIXME: This can probably be replaced by an ASSERT (or just removed).
1275
1276             if (lineBox) {
1277                 lineBox->setLineBreakInfo(end.renderer(), end.offset(), resolver.status());
1278                 if (layoutState.usesRepaintBounds())
1279                     layoutState.updateRepaintRangeFromBox(lineBox);
1280
1281                 if (paginated) {
1282                     LayoutUnit adjustment = 0;
1283                     bool overflowsRegion;
1284                     adjustLinePositionForPagination(lineBox, adjustment, overflowsRegion, layoutState.flowThread());
1285                     if (adjustment) {
1286                         LayoutUnit oldLineWidth = availableLogicalWidthForLine(oldLogicalHeight, layoutState.lineInfo().isFirstLine());
1287                         lineBox->adjustBlockDirectionPosition(adjustment);
1288                         if (layoutState.usesRepaintBounds())
1289                             layoutState.updateRepaintRangeFromBox(lineBox);
1290
1291                         if (availableLogicalWidthForLine(oldLogicalHeight + adjustment, layoutState.lineInfo().isFirstLine()) != oldLineWidth) {
1292                             // We have to delete this line, remove all floats that got added, and let line layout re-run.
1293                             lineBox->deleteLine();
1294                             end = restartLayoutRunsAndFloatsInRange(oldLogicalHeight, oldLogicalHeight + adjustment, lastFloatFromPreviousLine, resolver, oldEnd);
1295                             continue;
1296                         }
1297
1298                         setLogicalHeight(lineBox->lineBottomWithLeading());
1299                     }
1300                     
1301                     if (RenderFlowThread* flowThread = flowThreadContainingBlock()) {
1302                         if (flowThread->isRenderNamedFlowThread() && overflowsRegion && hasNextPage(lineBox->lineTop())) {
1303                             // Limit the height of this block to the end of the current region because
1304                             // it is also fragmented into the next region.
1305                             LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(logicalTop(), ExcludePageBoundary);
1306                             if (logicalHeight() > remainingLogicalHeight)
1307                                 setLogicalHeight(remainingLogicalHeight);
1308                         }
1309                     }
1310
1311                     if (layoutState.flowThread())
1312                         updateRegionForLine(lineBox);
1313                 }
1314             }
1315         }
1316
1317         for (size_t i = 0; i < lineBreaker.positionedObjects().size(); ++i)
1318             setStaticPositions(*this, *lineBreaker.positionedObjects()[i]);
1319
1320         if (!layoutState.lineInfo().isEmpty()) {
1321             layoutState.lineInfo().setFirstLine(false);
1322             clearFloats(lineBreaker.clear());
1323         }
1324
1325         if (m_floatingObjects && lastRootBox()) {
1326             const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1327             auto it = floatingObjectSet.begin();
1328             auto end = floatingObjectSet.end();
1329             if (layoutState.lastFloat()) {
1330                 auto lastFloatIterator = floatingObjectSet.find<FloatingObject&, FloatingObjectHashTranslator>(*layoutState.lastFloat());
1331                 ASSERT(lastFloatIterator != end);
1332                 ++lastFloatIterator;
1333                 it = lastFloatIterator;
1334             }
1335             for (; it != end; ++it) {
1336                 FloatingObject* f = it->get();
1337                 appendFloatingObjectToLastLine(f);
1338                 ASSERT(&f->renderer() == &layoutState.floats()[layoutState.floatIndex()].object);
1339                 // If a float's geometry has changed, give up on syncing with clean lines.
1340                 if (layoutState.floats()[layoutState.floatIndex()].rect != f->frameRect())
1341                     checkForEndLineMatch = false;
1342                 layoutState.setFloatIndex(layoutState.floatIndex() + 1);
1343             }
1344             layoutState.setLastFloat(!floatingObjectSet.isEmpty() ? floatingObjectSet.last().get() : nullptr);
1345         }
1346
1347         lineMidpointState.reset();
1348         resolver.setPosition(end, numberOfIsolateAncestors(end));
1349     }
1350
1351     // In case we already adjusted the line positions during this layout to avoid widows
1352     // then we need to ignore the possibility of having a new widows situation.
1353     // Otherwise, we risk leaving empty containers which is against the block fragmentation principles.
1354     if (paginated && !style().hasAutoWidows() && !didBreakAtLineToAvoidWidow()) {
1355         // Check the line boxes to make sure we didn't create unacceptable widows.
1356         // However, we'll prioritize orphans - so nothing we do here should create
1357         // a new orphan.
1358
1359         RootInlineBox* lineBox = lastRootBox();
1360
1361         // Count from the end of the block backwards, to see how many hanging
1362         // lines we have.
1363         RootInlineBox* firstLineInBlock = firstRootBox();
1364         int numLinesHanging = 1;
1365         while (lineBox && lineBox != firstLineInBlock && !lineBox->isFirstAfterPageBreak()) {
1366             ++numLinesHanging;
1367             lineBox = lineBox->prevRootBox();
1368         }
1369
1370         // If there were no breaks in the block, we didn't create any widows.
1371         if (!lineBox || !lineBox->isFirstAfterPageBreak() || lineBox == firstLineInBlock)
1372             return;
1373
1374         if (numLinesHanging < style().widows()) {
1375             // We have detected a widow. Now we need to work out how many
1376             // lines there are on the previous page, and how many we need
1377             // to steal.
1378             int numLinesNeeded = style().widows() - numLinesHanging;
1379             RootInlineBox* currentFirstLineOfNewPage = lineBox;
1380
1381             // Count the number of lines in the previous page.
1382             lineBox = lineBox->prevRootBox();
1383             int numLinesInPreviousPage = 1;
1384             while (lineBox && lineBox != firstLineInBlock && !lineBox->isFirstAfterPageBreak()) {
1385                 ++numLinesInPreviousPage;
1386                 lineBox = lineBox->prevRootBox();
1387             }
1388
1389             // If there was an explicit value for orphans, respect that. If not, we still
1390             // shouldn't create a situation where we make an orphan bigger than the initial value.
1391             // This means that setting widows implies we also care about orphans, but given
1392             // the specification says the initial orphan value is non-zero, this is ok. The
1393             // author is always free to set orphans explicitly as well.
1394             int orphans = style().hasAutoOrphans() ? style().initialOrphans() : style().orphans();
1395             int numLinesAvailable = numLinesInPreviousPage - orphans;
1396             if (numLinesAvailable <= 0)
1397                 return;
1398
1399             int numLinesToTake = std::min(numLinesAvailable, numLinesNeeded);
1400             // Wind back from our first widowed line.
1401             lineBox = currentFirstLineOfNewPage;
1402             for (int i = 0; i < numLinesToTake; ++i)
1403                 lineBox = lineBox->prevRootBox();
1404
1405             // We now want to break at this line. Remember for next layout and trigger relayout.
1406             setBreakAtLineToAvoidWidow(lineCount(lineBox));
1407             markLinesDirtyInBlockRange(lastRootBox()->lineBottomWithLeading(), lineBox->lineBottomWithLeading(), lineBox);
1408         }
1409     }
1410
1411     clearDidBreakAtLineToAvoidWidow();
1412 }
1413
1414 void RenderBlockFlow::linkToEndLineIfNeeded(LineLayoutState& layoutState)
1415 {
1416     if (layoutState.endLine()) {
1417         if (layoutState.endLineMatched()) {
1418             bool paginated = view().layoutState() && view().layoutState()->isPaginated();
1419             // Attach all the remaining lines, and then adjust their y-positions as needed.
1420             LayoutUnit delta = logicalHeight() - layoutState.endLineLogicalTop();
1421             for (RootInlineBox* line = layoutState.endLine(); line; line = line->nextRootBox()) {
1422                 line->attachLine();
1423                 if (paginated) {
1424                     delta -= line->paginationStrut();
1425                     bool overflowsRegion;
1426                     adjustLinePositionForPagination(line, delta, overflowsRegion, layoutState.flowThread());
1427                 }
1428                 if (delta) {
1429                     layoutState.updateRepaintRangeFromBox(line, delta);
1430                     line->adjustBlockDirectionPosition(delta);
1431                 }
1432                 if (layoutState.flowThread())
1433                     updateRegionForLine(line);
1434                 if (Vector<RenderBox*>* cleanLineFloats = line->floatsPtr()) {
1435                     for (auto it = cleanLineFloats->begin(), end = cleanLineFloats->end(); it != end; ++it) {
1436                         RenderBox* floatingBox = *it;
1437                         FloatingObject* floatingObject = insertFloatingObject(*floatingBox);
1438                         ASSERT(!floatingObject->originatingLine());
1439                         floatingObject->setOriginatingLine(line);
1440                         setLogicalHeight(logicalTopForChild(*floatingBox) - marginBeforeForChild(*floatingBox) + delta);
1441                         positionNewFloats();
1442                     }
1443                 }
1444             }
1445             setLogicalHeight(lastRootBox()->lineBottomWithLeading());
1446         } else {
1447             // Delete all the remaining lines.
1448             deleteLineRange(layoutState, layoutState.endLine());
1449         }
1450     }
1451     
1452     if (m_floatingObjects && (layoutState.checkForFloatsFromLastLine() || positionNewFloats()) && lastRootBox()) {
1453         // In case we have a float on the last line, it might not be positioned up to now.
1454         // This has to be done before adding in the bottom border/padding, or the float will
1455         // include the padding incorrectly. -dwh
1456         if (layoutState.checkForFloatsFromLastLine()) {
1457             LayoutUnit bottomVisualOverflow = lastRootBox()->logicalBottomVisualOverflow();
1458             LayoutUnit bottomLayoutOverflow = lastRootBox()->logicalBottomLayoutOverflow();
1459             auto newLineBox = std::make_unique<TrailingFloatsRootInlineBox>(*this);
1460             auto trailingFloatsLineBox = newLineBox.get();
1461             m_lineBoxes.appendLineBox(WTF::move(newLineBox));
1462             trailingFloatsLineBox->setConstructed();
1463             GlyphOverflowAndFallbackFontsMap textBoxDataMap;
1464             VerticalPositionCache verticalPositionCache;
1465             LayoutUnit blockLogicalHeight = logicalHeight();
1466             trailingFloatsLineBox->alignBoxesInBlockDirection(blockLogicalHeight, textBoxDataMap, verticalPositionCache);
1467             trailingFloatsLineBox->setLineTopBottomPositions(blockLogicalHeight, blockLogicalHeight, blockLogicalHeight, blockLogicalHeight);
1468             trailingFloatsLineBox->setPaginatedLineWidth(availableLogicalWidthForContent(blockLogicalHeight));
1469             LayoutRect logicalLayoutOverflow(0, blockLogicalHeight, 1, bottomLayoutOverflow - blockLogicalHeight);
1470             LayoutRect logicalVisualOverflow(0, blockLogicalHeight, 1, bottomVisualOverflow - blockLogicalHeight);
1471             trailingFloatsLineBox->setOverflowFromLogicalRects(logicalLayoutOverflow, logicalVisualOverflow, trailingFloatsLineBox->lineTop(), trailingFloatsLineBox->lineBottom());
1472             if (layoutState.flowThread())
1473                 updateRegionForLine(trailingFloatsLineBox);
1474         }
1475
1476         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1477         auto it = floatingObjectSet.begin();
1478         auto end = floatingObjectSet.end();
1479         if (layoutState.lastFloat()) {
1480             auto lastFloatIterator = floatingObjectSet.find<FloatingObject&, FloatingObjectHashTranslator>(*layoutState.lastFloat());
1481             ASSERT(lastFloatIterator != end);
1482             ++lastFloatIterator;
1483             it = lastFloatIterator;
1484         }
1485         for (; it != end; ++it)
1486             appendFloatingObjectToLastLine(it->get());
1487         layoutState.setLastFloat(!floatingObjectSet.isEmpty() ? floatingObjectSet.last().get() : nullptr);
1488     }
1489 }
1490
1491 void RenderBlockFlow::repaintDirtyFloats(Vector<FloatWithRect>& floats)
1492 {
1493     size_t floatCount = floats.size();
1494     // Floats that did not have layout did not repaint when we laid them out. They would have
1495     // painted by now if they had moved, but if they stayed at (0, 0), they still need to be
1496     // painted.
1497     for (size_t i = 0; i < floatCount; ++i) {
1498         if (!floats[i].everHadLayout) {
1499             RenderBox& box = floats[i].object;
1500             if (!box.x() && !box.y() && box.checkForRepaintDuringLayout())
1501                 box.repaint();
1502         }
1503     }
1504 }
1505
1506 void RenderBlockFlow::layoutLineBoxes(bool relayoutChildren, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom)
1507 {
1508     ASSERT(!m_simpleLineLayout);
1509
1510     setLogicalHeight(borderAndPaddingBefore());
1511     
1512     // Lay out our hypothetical grid line as though it occurs at the top of the block.
1513     if (view().layoutState() && view().layoutState()->lineGrid() == this)
1514         layoutLineGridBox();
1515
1516     RenderFlowThread* flowThread = flowThreadContainingBlock();
1517     bool clearLinesForPagination = firstRootBox() && flowThread && !flowThread->hasRegions();
1518
1519     // Figure out if we should clear out our line boxes.
1520     // FIXME: Handle resize eventually!
1521     bool isFullLayout = !firstRootBox() || selfNeedsLayout() || relayoutChildren || clearLinesForPagination;
1522     LineLayoutState layoutState(isFullLayout, repaintLogicalTop, repaintLogicalBottom, flowThread);
1523
1524     if (isFullLayout)
1525         lineBoxes().deleteLineBoxes();
1526
1527     // Text truncation kicks in in two cases:
1528     //     1) If your overflow isn't visible and your text-overflow-mode isn't clip.
1529     //     2) If you're an anonymous block with a block parent that satisfies #1.
1530     // FIXME: CSS3 says that descendants that are clipped must also know how to truncate.  This is insanely
1531     // difficult to figure out in general (especially in the middle of doing layout), so we only handle the
1532     // simple case of an anonymous block truncating when it's parent is clipped.
1533     bool hasTextOverflow = (style().textOverflow() && hasOverflowClip())
1534         || (isAnonymousBlock() && parent() && parent()->isRenderBlock() && parent()->style().textOverflow() && parent()->hasOverflowClip());
1535
1536     // Walk all the lines and delete our ellipsis line boxes if they exist.
1537     if (hasTextOverflow)
1538          deleteEllipsisLineBoxes();
1539
1540     if (firstChild()) {
1541         // In full layout mode, clear the line boxes of children upfront. Otherwise,
1542         // siblings can run into stale root lineboxes during layout. Then layout
1543         // the replaced elements later. In partial layout mode, line boxes are not
1544         // deleted and only dirtied. In that case, we can layout the replaced
1545         // elements at the same time.
1546         bool hasInlineChild = false;
1547         Vector<RenderBox*> replacedChildren;
1548         for (InlineWalker walker(*this); !walker.atEnd(); walker.advance()) {
1549             RenderObject& o = *walker.current();
1550
1551             if (!hasInlineChild && o.isInline())
1552                 hasInlineChild = true;
1553
1554             if (o.isReplaced() || o.isFloating() || o.isOutOfFlowPositioned()) {
1555                 RenderBox& box = downcast<RenderBox>(o);
1556
1557                 if (relayoutChildren || box.hasRelativeDimensions())
1558                     box.setChildNeedsLayout(MarkOnlyThis);
1559
1560                 // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
1561                 if (relayoutChildren && box.needsPreferredWidthsRecalculation())
1562                     box.setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
1563
1564                 if (box.isOutOfFlowPositioned())
1565                     box.containingBlock()->insertPositionedObject(box);
1566                 else if (box.isFloating())
1567                     layoutState.floats().append(FloatWithRect(box));
1568                 else if (isFullLayout || box.needsLayout()) {
1569                     // Replaced element.
1570                     box.dirtyLineBoxes(isFullLayout);
1571                     if (!o.isAnonymousInlineBlock()) {
1572                         if (isFullLayout)
1573                             replacedChildren.append(&box);
1574                         else
1575                             box.layoutIfNeeded();
1576                     }
1577                 }
1578             } else if (o.isTextOrLineBreak() || (is<RenderInline>(o) && !walker.atEndOfInline())) {
1579                 if (is<RenderInline>(o))
1580                     downcast<RenderInline>(o).updateAlwaysCreateLineBoxes(layoutState.isFullLayout());
1581                 if (layoutState.isFullLayout() || o.selfNeedsLayout())
1582                     dirtyLineBoxesForRenderer(o, layoutState.isFullLayout());
1583                 o.clearNeedsLayout();
1584             }
1585         }
1586
1587         for (size_t i = 0; i < replacedChildren.size(); i++)
1588              replacedChildren[i]->layoutIfNeeded();
1589
1590         layoutRunsAndFloats(layoutState, hasInlineChild);
1591     }
1592
1593     // Expand the last line to accommodate Ruby and emphasis marks.
1594     int lastLineAnnotationsAdjustment = 0;
1595     if (lastRootBox()) {
1596         LayoutUnit lowestAllowedPosition = std::max(lastRootBox()->lineBottom(), logicalHeight() + paddingAfter());
1597         if (!style().isFlippedLinesWritingMode())
1598             lastLineAnnotationsAdjustment = lastRootBox()->computeUnderAnnotationAdjustment(lowestAllowedPosition);
1599         else
1600             lastLineAnnotationsAdjustment = lastRootBox()->computeOverAnnotationAdjustment(lowestAllowedPosition);
1601     }
1602
1603     // Now add in the bottom border/padding.
1604     setLogicalHeight(logicalHeight() + lastLineAnnotationsAdjustment + borderAndPaddingAfter() + scrollbarLogicalHeight());
1605
1606     if (!firstRootBox() && hasLineIfEmpty())
1607         setLogicalHeight(logicalHeight() + lineHeight(true, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes));
1608
1609     // See if we have any lines that spill out of our block.  If we do, then we will possibly need to
1610     // truncate text.
1611     if (hasTextOverflow)
1612         checkLinesForTextOverflow();
1613 }
1614
1615 void RenderBlockFlow::checkFloatsInCleanLine(RootInlineBox* line, Vector<FloatWithRect>& floats, size_t& floatIndex, bool& encounteredNewFloat, bool& dirtiedByFloat)
1616 {
1617     Vector<RenderBox*>* cleanLineFloats = line->floatsPtr();
1618     if (!cleanLineFloats)
1619         return;
1620     
1621     if (!floats.size()) {
1622         encounteredNewFloat = true;
1623         return;
1624     }
1625
1626     for (auto it = cleanLineFloats->begin(), end = cleanLineFloats->end(); it != end; ++it) {
1627         RenderBox* floatingBox = *it;
1628         floatingBox->layoutIfNeeded();
1629         LayoutSize newSize(floatingBox->width() + floatingBox->horizontalMarginExtent(), floatingBox->height() + floatingBox->verticalMarginExtent());
1630         ASSERT_WITH_SECURITY_IMPLICATION(floatIndex < floats.size());
1631         if (&floats[floatIndex].object != floatingBox) {
1632             encounteredNewFloat = true;
1633             return;
1634         }
1635     
1636         // We have to reset the cap-height alignment done by the first-letter floats when initial-letter is set, so just always treat first-letter floats
1637         // as dirty.
1638         if (floats[floatIndex].rect.size() != newSize || (floatingBox->style().styleType() == FIRST_LETTER && floatingBox->style().initialLetterDrop() > 0)) {
1639             LayoutUnit floatTop = isHorizontalWritingMode() ? floats[floatIndex].rect.y() : floats[floatIndex].rect.x();
1640             LayoutUnit floatHeight = isHorizontalWritingMode() ? std::max(floats[floatIndex].rect.height(), newSize.height()) : std::max(floats[floatIndex].rect.width(), newSize.width());
1641             floatHeight = std::min(floatHeight, LayoutUnit::max() - floatTop);
1642             line->markDirty();
1643             markLinesDirtyInBlockRange(line->lineBottomWithLeading(), floatTop + floatHeight, line);
1644             floats[floatIndex].rect.setSize(newSize);
1645             dirtiedByFloat = true;
1646         }
1647         floatIndex++;
1648     }
1649 }
1650
1651 RootInlineBox* RenderBlockFlow::determineStartPosition(LineLayoutState& layoutState, InlineBidiResolver& resolver)
1652 {
1653     RootInlineBox* curr = 0;
1654     RootInlineBox* last = 0;
1655
1656     // FIXME: This entire float-checking block needs to be broken into a new function.
1657     bool dirtiedByFloat = false;
1658     if (!layoutState.isFullLayout()) {
1659         // Paginate all of the clean lines.
1660         bool paginated = view().layoutState() && view().layoutState()->isPaginated();
1661         LayoutUnit paginationDelta = 0;
1662         size_t floatIndex = 0;
1663         for (curr = firstRootBox(); curr && !curr->isDirty(); curr = curr->nextRootBox()) {
1664             if (paginated) {
1665                 if (lineWidthForPaginatedLineChanged(curr, 0, layoutState.flowThread())) {
1666                     curr->markDirty();
1667                     break;
1668                 }
1669                 paginationDelta -= curr->paginationStrut();
1670                 bool overflowsRegion;
1671                 adjustLinePositionForPagination(curr, paginationDelta, overflowsRegion, layoutState.flowThread());
1672                 if (paginationDelta) {
1673                     if (containsFloats() || !layoutState.floats().isEmpty()) {
1674                         // FIXME: Do better eventually.  For now if we ever shift because of pagination and floats are present just go to a full layout.
1675                         layoutState.markForFullLayout();
1676                         break;
1677                     }
1678
1679                     layoutState.updateRepaintRangeFromBox(curr, paginationDelta);
1680                     curr->adjustBlockDirectionPosition(paginationDelta);
1681                 }
1682                 if (layoutState.flowThread())
1683                     updateRegionForLine(curr);
1684             }
1685
1686             // If a new float has been inserted before this line or before its last known float, just do a full layout.
1687             bool encounteredNewFloat = false;
1688             checkFloatsInCleanLine(curr, layoutState.floats(), floatIndex, encounteredNewFloat, dirtiedByFloat);
1689             if (encounteredNewFloat)
1690                 layoutState.markForFullLayout();
1691
1692             if (dirtiedByFloat || layoutState.isFullLayout())
1693                 break;
1694         }
1695         // Check if a new float has been inserted after the last known float.
1696         if (!curr && floatIndex < layoutState.floats().size())
1697             layoutState.markForFullLayout();
1698     }
1699
1700     if (layoutState.isFullLayout()) {
1701         m_lineBoxes.deleteLineBoxTree();
1702         curr = 0;
1703
1704         ASSERT(!firstRootBox() && !lastRootBox());
1705     } else {
1706         if (curr) {
1707             // We have a dirty line.
1708             if (RootInlineBox* prevRootBox = curr->prevRootBox()) {
1709                 // We have a previous line.
1710                 if (!dirtiedByFloat && (!prevRootBox->endsWithBreak() || !prevRootBox->lineBreakObj() || (is<RenderText>(*prevRootBox->lineBreakObj()) && prevRootBox->lineBreakPos() >= downcast<RenderText>(*prevRootBox->lineBreakObj()).textLength()))) {
1711                     // The previous line didn't break cleanly or broke at a newline
1712                     // that has been deleted, so treat it as dirty too.
1713                     curr = prevRootBox;
1714                 }
1715             }
1716         }
1717         // If we have no dirty lines, then last is just the last root box.
1718         last = curr ? curr->prevRootBox() : lastRootBox();
1719     }
1720
1721     unsigned numCleanFloats = 0;
1722     if (!layoutState.floats().isEmpty()) {
1723         LayoutUnit savedLogicalHeight = logicalHeight();
1724         // Restore floats from clean lines.
1725         RootInlineBox* line = firstRootBox();
1726         while (line != curr) {
1727             if (Vector<RenderBox*>* cleanLineFloats = line->floatsPtr()) {
1728                 for (auto it = cleanLineFloats->begin(), end = cleanLineFloats->end(); it != end; ++it) {
1729                     RenderBox* floatingBox = *it;
1730                     FloatingObject* floatingObject = insertFloatingObject(*floatingBox);
1731                     ASSERT(!floatingObject->originatingLine());
1732                     floatingObject->setOriginatingLine(line);
1733                     setLogicalHeight(logicalTopForChild(*floatingBox) - marginBeforeForChild(*floatingBox));
1734                     positionNewFloats();
1735                     ASSERT(&layoutState.floats()[numCleanFloats].object == floatingBox);
1736                     numCleanFloats++;
1737                 }
1738             }
1739             line = line->nextRootBox();
1740         }
1741         setLogicalHeight(savedLogicalHeight);
1742     }
1743     layoutState.setFloatIndex(numCleanFloats);
1744
1745     layoutState.lineInfo().setFirstLine(!last);
1746     layoutState.lineInfo().setPreviousLineBrokeCleanly(!last || last->endsWithBreak());
1747
1748     if (last) {
1749         setLogicalHeight(last->lineBottomWithLeading());
1750         InlineIterator iter = InlineIterator(this, last->lineBreakObj(), last->lineBreakPos());
1751         resolver.setPosition(iter, numberOfIsolateAncestors(iter));
1752         resolver.setStatus(last->lineBreakBidiStatus());
1753     } else {
1754         TextDirection direction = style().direction();
1755         if (style().unicodeBidi() == Plaintext)
1756             determineDirectionality(direction, InlineIterator(this, bidiFirstSkippingEmptyInlines(*this), 0));
1757         resolver.setStatus(BidiStatus(direction, isOverride(style().unicodeBidi())));
1758         InlineIterator iter = InlineIterator(this, bidiFirstSkippingEmptyInlines(*this, &resolver), 0);
1759         resolver.setPosition(iter, numberOfIsolateAncestors(iter));
1760     }
1761     return curr;
1762 }
1763
1764 void RenderBlockFlow::determineEndPosition(LineLayoutState& layoutState, RootInlineBox* startLine, InlineIterator& cleanLineStart, BidiStatus& cleanLineBidiStatus)
1765 {
1766     ASSERT(!layoutState.endLine());
1767     size_t floatIndex = layoutState.floatIndex();
1768     RootInlineBox* last = 0;
1769     for (RootInlineBox* curr = startLine->nextRootBox(); curr; curr = curr->nextRootBox()) {
1770         if (!curr->isDirty()) {
1771             bool encounteredNewFloat = false;
1772             bool dirtiedByFloat = false;
1773             checkFloatsInCleanLine(curr, layoutState.floats(), floatIndex, encounteredNewFloat, dirtiedByFloat);
1774             if (encounteredNewFloat)
1775                 return;
1776         }
1777         if (curr->isDirty())
1778             last = 0;
1779         else if (!last)
1780             last = curr;
1781     }
1782
1783     if (!last)
1784         return;
1785
1786     // At this point, |last| is the first line in a run of clean lines that ends with the last line
1787     // in the block.
1788
1789     RootInlineBox* prev = last->prevRootBox();
1790     cleanLineStart = InlineIterator(this, prev->lineBreakObj(), prev->lineBreakPos());
1791     cleanLineBidiStatus = prev->lineBreakBidiStatus();
1792     layoutState.setEndLineLogicalTop(prev->lineBottomWithLeading());
1793
1794     for (RootInlineBox* line = last; line; line = line->nextRootBox())
1795         line->extractLine(); // Disconnect all line boxes from their render objects while preserving
1796                              // their connections to one another.
1797
1798     layoutState.setEndLine(last);
1799 }
1800
1801 bool RenderBlockFlow::checkPaginationAndFloatsAtEndLine(LineLayoutState& layoutState)
1802 {
1803     LayoutUnit lineDelta = logicalHeight() - layoutState.endLineLogicalTop();
1804
1805     bool paginated = view().layoutState() && view().layoutState()->isPaginated();
1806     if (paginated && layoutState.flowThread()) {
1807         // Check all lines from here to the end, and see if the hypothetical new position for the lines will result
1808         // in a different available line width.
1809         for (RootInlineBox* lineBox = layoutState.endLine(); lineBox; lineBox = lineBox->nextRootBox()) {
1810             if (paginated) {
1811                 // This isn't the real move we're going to do, so don't update the line box's pagination
1812                 // strut yet.
1813                 LayoutUnit oldPaginationStrut = lineBox->paginationStrut();
1814                 bool overflowsRegion;
1815                 lineDelta -= oldPaginationStrut;
1816                 adjustLinePositionForPagination(lineBox, lineDelta, overflowsRegion, layoutState.flowThread());
1817                 lineBox->setPaginationStrut(oldPaginationStrut);
1818             }
1819             if (lineWidthForPaginatedLineChanged(lineBox, lineDelta, layoutState.flowThread()))
1820                 return false;
1821         }
1822     }
1823     
1824     if (!lineDelta || !m_floatingObjects)
1825         return true;
1826     
1827     // See if any floats end in the range along which we want to shift the lines vertically.
1828     LayoutUnit logicalTop = std::min(logicalHeight(), layoutState.endLineLogicalTop());
1829
1830     RootInlineBox* lastLine = layoutState.endLine();
1831     while (RootInlineBox* nextLine = lastLine->nextRootBox())
1832         lastLine = nextLine;
1833
1834     LayoutUnit logicalBottom = lastLine->lineBottomWithLeading() + absoluteValue(lineDelta);
1835
1836     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1837     auto end = floatingObjectSet.end();
1838     for (auto it = floatingObjectSet.begin(); it != end; ++it) {
1839         FloatingObject* floatingObject = it->get();
1840         if (logicalBottomForFloat(floatingObject) >= logicalTop && logicalBottomForFloat(floatingObject) < logicalBottom)
1841             return false;
1842     }
1843
1844     return true;
1845 }
1846
1847 bool RenderBlockFlow::lineWidthForPaginatedLineChanged(RootInlineBox* rootBox, LayoutUnit lineDelta, RenderFlowThread* flowThread) const
1848 {
1849     if (!flowThread)
1850         return false;
1851
1852     RenderRegion* currentRegion = regionAtBlockOffset(rootBox->lineTopWithLeading() + lineDelta);
1853     // Just bail if the region didn't change.
1854     if (rootBox->containingRegion() == currentRegion)
1855         return false;
1856     return rootBox->paginatedLineWidth() != availableLogicalWidthForContent(currentRegion);
1857 }
1858
1859 bool RenderBlockFlow::matchedEndLine(LineLayoutState& layoutState, const InlineBidiResolver& resolver, const InlineIterator& endLineStart, const BidiStatus& endLineStatus)
1860 {
1861     if (resolver.position() == endLineStart) {
1862         if (resolver.status() != endLineStatus)
1863             return false;
1864         return checkPaginationAndFloatsAtEndLine(layoutState);
1865     }
1866
1867     // The first clean line doesn't match, but we can check a handful of following lines to try
1868     // to match back up.
1869     static int numLines = 8; // The # of lines we're willing to match against.
1870     RootInlineBox* originalEndLine = layoutState.endLine();
1871     RootInlineBox* line = originalEndLine;
1872     for (int i = 0; i < numLines && line; i++, line = line->nextRootBox()) {
1873         if (line->lineBreakObj() == resolver.position().renderer() && line->lineBreakPos() == resolver.position().offset()) {
1874             // We have a match.
1875             if (line->lineBreakBidiStatus() != resolver.status())
1876                 return false; // ...but the bidi state doesn't match.
1877             
1878             bool matched = false;
1879             RootInlineBox* result = line->nextRootBox();
1880             layoutState.setEndLine(result);
1881             if (result) {
1882                 layoutState.setEndLineLogicalTop(line->lineBottomWithLeading());
1883                 matched = checkPaginationAndFloatsAtEndLine(layoutState);
1884             }
1885
1886             // Now delete the lines that we failed to sync.
1887             deleteLineRange(layoutState, originalEndLine, result);
1888             return matched;
1889         }
1890     }
1891
1892     return false;
1893 }
1894
1895 bool RenderBlock::generatesLineBoxesForInlineChild(RenderObject* inlineObj)
1896 {
1897     ASSERT(inlineObj->parent() == this);
1898
1899     InlineIterator it(this, inlineObj, 0);
1900     // FIXME: We should pass correct value for WhitespacePosition.
1901     while (!it.atEnd() && !requiresLineBox(it))
1902         it.increment();
1903
1904     return !it.atEnd();
1905 }
1906
1907 void RenderBlockFlow::addOverflowFromInlineChildren()
1908 {
1909     if (auto layout = simpleLineLayout()) {
1910         ASSERT(!hasOverflowClip());
1911         SimpleLineLayout::collectFlowOverflow(*this, *layout);
1912         return;
1913     }
1914     LayoutUnit endPadding = hasOverflowClip() ? paddingEnd() : LayoutUnit();
1915     // FIXME: Need to find another way to do this, since scrollbars could show when we don't want them to.
1916     if (hasOverflowClip() && !endPadding && element() && element()->isRootEditableElement() && style().isLeftToRightDirection())
1917         endPadding = 1;
1918     for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
1919         addLayoutOverflow(curr->paddedLayoutOverflowRect(endPadding));
1920         RenderRegion* region = flowThreadContainingBlock() ? curr->containingRegion() : nullptr;
1921         if (region)
1922             region->addLayoutOverflowForBox(this, curr->paddedLayoutOverflowRect(endPadding));
1923         if (!hasOverflowClip()) {
1924             addVisualOverflow(curr->visualOverflowRect(curr->lineTop(), curr->lineBottom()));
1925             if (region)
1926                 region->addVisualOverflowForBox(this, curr->visualOverflowRect(curr->lineTop(), curr->lineBottom()));
1927         }
1928     }
1929 }
1930
1931 void RenderBlockFlow::deleteEllipsisLineBoxes()
1932 {
1933     ETextAlign textAlign = style().textAlign();
1934     bool ltr = style().isLeftToRightDirection();
1935     bool firstLine = true;
1936     for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
1937         if (curr->hasEllipsisBox()) {
1938             curr->clearTruncation();
1939
1940             // Shift the line back where it belongs if we cannot accomodate an ellipsis.
1941             float logicalLeft = logicalLeftOffsetForLine(curr->lineTop(), firstLine);
1942             float availableLogicalWidth = logicalRightOffsetForLine(curr->lineTop(), false) - logicalLeft;
1943             float totalLogicalWidth = curr->logicalWidth();
1944             updateLogicalWidthForAlignment(textAlign, curr, 0, logicalLeft, totalLogicalWidth, availableLogicalWidth, 0);
1945
1946             if (ltr)
1947                 curr->adjustLogicalPosition((logicalLeft - curr->logicalLeft()), 0);
1948             else
1949                 curr->adjustLogicalPosition(-(curr->logicalLeft() - logicalLeft), 0);
1950         }
1951         firstLine = false;
1952     }
1953 }
1954
1955 void RenderBlockFlow::checkLinesForTextOverflow()
1956 {
1957     // Determine the width of the ellipsis using the current font.
1958     // FIXME: CSS3 says this is configurable, also need to use 0x002E (FULL STOP) if horizontal ellipsis is "not renderable"
1959     const FontCascade& font = style().fontCascade();
1960     DEPRECATED_DEFINE_STATIC_LOCAL(AtomicString, ellipsisStr, (&horizontalEllipsis, 1));
1961     const FontCascade& firstLineFont = firstLineStyle().fontCascade();
1962     float firstLineEllipsisWidth = firstLineFont.width(constructTextRun(this, firstLineFont, &horizontalEllipsis, 1, firstLineStyle()));
1963     float ellipsisWidth = (font == firstLineFont) ? firstLineEllipsisWidth : font.width(constructTextRun(this, font, &horizontalEllipsis, 1, style()));
1964
1965     // For LTR text truncation, we want to get the right edge of our padding box, and then we want to see
1966     // if the right edge of a line box exceeds that.  For RTL, we use the left edge of the padding box and
1967     // check the left edge of the line box to see if it is less
1968     // Include the scrollbar for overflow blocks, which means we want to use "contentWidth()"
1969     bool ltr = style().isLeftToRightDirection();
1970     ETextAlign textAlign = style().textAlign();
1971     bool firstLine = true;
1972     for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
1973         LayoutUnit blockRightEdge = logicalRightOffsetForLine(curr->lineTop(), firstLine);
1974         LayoutUnit blockLeftEdge = logicalLeftOffsetForLine(curr->lineTop(), firstLine);
1975         LayoutUnit lineBoxEdge = ltr ? curr->x() + curr->logicalWidth() : curr->x();
1976         if ((ltr && lineBoxEdge > blockRightEdge) || (!ltr && lineBoxEdge < blockLeftEdge)) {
1977             // This line spills out of our box in the appropriate direction.  Now we need to see if the line
1978             // can be truncated.  In order for truncation to be possible, the line must have sufficient space to
1979             // accommodate our truncation string, and no replaced elements (images, tables) can overlap the ellipsis
1980             // space.
1981
1982             LayoutUnit width = firstLine ? firstLineEllipsisWidth : ellipsisWidth;
1983             LayoutUnit blockEdge = ltr ? blockRightEdge : blockLeftEdge;
1984             if (curr->lineCanAccommodateEllipsis(ltr, blockEdge, lineBoxEdge, width)) {
1985                 float totalLogicalWidth = curr->placeEllipsis(ellipsisStr, ltr, blockLeftEdge, blockRightEdge, width);
1986
1987                 float logicalLeft = 0; // We are only interested in the delta from the base position.
1988                 float truncatedWidth = logicalRightOffsetForLine(curr->lineTop(), firstLine);
1989                 updateLogicalWidthForAlignment(textAlign, curr, 0, logicalLeft, totalLogicalWidth, truncatedWidth, 0);
1990                 if (ltr)
1991                     curr->adjustLogicalPosition(logicalLeft, 0);
1992                 else
1993                     curr->adjustLogicalPosition(-(truncatedWidth - (logicalLeft + totalLogicalWidth)), 0);
1994             }
1995         }
1996         firstLine = false;
1997     }
1998 }
1999
2000 bool RenderBlockFlow::positionNewFloatOnLine(FloatingObject* newFloat, FloatingObject* lastFloatFromPreviousLine, LineInfo& lineInfo, LineWidth& width)
2001 {
2002     if (!positionNewFloats())
2003         return false;
2004
2005     width.shrinkAvailableWidthForNewFloatIfNeeded(newFloat);
2006
2007     // We only connect floats to lines for pagination purposes if the floats occur at the start of
2008     // the line and the previous line had a hard break (so this line is either the first in the block
2009     // or follows a <br>).
2010     if (!newFloat->paginationStrut() || !lineInfo.previousLineBrokeCleanly() || !lineInfo.isEmpty())
2011         return true;
2012
2013     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2014     ASSERT(floatingObjectSet.last().get() == newFloat);
2015
2016     LayoutUnit floatLogicalTop = logicalTopForFloat(newFloat);
2017     LayoutUnit paginationStrut = newFloat->paginationStrut();
2018
2019     if (floatLogicalTop - paginationStrut != logicalHeight() + lineInfo.floatPaginationStrut())
2020         return true;
2021
2022     auto it = floatingObjectSet.end();
2023     --it; // Last float is newFloat, skip that one.
2024     auto begin = floatingObjectSet.begin();
2025     while (it != begin) {
2026         --it;
2027         FloatingObject* floatingObject = it->get();
2028         if (floatingObject == lastFloatFromPreviousLine)
2029             break;
2030         if (logicalTopForFloat(floatingObject) == logicalHeight() + lineInfo.floatPaginationStrut()) {
2031             floatingObject->setPaginationStrut(paginationStrut + floatingObject->paginationStrut());
2032             RenderBox& floatBox = floatingObject->renderer();
2033             setLogicalTopForChild(floatBox, logicalTopForChild(floatBox) + marginBeforeForChild(floatBox) + paginationStrut);
2034
2035             if (updateRegionRangeForBoxChild(floatingObject->renderer()))
2036                 floatBox.setNeedsLayout(MarkOnlyThis);
2037             else if (is<RenderBlock>(floatBox))
2038                 downcast<RenderBlock>(floatBox).setChildNeedsLayout(MarkOnlyThis);
2039             floatBox.layoutIfNeeded();
2040
2041             // Save the old logical top before calling removePlacedObject which will set
2042             // isPlaced to false. Otherwise it will trigger an assert in logicalTopForFloat.
2043             LayoutUnit oldLogicalTop = logicalTopForFloat(floatingObject);
2044             m_floatingObjects->removePlacedObject(floatingObject);
2045             setLogicalTopForFloat(floatingObject, oldLogicalTop + paginationStrut);
2046             m_floatingObjects->addPlacedObject(floatingObject);
2047         }
2048     }
2049
2050     // Just update the line info's pagination strut without altering our logical height yet. If the line ends up containing
2051     // no content, then we don't want to improperly grow the height of the block.
2052     lineInfo.setFloatPaginationStrut(lineInfo.floatPaginationStrut() + paginationStrut);
2053     return true;
2054 }
2055
2056 LayoutUnit RenderBlockFlow::startAlignedOffsetForLine(LayoutUnit position, bool firstLine)
2057 {
2058     ETextAlign textAlign = style().textAlign();
2059
2060     // <rdar://problem/15427571>
2061     // https://bugs.webkit.org/show_bug.cgi?id=124522
2062     // This quirk is for legacy content that doesn't work properly with the center positioning scheme
2063     // being honored (e.g., epubs).
2064     if (textAlign == TASTART || document().settings()->useLegacyTextAlignPositionedElementBehavior()) // FIXME: Handle TAEND here
2065         return startOffsetForLine(position, firstLine);
2066
2067     // updateLogicalWidthForAlignment() handles the direction of the block so no need to consider it here
2068     float totalLogicalWidth = 0;
2069     float logicalLeft = logicalLeftOffsetForLine(logicalHeight(), false);
2070     float availableLogicalWidth = logicalRightOffsetForLine(logicalHeight(), false) - logicalLeft;
2071
2072     // FIXME: Bug 129311: We need to pass a valid RootInlineBox here, considering the bidi level used to construct the line.
2073     updateLogicalWidthForAlignment(textAlign, 0, 0, logicalLeft, totalLogicalWidth, availableLogicalWidth, 0);
2074
2075     if (!style().isLeftToRightDirection())
2076         return logicalWidth() - logicalLeft;
2077     return logicalLeft;
2078 }
2079
2080 void RenderBlockFlow::updateRegionForLine(RootInlineBox* lineBox) const
2081 {
2082     ASSERT(lineBox);
2083
2084     if (!hasRegionRangeInFlowThread())
2085         lineBox->clearContainingRegion();
2086     else {
2087         if (auto containingRegion = regionAtBlockOffset(lineBox->lineTopWithLeading()))
2088             lineBox->setContainingRegion(*containingRegion);
2089         else
2090             lineBox->clearContainingRegion();
2091     }
2092
2093     RootInlineBox* prevLineBox = lineBox->prevRootBox();
2094     if (!prevLineBox)
2095         return;
2096
2097     // This check is more accurate than the one in |adjustLinePositionForPagination| because it takes into
2098     // account just the container changes between lines. The before mentioned function doesn't set the flag
2099     // correctly if the line is positioned at the top of the last fragment container.
2100     if (lineBox->containingRegion() != prevLineBox->containingRegion())
2101         lineBox->setIsFirstAfterPageBreak(true);
2102 }
2103
2104 }