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