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