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