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