<rdar://problem/9479926> REGRESSION (r82144): Icon overlaps text in Twitter message...
[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  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public License
17  * along with this library; see the file COPYING.LIB.  If not, write to
18  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  *
21  */
22
23 #include "config.h"
24
25 #include "BidiResolver.h"
26 #include "Hyphenation.h"
27 #include "InlineIterator.h"
28 #include "InlineTextBox.h"
29 #include "Logging.h"
30 #include "RenderArena.h"
31 #include "RenderCombineText.h"
32 #include "RenderInline.h"
33 #include "RenderLayer.h"
34 #include "RenderListMarker.h"
35 #include "RenderRubyRun.h"
36 #include "RenderView.h"
37 #include "Settings.h"
38 #include "TextBreakIterator.h"
39 #include "TextRun.h"
40 #include "TrailingFloatsRootInlineBox.h"
41 #include "VerticalPositionCache.h"
42 #include "break_lines.h"
43 #include <wtf/AlwaysInline.h>
44 #include <wtf/RefCountedLeakCounter.h>
45 #include <wtf/StdLibExtras.h>
46 #include <wtf/Vector.h>
47 #include <wtf/unicode/CharacterNames.h>
48
49 #if ENABLE(SVG)
50 #include "RenderSVGInlineText.h"
51 #include "SVGRootInlineBox.h"
52 #endif
53
54 using namespace std;
55 using namespace WTF;
56 using namespace Unicode;
57
58 namespace WebCore {
59
60 // We don't let our line box tree for a single line get any deeper than this.
61 const unsigned cMaxLineDepth = 200;
62
63 class LineInfo {
64 public:
65     LineInfo()
66         : m_isFirstLine(true)
67         , m_isLastLine(false)
68         , m_isEmpty(true)
69         , m_previousLineBrokeCleanly(true)
70     { }
71
72     bool isFirstLine() const { return m_isFirstLine; }
73     bool isLastLine() const { return m_isLastLine; }
74     bool isEmpty() const { return m_isEmpty; }
75     bool previousLineBrokeCleanly() const { return m_previousLineBrokeCleanly; }
76
77     void setFirstLine(bool firstLine) { m_isFirstLine = firstLine; }
78     void setLastLine(bool lastLine) { m_isLastLine = lastLine; }
79     void setEmpty(bool empty) { m_isEmpty = empty; }
80     void setPreviousLineBrokeCleanly(bool previousLineBrokeCleanly) { m_previousLineBrokeCleanly = previousLineBrokeCleanly; }
81
82 private:
83     bool m_isFirstLine;
84     bool m_isLastLine;
85     bool m_isEmpty;
86     bool m_previousLineBrokeCleanly;
87 };
88
89 static inline int borderPaddingMarginStart(RenderInline* child)
90 {
91     return child->marginStart() + child->paddingStart() + child->borderStart();
92 }
93
94 static inline int borderPaddingMarginEnd(RenderInline* child)
95 {
96     return child->marginEnd() + child->paddingEnd() + child->borderEnd();
97 }
98
99 static int inlineLogicalWidth(RenderObject* child, bool start = true, bool end = true)
100 {
101     unsigned lineDepth = 1;
102     int extraWidth = 0;
103     RenderObject* parent = child->parent();
104     while (parent->isRenderInline() && lineDepth++ < cMaxLineDepth) {
105         RenderInline* parentAsRenderInline = toRenderInline(parent);
106         if (start && !child->previousSibling())
107             extraWidth += borderPaddingMarginStart(parentAsRenderInline);
108         if (end && !child->nextSibling())
109             extraWidth += borderPaddingMarginEnd(parentAsRenderInline);
110         child = parent;
111         parent = child->parent();
112     }
113     return extraWidth;
114 }
115
116 static void checkMidpoints(LineMidpointState& lineMidpointState, InlineIterator& lBreak)
117 {
118     // Check to see if our last midpoint is a start point beyond the line break.  If so,
119     // shave it off the list, and shave off a trailing space if the previous end point doesn't
120     // preserve whitespace.
121     if (lBreak.m_obj && lineMidpointState.numMidpoints && !(lineMidpointState.numMidpoints % 2)) {
122         InlineIterator* midpoints = lineMidpointState.midpoints.data();
123         InlineIterator& endpoint = midpoints[lineMidpointState.numMidpoints - 2];
124         const InlineIterator& startpoint = midpoints[lineMidpointState.numMidpoints - 1];
125         InlineIterator currpoint = endpoint;
126         while (!currpoint.atEnd() && currpoint != startpoint && currpoint != lBreak)
127             currpoint.increment();
128         if (currpoint == lBreak) {
129             // We hit the line break before the start point.  Shave off the start point.
130             lineMidpointState.numMidpoints--;
131             if (endpoint.m_obj->style()->collapseWhiteSpace())
132                 endpoint.m_pos--;
133         }
134     }
135 }
136
137 static void addMidpoint(LineMidpointState& lineMidpointState, const InlineIterator& midpoint)
138 {
139     if (lineMidpointState.midpoints.size() <= lineMidpointState.numMidpoints)
140         lineMidpointState.midpoints.grow(lineMidpointState.numMidpoints + 10);
141
142     InlineIterator* midpoints = lineMidpointState.midpoints.data();
143     midpoints[lineMidpointState.numMidpoints++] = midpoint;
144 }
145
146 static inline BidiRun* createRun(int start, int end, RenderObject* obj, InlineBidiResolver& resolver)
147 {
148     return new (obj->renderArena()) BidiRun(start, end, obj, resolver.context(), resolver.dir());
149 }
150
151 void RenderBlock::appendRunsForObject(BidiRunList<BidiRun>& runs, int start, int end, RenderObject* obj, InlineBidiResolver& resolver)
152 {
153     if (start > end || obj->isFloating() ||
154         (obj->isPositioned() && !obj->style()->isOriginalDisplayInlineType() && !obj->container()->isRenderInline()))
155         return;
156
157     LineMidpointState& lineMidpointState = resolver.midpointState();
158     bool haveNextMidpoint = (lineMidpointState.currentMidpoint < lineMidpointState.numMidpoints);
159     InlineIterator nextMidpoint;
160     if (haveNextMidpoint)
161         nextMidpoint = lineMidpointState.midpoints[lineMidpointState.currentMidpoint];
162     if (lineMidpointState.betweenMidpoints) {
163         if (!(haveNextMidpoint && nextMidpoint.m_obj == obj))
164             return;
165         // This is a new start point. Stop ignoring objects and
166         // adjust our start.
167         lineMidpointState.betweenMidpoints = false;
168         start = nextMidpoint.m_pos;
169         lineMidpointState.currentMidpoint++;
170         if (start < end)
171             return appendRunsForObject(runs, start, end, obj, resolver);
172     } else {
173         if (!haveNextMidpoint || (obj != nextMidpoint.m_obj)) {
174             runs.addRun(createRun(start, end, obj, resolver));
175             return;
176         }
177
178         // An end midpoint has been encountered within our object.  We
179         // need to go ahead and append a run with our endpoint.
180         if (static_cast<int>(nextMidpoint.m_pos + 1) <= end) {
181             lineMidpointState.betweenMidpoints = true;
182             lineMidpointState.currentMidpoint++;
183             if (nextMidpoint.m_pos != UINT_MAX) { // UINT_MAX means stop at the object and don't include any of it.
184                 if (static_cast<int>(nextMidpoint.m_pos + 1) > start)
185                     runs.addRun(createRun(start, nextMidpoint.m_pos + 1, obj, resolver));
186                 return appendRunsForObject(runs, nextMidpoint.m_pos + 1, end, obj, resolver);
187             }
188         } else
189            runs.addRun(createRun(start, end, obj, resolver));
190     }
191 }
192
193 static inline InlineBox* createInlineBoxForRenderer(RenderObject* obj, bool isRootLineBox, bool isOnlyRun = false)
194 {
195     if (isRootLineBox)
196         return toRenderBlock(obj)->createAndAppendRootInlineBox();
197
198     if (obj->isText()) {
199         InlineTextBox* textBox = toRenderText(obj)->createInlineTextBox();
200         // We only treat a box as text for a <br> if we are on a line by ourself or in strict mode
201         // (Note the use of strict mode.  In "almost strict" mode, we don't treat the box for <br> as text.)
202         if (obj->isBR())
203             textBox->setIsText(isOnlyRun || obj->document()->inNoQuirksMode());
204         return textBox;
205     }
206
207     if (obj->isBox())
208         return toRenderBox(obj)->createInlineBox();
209
210     return toRenderInline(obj)->createAndAppendInlineFlowBox();
211 }
212
213 static inline void dirtyLineBoxesForRenderer(RenderObject* o, bool fullLayout)
214 {
215     if (o->isText()) {
216         if (o->preferredLogicalWidthsDirty() && (o->isCounter() || o->isQuote()))
217             toRenderText(o)->computePreferredLogicalWidths(0); // FIXME: Counters depend on this hack. No clue why. Should be investigated and removed.
218         toRenderText(o)->dirtyLineBoxes(fullLayout);
219     } else
220         toRenderInline(o)->dirtyLineBoxes(fullLayout);
221 }
222
223 static bool parentIsConstructedOrHaveNext(InlineFlowBox* parentBox)
224 {
225     do {
226         if (parentBox->isConstructed() || parentBox->nextOnLine())
227             return true;
228         parentBox = parentBox->parent();
229     } while (parentBox);
230     return false;
231 }
232
233 InlineFlowBox* RenderBlock::createLineBoxes(RenderObject* obj, const LineInfo& lineInfo, InlineBox* childBox)
234 {
235     // See if we have an unconstructed line box for this object that is also
236     // the last item on the line.
237     unsigned lineDepth = 1;
238     InlineFlowBox* parentBox = 0;
239     InlineFlowBox* result = 0;
240     bool hasDefaultLineBoxContain = style()->lineBoxContain() == RenderStyle::initialLineBoxContain();
241     do {
242         ASSERT(obj->isRenderInline() || obj == this);
243
244         RenderInline* inlineFlow = (obj != this) ? toRenderInline(obj) : 0;
245
246         // Get the last box we made for this render object.
247         parentBox = inlineFlow ? inlineFlow->lastLineBox() : toRenderBlock(obj)->lastLineBox();
248
249         // If this box or its ancestor is constructed then it is from a previous line, and we need
250         // to make a new box for our line.  If this box or its ancestor is unconstructed but it has
251         // something following it on the line, then we know we have to make a new box
252         // as well.  In this situation our inline has actually been split in two on
253         // the same line (this can happen with very fancy language mixtures).
254         bool constructedNewBox = false;
255         bool allowedToConstructNewBox = !hasDefaultLineBoxContain || !inlineFlow || inlineFlow->alwaysCreateLineBoxes();
256         bool canUseExistingParentBox = parentBox && !parentIsConstructedOrHaveNext(parentBox);
257         if (allowedToConstructNewBox && !canUseExistingParentBox) {
258             // We need to make a new box for this render object.  Once
259             // made, we need to place it at the end of the current line.
260             InlineBox* newBox = createInlineBoxForRenderer(obj, obj == this);
261             ASSERT(newBox->isInlineFlowBox());
262             parentBox = static_cast<InlineFlowBox*>(newBox);
263             parentBox->setFirstLineStyleBit(lineInfo.isFirstLine());
264             parentBox->setIsHorizontal(isHorizontalWritingMode());
265             if (!hasDefaultLineBoxContain)
266                 parentBox->clearDescendantsHaveSameLineHeightAndBaseline();
267             constructedNewBox = true;
268         }
269
270         if (constructedNewBox || canUseExistingParentBox) {
271             if (!result)
272                 result = parentBox;
273
274             // If we have hit the block itself, then |box| represents the root
275             // inline box for the line, and it doesn't have to be appended to any parent
276             // inline.
277             if (childBox)
278                 parentBox->addToLine(childBox);
279
280             if (!constructedNewBox || obj == this)
281                 break;
282
283             childBox = parentBox;
284         }
285
286         // If we've exceeded our line depth, then jump straight to the root and skip all the remaining
287         // intermediate inline flows.
288         obj = (++lineDepth >= cMaxLineDepth) ? this : obj->parent();
289
290     } while (true);
291
292     return result;
293 }
294
295 static bool reachedEndOfTextRenderer(const BidiRunList<BidiRun>& bidiRuns)
296 {
297     BidiRun* run = bidiRuns.logicallyLastRun();
298     if (!run)
299         return true;
300     unsigned int pos = run->stop();
301     RenderObject* r = run->m_object;
302     if (!r->isText() || r->isBR())
303         return false;
304     RenderText* renderText = toRenderText(r);
305     if (pos >= renderText->textLength())
306         return true;
307
308     while (isASCIISpace(renderText->characters()[pos])) {
309         pos++;
310         if (pos >= renderText->textLength())
311             return true;
312     }
313     return false;
314 }
315
316 RootInlineBox* RenderBlock::constructLine(BidiRunList<BidiRun>& bidiRuns, const LineInfo& lineInfo)
317 {
318     ASSERT(bidiRuns.firstRun());
319
320     bool rootHasSelectedChildren = false;
321     InlineFlowBox* parentBox = 0;
322     for (BidiRun* r = bidiRuns.firstRun(); r; r = r->next()) {
323         // Create a box for our object.
324         bool isOnlyRun = (bidiRuns.runCount() == 1);
325         if (bidiRuns.runCount() == 2 && !r->m_object->isListMarker())
326             isOnlyRun = (!style()->isLeftToRightDirection() ? bidiRuns.lastRun() : bidiRuns.firstRun())->m_object->isListMarker();
327
328         InlineBox* box = createInlineBoxForRenderer(r->m_object, false, isOnlyRun);
329         r->m_box = box;
330
331         ASSERT(box);
332         if (!box)
333             continue;
334
335         if (!rootHasSelectedChildren && box->renderer()->selectionState() != RenderObject::SelectionNone)
336             rootHasSelectedChildren = true;
337
338         // If we have no parent box yet, or if the run is not simply a sibling,
339         // then we need to construct inline boxes as necessary to properly enclose the
340         // run's inline box.
341         if (!parentBox || parentBox->renderer() != r->m_object->parent())
342             // Create new inline boxes all the way back to the appropriate insertion point.
343             parentBox = createLineBoxes(r->m_object->parent(), lineInfo, box);
344         else {
345             // Append the inline box to this line.
346             parentBox->addToLine(box);
347         }
348
349         bool visuallyOrdered = r->m_object->style()->visuallyOrdered();
350         box->setBidiLevel(r->level());
351
352         if (box->isInlineTextBox()) {
353             InlineTextBox* text = static_cast<InlineTextBox*>(box);
354             text->setStart(r->m_start);
355             text->setLen(r->m_stop - r->m_start);
356             text->m_dirOverride = r->dirOverride(visuallyOrdered);
357             if (r->m_hasHyphen)
358                 text->setHasHyphen(true);
359         }
360     }
361
362     // We should have a root inline box.  It should be unconstructed and
363     // be the last continuation of our line list.
364     ASSERT(lastLineBox() && !lastLineBox()->isConstructed());
365
366     // Set the m_selectedChildren flag on the root inline box if one of the leaf inline box
367     // from the bidi runs walk above has a selection state.
368     if (rootHasSelectedChildren)
369         lastLineBox()->root()->setHasSelectedChildren(true);
370
371     // Set bits on our inline flow boxes that indicate which sides should
372     // paint borders/margins/padding.  This knowledge will ultimately be used when
373     // we determine the horizontal positions and widths of all the inline boxes on
374     // the line.
375     bool isLogicallyLastRunWrapped = bidiRuns.logicallyLastRun()->m_object && bidiRuns.logicallyLastRun()->m_object->isText() ? !reachedEndOfTextRenderer(bidiRuns) : true;
376     lastLineBox()->determineSpacingForFlowBoxes(lineInfo.isLastLine(), isLogicallyLastRunWrapped, bidiRuns.logicallyLastRun()->m_object);
377
378     // Now mark the line boxes as being constructed.
379     lastLineBox()->setConstructed();
380
381     // Return the last line.
382     return lastRootBox();
383 }
384
385 ETextAlign RenderBlock::textAlignmentForLine(bool endsWithSoftBreak) const
386 {
387     ETextAlign alignment = style()->textAlign();
388     if (!endsWithSoftBreak && alignment == JUSTIFY)
389         alignment = TAAUTO;
390
391     return alignment;
392 }
393
394 static void updateLogicalWidthForLeftAlignedBlock(bool isLeftToRightDirection, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float availableLogicalWidth)
395 {
396     // The direction of the block should determine what happens with wide lines.
397     // In particular with RTL blocks, wide lines should still spill out to the left.
398     if (isLeftToRightDirection) {
399         if (totalLogicalWidth > availableLogicalWidth && trailingSpaceRun)
400             trailingSpaceRun->m_box->setLogicalWidth(max<float>(0, trailingSpaceRun->m_box->logicalWidth() - totalLogicalWidth + availableLogicalWidth));
401         return;
402     }
403
404     if (trailingSpaceRun)
405         trailingSpaceRun->m_box->setLogicalWidth(0);
406     else if (totalLogicalWidth > availableLogicalWidth)
407         logicalLeft -= (totalLogicalWidth - availableLogicalWidth);
408 }
409
410 static void updateLogicalWidthForRightAlignedBlock(bool isLeftToRightDirection, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float availableLogicalWidth)
411 {
412     // Wide lines spill out of the block based off direction.
413     // So even if text-align is right, if direction is LTR, wide lines should overflow out of the right
414     // side of the block.
415     if (isLeftToRightDirection) {
416         if (trailingSpaceRun) {
417             totalLogicalWidth -= trailingSpaceRun->m_box->logicalWidth();
418             trailingSpaceRun->m_box->setLogicalWidth(0);
419         }
420         if (totalLogicalWidth < availableLogicalWidth)
421             logicalLeft += availableLogicalWidth - totalLogicalWidth;
422         return;
423     }
424
425     if (totalLogicalWidth > availableLogicalWidth && trailingSpaceRun) {
426         trailingSpaceRun->m_box->setLogicalWidth(max<float>(0, trailingSpaceRun->m_box->logicalWidth() - totalLogicalWidth + availableLogicalWidth));
427         totalLogicalWidth -= trailingSpaceRun->m_box->logicalWidth();
428     } else
429         logicalLeft += availableLogicalWidth - totalLogicalWidth;
430 }
431
432 static void updateLogicalWidthForCenterAlignedBlock(bool isLeftToRightDirection, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float availableLogicalWidth)
433 {
434     float trailingSpaceWidth = 0;
435     if (trailingSpaceRun) {
436         totalLogicalWidth -= trailingSpaceRun->m_box->logicalWidth();
437         trailingSpaceWidth = min(trailingSpaceRun->m_box->logicalWidth(), (availableLogicalWidth - totalLogicalWidth + 1) / 2);
438         trailingSpaceRun->m_box->setLogicalWidth(max<float>(0, trailingSpaceWidth));
439     }
440     if (isLeftToRightDirection)
441         logicalLeft += max<float>((availableLogicalWidth - totalLogicalWidth) / 2, 0);
442     else
443         logicalLeft += totalLogicalWidth > availableLogicalWidth ? (availableLogicalWidth - totalLogicalWidth) : (availableLogicalWidth - totalLogicalWidth) / 2 - trailingSpaceWidth;
444 }
445
446 void RenderBlock::setMarginsForRubyRun(BidiRun* run, RenderRubyRun* renderer, RenderObject* previousObject, const LineInfo& lineInfo)
447 {
448     int startOverhang;
449     int endOverhang;
450     RenderObject* nextObject = 0;
451     for (BidiRun* runWithNextObject = run->next(); runWithNextObject; runWithNextObject = runWithNextObject->next()) {
452         if (!runWithNextObject->m_object->isPositioned() && !runWithNextObject->m_box->isLineBreak()) {
453             nextObject = runWithNextObject->m_object;
454             break;
455         }
456     }
457     renderer->getOverhang(lineInfo.isFirstLine(), renderer->style()->isLeftToRightDirection() ? previousObject : nextObject, renderer->style()->isLeftToRightDirection() ? nextObject : previousObject, startOverhang, endOverhang);
458     setMarginStartForChild(renderer, -startOverhang);
459     setMarginEndForChild(renderer, -endOverhang);
460 }
461
462 static inline void setLogicalWidthForTextRun(RootInlineBox* lineBox, BidiRun* run, RenderText* renderer, float xPos, const LineInfo& lineInfo,
463                                    GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache)
464 {
465     HashSet<const SimpleFontData*> fallbackFonts;
466     GlyphOverflow glyphOverflow;
467     
468     // Always compute glyph overflow if the block's line-box-contain value is "glyphs".
469     if (lineBox->fitsToGlyphs()) {
470         // If we don't stick out of the root line's font box, then don't bother computing our glyph overflow. This optimization
471         // will keep us from computing glyph bounds in nearly all cases.
472         bool includeRootLine = lineBox->includesRootLineBoxFontOrLeading();
473         int baselineShift = lineBox->verticalPositionForBox(run->m_box, verticalPositionCache);
474         int rootDescent = includeRootLine ? lineBox->renderer()->style(lineInfo.isFirstLine())->font().fontMetrics().descent() : 0;
475         int rootAscent = includeRootLine ? lineBox->renderer()->style(lineInfo.isFirstLine())->font().fontMetrics().ascent() : 0;
476         int boxAscent = renderer->style(lineInfo.isFirstLine())->font().fontMetrics().ascent() - baselineShift;
477         int boxDescent = renderer->style(lineInfo.isFirstLine())->font().fontMetrics().descent() + baselineShift;
478         if (boxAscent > rootDescent ||  boxDescent > rootAscent)
479             glyphOverflow.computeBounds = true; 
480     }
481     
482     int hyphenWidth = 0;
483     if (static_cast<InlineTextBox*>(run->m_box)->hasHyphen()) {
484         const AtomicString& hyphenString = renderer->style()->hyphenString();
485         hyphenWidth = renderer->style(lineInfo.isFirstLine())->font().width(TextRun(hyphenString.characters(), hyphenString.length()));
486     }
487     run->m_box->setLogicalWidth(renderer->width(run->m_start, run->m_stop - run->m_start, xPos, lineInfo.isFirstLine(), &fallbackFonts, &glyphOverflow) + hyphenWidth);
488     if (!fallbackFonts.isEmpty()) {
489         ASSERT(run->m_box->isText());
490         GlyphOverflowAndFallbackFontsMap::iterator it = textBoxDataMap.add(static_cast<InlineTextBox*>(run->m_box), make_pair(Vector<const SimpleFontData*>(), GlyphOverflow())).first;
491         ASSERT(it->second.first.isEmpty());
492         copyToVector(fallbackFonts, it->second.first);
493         run->m_box->parent()->clearDescendantsHaveSameLineHeightAndBaseline();
494     }
495     if ((glyphOverflow.top || glyphOverflow.bottom || glyphOverflow.left || glyphOverflow.right)) {
496         ASSERT(run->m_box->isText());
497         GlyphOverflowAndFallbackFontsMap::iterator it = textBoxDataMap.add(static_cast<InlineTextBox*>(run->m_box), make_pair(Vector<const SimpleFontData*>(), GlyphOverflow())).first;
498         it->second.second = glyphOverflow;
499         run->m_box->clearKnownToHaveNoOverflow();
500     }
501 }
502
503 static inline void computeExpansionForJustifiedText(BidiRun* firstRun, BidiRun* trailingSpaceRun, Vector<unsigned, 16>& expansionOpportunities, unsigned expansionOpportunityCount, float& totalLogicalWidth, float availableLogicalWidth)
504 {
505     if (!expansionOpportunityCount || availableLogicalWidth <= totalLogicalWidth)
506         return;
507
508     size_t i = 0;
509     for (BidiRun* r = firstRun; r; r = r->next()) {
510         if (!r->m_box || r == trailingSpaceRun)
511             continue;
512         
513         if (r->m_object->isText()) {
514             unsigned opportunitiesInRun = expansionOpportunities[i++];
515             
516             ASSERT(opportunitiesInRun <= expansionOpportunityCount);
517             
518             // Only justify text if whitespace is collapsed.
519             if (r->m_object->style()->collapseWhiteSpace()) {
520                 InlineTextBox* textBox = static_cast<InlineTextBox*>(r->m_box);
521                 int expansion = (availableLogicalWidth - totalLogicalWidth) * opportunitiesInRun / expansionOpportunityCount;
522                 textBox->setExpansion(expansion);
523                 totalLogicalWidth += expansion;
524             }
525             expansionOpportunityCount -= opportunitiesInRun;
526             if (!expansionOpportunityCount)
527                 break;
528         }
529     }
530 }
531
532 void RenderBlock::computeInlineDirectionPositionsForLine(RootInlineBox* lineBox, const LineInfo& lineInfo, BidiRun* firstRun, BidiRun* trailingSpaceRun, bool reachedEnd,
533                                                          GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache)
534 {
535     ETextAlign textAlign = textAlignmentForLine(!reachedEnd && !lineBox->endsWithBreak());
536     float logicalLeft = logicalLeftOffsetForLine(logicalHeight(), lineInfo.isFirstLine());
537     float availableLogicalWidth = logicalRightOffsetForLine(logicalHeight(), lineInfo.isFirstLine()) - logicalLeft;
538
539     bool needsWordSpacing = false;
540     float totalLogicalWidth = lineBox->getFlowSpacingLogicalWidth();
541     unsigned expansionOpportunityCount = 0;
542     bool isAfterExpansion = true;
543     Vector<unsigned, 16> expansionOpportunities;
544     RenderObject* previousObject = 0;
545
546     for (BidiRun* r = firstRun; r; r = r->next()) {
547         if (!r->m_box || r->m_object->isPositioned() || r->m_box->isLineBreak())
548             continue; // Positioned objects are only participating to figure out their
549                       // correct static x position.  They have no effect on the width.
550                       // Similarly, line break boxes have no effect on the width.
551         if (r->m_object->isText()) {
552             RenderText* rt = toRenderText(r->m_object);
553             if (textAlign == JUSTIFY && r != trailingSpaceRun) {
554                 if (!isAfterExpansion)
555                     static_cast<InlineTextBox*>(r->m_box)->setCanHaveLeadingExpansion(true);
556                 unsigned opportunitiesInRun = Font::expansionOpportunityCount(rt->characters() + r->m_start, r->m_stop - r->m_start, r->m_box->direction(), isAfterExpansion);
557                 expansionOpportunities.append(opportunitiesInRun);
558                 expansionOpportunityCount += opportunitiesInRun;
559             }
560
561             if (int length = rt->textLength()) {
562                 if (!r->m_start && needsWordSpacing && isSpaceOrNewline(rt->characters()[r->m_start]))
563                     totalLogicalWidth += rt->style(lineInfo.isFirstLine())->font().wordSpacing();
564                 needsWordSpacing = !isSpaceOrNewline(rt->characters()[r->m_stop - 1]) && r->m_stop == length;
565             }
566
567             setLogicalWidthForTextRun(lineBox, r, rt, totalLogicalWidth, lineInfo, textBoxDataMap, verticalPositionCache);
568         } else {
569             isAfterExpansion = false;
570             if (!r->m_object->isRenderInline()) {
571                 RenderBox* renderBox = toRenderBox(r->m_object);
572                 if (renderBox->isRubyRun())
573                     setMarginsForRubyRun(r, toRenderRubyRun(renderBox), previousObject, lineInfo);
574                 r->m_box->setLogicalWidth(logicalWidthForChild(renderBox));
575                 totalLogicalWidth += marginStartForChild(renderBox) + marginEndForChild(renderBox);
576             }
577         }
578
579         totalLogicalWidth += r->m_box->logicalWidth();
580         previousObject = r->m_object;
581     }
582
583     if (isAfterExpansion && !expansionOpportunities.isEmpty()) {
584         expansionOpportunities.last()--;
585         expansionOpportunityCount--;
586     }
587
588     // Armed with the total width of the line (without justification),
589     // we now examine our text-align property in order to determine where to position the
590     // objects horizontally.  The total width of the line can be increased if we end up
591     // justifying text.
592     switch (textAlign) {
593         case LEFT:
594         case WEBKIT_LEFT:
595             updateLogicalWidthForLeftAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
596             break;
597         case JUSTIFY:
598             adjustInlineDirectionLineBounds(expansionOpportunityCount, logicalLeft, availableLogicalWidth);
599             if (expansionOpportunityCount) {
600                 if (trailingSpaceRun) {
601                     totalLogicalWidth -= trailingSpaceRun->m_box->logicalWidth();
602                     trailingSpaceRun->m_box->setLogicalWidth(0);
603                 }
604                 break;
605             }
606             // fall through
607         case TAAUTO:
608             // for right to left fall through to right aligned
609             if (style()->isLeftToRightDirection()) {
610                 if (totalLogicalWidth > availableLogicalWidth && trailingSpaceRun)
611                     trailingSpaceRun->m_box->setLogicalWidth(max<float>(0, trailingSpaceRun->m_box->logicalWidth() - totalLogicalWidth + availableLogicalWidth));
612                 break;
613             }
614         case RIGHT:
615         case WEBKIT_RIGHT:
616             updateLogicalWidthForRightAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
617             break;
618         case CENTER:
619         case WEBKIT_CENTER:
620             updateLogicalWidthForCenterAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
621             break;
622         case TASTART:
623             if (style()->isLeftToRightDirection())
624                 updateLogicalWidthForLeftAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
625             else
626                 updateLogicalWidthForRightAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
627             break;
628         case TAEND:
629             if (style()->isLeftToRightDirection())
630                 updateLogicalWidthForRightAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
631             else
632                 updateLogicalWidthForLeftAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
633             break;
634     }
635
636     computeExpansionForJustifiedText(firstRun, trailingSpaceRun, expansionOpportunities, expansionOpportunityCount, totalLogicalWidth, availableLogicalWidth);
637
638     // The widths of all runs are now known.  We can now place every inline box (and
639     // compute accurate widths for the inline flow boxes).
640     needsWordSpacing = false;
641     lineBox->placeBoxesInInlineDirection(logicalLeft, needsWordSpacing, textBoxDataMap);
642 }
643
644 void RenderBlock::computeBlockDirectionPositionsForLine(RootInlineBox* lineBox, BidiRun* firstRun, GlyphOverflowAndFallbackFontsMap& textBoxDataMap,
645                                                         VerticalPositionCache& verticalPositionCache)
646 {
647     setLogicalHeight(lineBox->alignBoxesInBlockDirection(logicalHeight(), textBoxDataMap, verticalPositionCache));
648     lineBox->setBlockLogicalHeight(logicalHeight());
649
650     // Now make sure we place replaced render objects correctly.
651     for (BidiRun* r = firstRun; r; r = r->next()) {
652         ASSERT(r->m_box);
653         if (!r->m_box)
654             continue; // Skip runs with no line boxes.
655
656         // Align positioned boxes with the top of the line box.  This is
657         // a reasonable approximation of an appropriate y position.
658         if (r->m_object->isPositioned())
659             r->m_box->setLogicalTop(logicalHeight());
660
661         // Position is used to properly position both replaced elements and
662         // to update the static normal flow x/y of positioned elements.
663         if (r->m_object->isText())
664             toRenderText(r->m_object)->positionLineBox(r->m_box);
665         else if (r->m_object->isBox())
666             toRenderBox(r->m_object)->positionLineBox(r->m_box);
667     }
668     // Positioned objects and zero-length text nodes destroy their boxes in
669     // position(), which unnecessarily dirties the line.
670     lineBox->markDirty(false);
671 }
672
673 static inline bool isCollapsibleSpace(UChar character, RenderText* renderer)
674 {
675     if (character == ' ' || character == '\t' || character == softHyphen)
676         return true;
677     if (character == '\n')
678         return !renderer->style()->preserveNewline();
679     if (character == noBreakSpace)
680         return renderer->style()->nbspMode() == SPACE;
681     return false;
682 }
683
684
685 static void setStaticPositions(RenderBlock* block, RenderBox* child)
686 {
687     // FIXME: The math here is actually not really right. It's a best-guess approximation that
688     // will work for the common cases
689     RenderObject* containerBlock = child->container();
690     int blockHeight = block->logicalHeight();
691     if (containerBlock->isRenderInline()) {
692         // A relative positioned inline encloses us. In this case, we also have to determine our
693         // position as though we were an inline. Set |staticInlinePosition| and |staticBlockPosition| on the relative positioned
694         // inline so that we can obtain the value later.
695         toRenderInline(containerBlock)->layer()->setStaticInlinePosition(block->startOffsetForLine(blockHeight, false));
696         toRenderInline(containerBlock)->layer()->setStaticBlockPosition(blockHeight);
697     }
698
699     if (child->style()->isOriginalDisplayInlineType())
700         child->layer()->setStaticInlinePosition(block->startOffsetForLine(blockHeight, false));
701     else
702         child->layer()->setStaticInlinePosition(block->borderAndPaddingStart());
703     child->layer()->setStaticBlockPosition(blockHeight);
704 }
705
706 inline BidiRun* RenderBlock::handleTrailingSpaces(BidiRunList<BidiRun>& bidiRuns, BidiContext* currentContext)
707 {
708     if (!bidiRuns.runCount()
709         || !bidiRuns.logicallyLastRun()->m_object->style()->breakOnlyAfterWhiteSpace()
710         || !bidiRuns.logicallyLastRun()->m_object->style()->autoWrap())
711         return 0;
712
713     BidiRun* trailingSpaceRun = bidiRuns.logicallyLastRun();
714     RenderObject* lastObject = trailingSpaceRun->m_object;
715     if (!lastObject->isText())
716         return 0;
717
718     RenderText* lastText = toRenderText(lastObject);
719     const UChar* characters = lastText->characters();
720     int firstSpace = trailingSpaceRun->stop();
721     while (firstSpace > trailingSpaceRun->start()) {
722         UChar current = characters[firstSpace - 1];
723         if (!isCollapsibleSpace(current, lastText))
724             break;
725         firstSpace--;
726     }
727     if (firstSpace == trailingSpaceRun->stop())
728         return 0;
729
730     TextDirection direction = style()->direction();
731     bool shouldReorder = trailingSpaceRun != (direction == LTR ? bidiRuns.lastRun() : bidiRuns.firstRun());
732     if (firstSpace != trailingSpaceRun->start()) {
733         BidiContext* baseContext = currentContext;
734         while (BidiContext* parent = baseContext->parent())
735             baseContext = parent;
736
737         BidiRun* newTrailingRun = new (renderArena()) BidiRun(firstSpace, trailingSpaceRun->m_stop, trailingSpaceRun->m_object, baseContext, OtherNeutral);
738         trailingSpaceRun->m_stop = firstSpace;
739         if (direction == LTR)
740             bidiRuns.addRun(newTrailingRun);
741         else
742             bidiRuns.prependRun(newTrailingRun);
743         trailingSpaceRun = newTrailingRun;
744         return trailingSpaceRun;
745     }
746     if (!shouldReorder)
747         return trailingSpaceRun;
748
749     if (direction == LTR) {
750         bidiRuns.moveRunToEnd(trailingSpaceRun);
751         trailingSpaceRun->m_level = 0;
752     } else {
753         bidiRuns.moveRunToBeginning(trailingSpaceRun);
754         trailingSpaceRun->m_level = 1;
755     }
756     return trailingSpaceRun;
757 }
758
759 void RenderBlock::appendFloatingObjectToLastLine(FloatingObject* floatingObject)
760 {
761     ASSERT(!floatingObject->m_originatingLine);
762     floatingObject->m_originatingLine = lastRootBox();
763     lastRootBox()->appendFloat(floatingObject->renderer());
764 }
765
766 // This function constructs line boxes for all of the text runs in the resolver and computes their position.
767 RootInlineBox* RenderBlock::createLineBoxesFromBidiRuns(BidiRunList<BidiRun>& bidiRuns, const InlineIterator& end, LineInfo& lineInfo, VerticalPositionCache& verticalPositionCache, BidiRun* trailingSpaceRun)
768 {
769     if (!bidiRuns.runCount())
770         return 0;
771
772     // FIXME: Why is this only done when we had runs?
773     lineInfo.setLastLine(!end.m_obj);
774
775     RootInlineBox* lineBox = constructLine(bidiRuns, lineInfo);
776     if (!lineBox)
777         return 0;
778
779     lineBox->setEndsWithBreak(lineInfo.previousLineBrokeCleanly());
780     
781 #if ENABLE(SVG)
782     bool isSVGRootInlineBox = lineBox->isSVGRootInlineBox();
783 #else
784     bool isSVGRootInlineBox = false;
785 #endif
786     
787     GlyphOverflowAndFallbackFontsMap textBoxDataMap;
788     
789     // Now we position all of our text runs horizontally.
790     if (!isSVGRootInlineBox)
791         computeInlineDirectionPositionsForLine(lineBox, lineInfo, bidiRuns.firstRun(), trailingSpaceRun, end.atEnd(), textBoxDataMap, verticalPositionCache);
792     
793     // Now position our text runs vertically.
794     computeBlockDirectionPositionsForLine(lineBox, bidiRuns.firstRun(), textBoxDataMap, verticalPositionCache);
795     
796 #if ENABLE(SVG)
797     // SVG text layout code computes vertical & horizontal positions on its own.
798     // Note that we still need to execute computeVerticalPositionsForLine() as
799     // it calls InlineTextBox::positionLineBox(), which tracks whether the box
800     // contains reversed text or not. If we wouldn't do that editing and thus
801     // text selection in RTL boxes would not work as expected.
802     if (isSVGRootInlineBox) {
803         ASSERT(isSVGText());
804         static_cast<SVGRootInlineBox*>(lineBox)->computePerCharacterLayoutInformation();
805     }
806 #endif
807     
808     // Compute our overflow now.
809     lineBox->computeOverflow(lineBox->lineTop(), lineBox->lineBottom(), textBoxDataMap);
810     
811 #if PLATFORM(MAC)
812     // Highlight acts as an overflow inflation.
813     if (style()->highlight() != nullAtom)
814         lineBox->addHighlightOverflow();
815 #endif
816     return lineBox;
817 }
818
819 // Like LayoutState for layout(), LineLayoutState keeps track of global information
820 // during an entire linebox tree layout pass (aka layoutInlineChildren).
821 class LineLayoutState {
822 public:
823     LineLayoutState(bool fullLayout, int& repaintLogicalTop, int& repaintLogicalBottom)
824         : m_isFullLayout(fullLayout)
825         , m_repaintLogicalTop(repaintLogicalTop)
826         , m_repaintLogicalBottom(repaintLogicalBottom)
827     { }
828
829     void markForFullLayout() { m_isFullLayout = true; }
830     bool isFullLayout() const { return m_isFullLayout; }
831
832     void setRepaintRange(int logicalHeight) { m_repaintLogicalTop = m_repaintLogicalBottom = logicalHeight; }
833     void updateRepaintRangeFromBox(RootInlineBox* box, int paginationDelta = 0)
834     {
835         m_repaintLogicalTop = min(m_repaintLogicalTop, box->logicalTopVisualOverflow() + min(paginationDelta, 0));
836         m_repaintLogicalBottom = max(m_repaintLogicalBottom, box->logicalBottomVisualOverflow() + max(paginationDelta, 0));
837     }
838
839 private:
840     bool m_isFullLayout;
841
842     // FIXME: Should this be a range object instead of two ints?
843     int& m_repaintLogicalTop;
844     int& m_repaintLogicalBottom;
845 };
846
847 static void deleteLineRange(LineLayoutState& layoutState, RenderArena* arena, RootInlineBox* startLine, RootInlineBox* stopLine = 0)
848 {
849     RootInlineBox* boxToDelete = startLine;
850     while (boxToDelete && boxToDelete != stopLine) {
851         layoutState.updateRepaintRangeFromBox(boxToDelete);
852         // Note: deleteLineRange(renderArena(), firstRootBox()) is not identical to deleteLineBoxTree().
853         // deleteLineBoxTree uses nextLineBox() instead of nextRootBox() when traversing.
854         RootInlineBox* next = boxToDelete->nextRootBox();
855         boxToDelete->deleteLine(arena);
856         boxToDelete = next;
857     }
858 }
859
860 void RenderBlock::layoutRunsAndFloats(LineLayoutState& layoutState, bool hasInlineChild, Vector<FloatWithRect>& floats)
861 {
862     // We want to skip ahead to the first dirty line
863     InlineBidiResolver resolver;
864     unsigned floatIndex;
865     LineInfo lineInfo;
866     // FIXME: Should useRepaintBounds be on the LineLayoutState?
867     // It appears to be used to track the case where we're only repainting a subset of our lines.
868     bool useRepaintBounds = false;
869
870     RootInlineBox* startLine = determineStartPosition(layoutState, lineInfo, resolver, floats, floatIndex, useRepaintBounds);
871
872     // FIXME: This would make more sense outside of this function, but since
873     // determineStartPosition can change the fullLayout flag we have to do this here. Failure to call
874     // determineStartPosition first will break fast/repaint/line-flow-with-floats-9.html.
875     if (layoutState.isFullLayout() && hasInlineChild && !selfNeedsLayout()) {
876         setNeedsLayout(true, false);  // Mark ourselves as needing a full layout. This way we'll repaint like
877         // we're supposed to.
878         RenderView* v = view();
879         if (v && !v->doingFullRepaint() && hasLayer()) {
880             // Because we waited until we were already inside layout to discover
881             // that the block really needed a full layout, we missed our chance to repaint the layer
882             // before layout started.  Luckily the layer has cached the repaint rect for its original
883             // position and size, and so we can use that to make a repaint happen now.
884             repaintUsingContainer(containerForRepaint(), layer()->repaintRect());
885         }
886     }
887
888     FloatingObject* lastFloat = (m_floatingObjects && !m_floatingObjects->set().isEmpty()) ? m_floatingObjects->set().last() : 0;
889
890     LineMidpointState& lineMidpointState = resolver.midpointState();
891
892     // We also find the first clean line and extract these lines.  We will add them back
893     // if we determine that we're able to synchronize after handling all our dirty lines.
894     InlineIterator cleanLineStart;
895     BidiStatus cleanLineBidiStatus;
896     int endLineLogicalTop = 0;
897     RootInlineBox* endLine = (layoutState.isFullLayout() || !startLine) ?
898         0 : determineEndPosition(startLine, floats, floatIndex, cleanLineStart, cleanLineBidiStatus, endLineLogicalTop);
899
900     if (startLine) {
901         if (!useRepaintBounds) {
902             useRepaintBounds = true;
903             layoutState.setRepaintRange(logicalHeight());
904         }
905         deleteLineRange(layoutState, renderArena(), startLine);
906     }
907
908     InlineIterator end = resolver.position();
909
910     if (!layoutState.isFullLayout() && lastRootBox() && lastRootBox()->endsWithBreak()) {
911         // If the last line before the start line ends with a line break that clear floats,
912         // adjust the height accordingly.
913         // A line break can be either the first or the last object on a line, depending on its direction.
914         if (InlineBox* lastLeafChild = lastRootBox()->lastLeafChild()) {
915             RenderObject* lastObject = lastLeafChild->renderer();
916             if (!lastObject->isBR())
917                 lastObject = lastRootBox()->firstLeafChild()->renderer();
918             if (lastObject->isBR()) {
919                 EClear clear = lastObject->style()->clear();
920                 if (clear != CNONE)
921                     newLine(clear);
922             }
923         }
924     }
925
926     bool endLineMatched = false;
927     bool checkForEndLineMatch = endLine;
928     bool checkForFloatsFromLastLine = false;
929
930     bool paginated = view()->layoutState() && view()->layoutState()->isPaginated();
931
932     LineBreakIteratorInfo lineBreakIteratorInfo;
933     VerticalPositionCache verticalPositionCache;
934
935     LineBreaker lineBreaker(this);
936
937     while (!end.atEnd()) {
938         // FIXME: Is this check necessary before the first iteration or can it be moved to the end?
939         if (checkForEndLineMatch && (endLineMatched = matchedEndLine(layoutState, resolver, cleanLineStart, cleanLineBidiStatus, endLine, endLineLogicalTop)))
940             break;
941
942         lineMidpointState.reset();
943
944         lineInfo.setEmpty(true);
945
946         InlineIterator oldEnd = end;
947         FloatingObject* lastFloatFromPreviousLine = (m_floatingObjects && !m_floatingObjects->set().isEmpty()) ? m_floatingObjects->set().last() : 0;
948         end = lineBreaker.nextLineBreak(resolver, lineInfo, lineBreakIteratorInfo, lastFloatFromPreviousLine);
949         if (resolver.position().atEnd()) {
950             // FIXME: We shouldn't be creating any runs in findNextLineBreak to begin with!
951             // Once BidiRunList is separated from BidiResolver this will not be needed.
952             resolver.runs().deleteRuns();
953             resolver.markCurrentRunEmpty(); // FIXME: This can probably be replaced by an ASSERT (or just removed).
954             checkForFloatsFromLastLine = true;
955             break;
956         }
957         ASSERT(end != resolver.position());
958
959         // This is a short-cut for empty lines.
960         if (lineInfo.isEmpty()) {
961             if (lastRootBox())
962                 lastRootBox()->setLineBreakInfo(end.m_obj, end.m_pos, resolver.status());
963         } else {
964             VisualDirectionOverride override = (style()->visuallyOrdered() ? (style()->direction() == LTR ? VisualLeftToRightOverride : VisualRightToLeftOverride) : NoVisualOverride);
965             // FIXME: This ownership is reversed. We should own the BidiRunList and pass it to createBidiRunsForLine.
966             BidiRunList<BidiRun>& bidiRuns = resolver.runs();
967             resolver.createBidiRunsForLine(end, override, lineInfo.previousLineBrokeCleanly());
968             ASSERT(resolver.position() == end);
969
970             BidiRun* trailingSpaceRun = !lineInfo.previousLineBrokeCleanly() ? handleTrailingSpaces(bidiRuns, resolver.context()) : 0;
971
972             if (bidiRuns.runCount() && lineBreaker.lineWasHyphenated())
973                 bidiRuns.logicallyLastRun()->m_hasHyphen = true;
974
975             // Now that the runs have been ordered, we create the line boxes.
976             // At the same time we figure out where border/padding/margin should be applied for
977             // inline flow boxes.
978
979             int oldLogicalHeight = logicalHeight();
980             RootInlineBox* lineBox = createLineBoxesFromBidiRuns(bidiRuns, end, lineInfo, verticalPositionCache, trailingSpaceRun);
981
982             bidiRuns.deleteRuns();
983             resolver.markCurrentRunEmpty(); // FIXME: This can probably be replaced by an ASSERT (or just removed).
984
985             if (lineBox) {
986                 lineBox->setLineBreakInfo(end.m_obj, end.m_pos, resolver.status());
987                 if (useRepaintBounds)
988                     layoutState.updateRepaintRangeFromBox(lineBox);
989
990                 if (paginated) {
991                     int adjustment = 0;
992                     adjustLinePositionForPagination(lineBox, adjustment);
993                     if (adjustment) {
994                         int oldLineWidth = availableLogicalWidthForLine(oldLogicalHeight, lineInfo.isFirstLine());
995                         lineBox->adjustBlockDirectionPosition(adjustment);
996                         if (useRepaintBounds)
997                             layoutState.updateRepaintRangeFromBox(lineBox);
998
999                         if (availableLogicalWidthForLine(oldLogicalHeight + adjustment, lineInfo.isFirstLine()) != oldLineWidth) {
1000                             // We have to delete this line, remove all floats that got added, and let line layout re-run.
1001                             lineBox->deleteLine(renderArena());
1002                             removeFloatingObjectsBelow(lastFloatFromPreviousLine, oldLogicalHeight);
1003                             setLogicalHeight(oldLogicalHeight + adjustment);
1004                             resolver.setPosition(oldEnd);
1005                             end = oldEnd;
1006                             continue;
1007                         }
1008
1009                         setLogicalHeight(lineBox->blockLogicalHeight());
1010                     }
1011                 }
1012             }
1013
1014             for (size_t i = 0; i < lineBreaker.positionedObjects().size(); ++i)
1015                 setStaticPositions(this, lineBreaker.positionedObjects()[i]);
1016
1017             lineInfo.setFirstLine(false);
1018             newLine(lineBreaker.clear());
1019         }
1020
1021         if (m_floatingObjects && lastRootBox()) {
1022             FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1023             FloatingObjectSetIterator it = floatingObjectSet.begin();
1024             FloatingObjectSetIterator end = floatingObjectSet.end();
1025             if (lastFloat) {
1026                 FloatingObjectSetIterator lastFloatIterator = floatingObjectSet.find(lastFloat);
1027                 ASSERT(lastFloatIterator != end);
1028                 ++lastFloatIterator;
1029                 it = lastFloatIterator;
1030             }
1031             for (; it != end; ++it) {
1032                 FloatingObject* f = *it;
1033                 appendFloatingObjectToLastLine(f);
1034                 ASSERT(f->m_renderer == floats[floatIndex].object);
1035                 // If a float's geometry has changed, give up on syncing with clean lines.
1036                 if (floats[floatIndex].rect != f->frameRect())
1037                     checkForEndLineMatch = false;
1038                 floatIndex++;
1039             }
1040             lastFloat = !floatingObjectSet.isEmpty() ? floatingObjectSet.last() : 0;
1041         }
1042
1043         lineMidpointState.reset();
1044         resolver.setPosition(end);
1045     }
1046
1047     if (endLine) {
1048         if (endLineMatched) {
1049             // Attach all the remaining lines, and then adjust their y-positions as needed.
1050             int delta = logicalHeight() - endLineLogicalTop;
1051             for (RootInlineBox* line = endLine; line; line = line->nextRootBox()) {
1052                 line->attachLine();
1053                 if (paginated) {
1054                     delta -= line->paginationStrut();
1055                     adjustLinePositionForPagination(line, delta);
1056                 }
1057                 if (delta) {
1058                     layoutState.updateRepaintRangeFromBox(line, delta);
1059                     line->adjustBlockDirectionPosition(delta);
1060                 }
1061                 if (Vector<RenderBox*>* cleanLineFloats = line->floatsPtr()) {
1062                     Vector<RenderBox*>::iterator end = cleanLineFloats->end();
1063                     for (Vector<RenderBox*>::iterator f = cleanLineFloats->begin(); f != end; ++f) {
1064                         FloatingObject* floatingObject = insertFloatingObject(*f);
1065                         ASSERT(!floatingObject->m_originatingLine);
1066                         floatingObject->m_originatingLine = line;
1067                         setLogicalHeight(logicalTopForChild(*f) - marginBeforeForChild(*f) + delta);
1068                         positionNewFloats();
1069                     }
1070                 }
1071             }
1072             setLogicalHeight(lastRootBox()->blockLogicalHeight());
1073         } else {
1074             // Delete all the remaining lines.
1075             deleteLineRange(layoutState, renderArena(), endLine);
1076         }
1077     }
1078     if (m_floatingObjects && (checkForFloatsFromLastLine || positionNewFloats()) && lastRootBox()) {
1079         // In case we have a float on the last line, it might not be positioned up to now.
1080         // This has to be done before adding in the bottom border/padding, or the float will
1081         // include the padding incorrectly. -dwh
1082         if (checkForFloatsFromLastLine) {
1083             int bottomVisualOverflow = lastRootBox()->logicalBottomVisualOverflow();
1084             int bottomLayoutOverflow = lastRootBox()->logicalBottomLayoutOverflow();
1085             TrailingFloatsRootInlineBox* trailingFloatsLineBox = new (renderArena()) TrailingFloatsRootInlineBox(this);
1086             m_lineBoxes.appendLineBox(trailingFloatsLineBox);
1087             trailingFloatsLineBox->setConstructed();
1088             GlyphOverflowAndFallbackFontsMap textBoxDataMap;
1089             VerticalPositionCache verticalPositionCache;
1090             trailingFloatsLineBox->alignBoxesInBlockDirection(logicalHeight(), textBoxDataMap, verticalPositionCache);
1091             int blockLogicalHeight = logicalHeight();
1092             IntRect logicalLayoutOverflow(0, blockLogicalHeight, 1, bottomLayoutOverflow - blockLogicalHeight);
1093             IntRect logicalVisualOverflow(0, blockLogicalHeight, 1, bottomVisualOverflow - blockLogicalHeight);
1094             trailingFloatsLineBox->setOverflowFromLogicalRects(logicalLayoutOverflow, logicalVisualOverflow, trailingFloatsLineBox->lineTop(), trailingFloatsLineBox->lineBottom());
1095             trailingFloatsLineBox->setBlockLogicalHeight(logicalHeight());
1096         }
1097
1098         FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1099         FloatingObjectSetIterator it = floatingObjectSet.begin();
1100         FloatingObjectSetIterator end = floatingObjectSet.end();
1101         if (lastFloat) {
1102             FloatingObjectSetIterator lastFloatIterator = floatingObjectSet.find(lastFloat);
1103             ASSERT(lastFloatIterator != end);
1104             ++lastFloatIterator;
1105             it = lastFloatIterator;
1106         }
1107         for (; it != end; ++it)
1108             appendFloatingObjectToLastLine(*it);
1109         lastFloat = !floatingObjectSet.isEmpty() ? floatingObjectSet.last() : 0;
1110     }
1111     size_t floatCount = floats.size();
1112     // Floats that did not have layout did not repaint when we laid them out. They would have
1113     // painted by now if they had moved, but if they stayed at (0, 0), they still need to be
1114     // painted.
1115     for (size_t i = 0; i < floatCount; ++i) {
1116         if (!floats[i].everHadLayout) {
1117             RenderBox* f = floats[i].object;
1118             if (!f->x() && !f->y() && f->checkForRepaintDuringLayout())
1119                 f->repaint();
1120         }
1121     }
1122 }
1123
1124 void RenderBlock::layoutInlineChildren(bool relayoutChildren, int& repaintLogicalTop, int& repaintLogicalBottom)
1125 {
1126     m_overflow.clear();
1127
1128     setLogicalHeight(borderBefore() + paddingBefore());
1129
1130     // Figure out if we should clear out our line boxes.
1131     // FIXME: Handle resize eventually!
1132     bool isFullLayout = !firstLineBox() || selfNeedsLayout() || relayoutChildren;
1133     LineLayoutState layoutState(isFullLayout, repaintLogicalTop, repaintLogicalBottom);
1134
1135     if (isFullLayout)
1136         lineBoxes()->deleteLineBoxes(renderArena());
1137
1138     // Text truncation only kicks in if your overflow isn't visible and your text-overflow-mode isn't
1139     // clip.
1140     // FIXME: CSS3 says that descendants that are clipped must also know how to truncate.  This is insanely
1141     // difficult to figure out (especially in the middle of doing layout), and is really an esoteric pile of nonsense
1142     // anyway, so we won't worry about following the draft here.
1143     bool hasTextOverflow = style()->textOverflow() && hasOverflowClip();
1144
1145     // Walk all the lines and delete our ellipsis line boxes if they exist.
1146     if (hasTextOverflow)
1147          deleteEllipsisLineBoxes();
1148
1149     if (firstChild()) {
1150         // layout replaced elements
1151         bool endOfInline = false;
1152         RenderObject* o = bidiFirstNotSkippingInlines(this);
1153         Vector<FloatWithRect> floats;
1154         bool hasInlineChild = false;
1155         while (o) {
1156             if (!hasInlineChild && o->isInline())
1157                 hasInlineChild = true;
1158
1159             if (o->isReplaced() || o->isFloating() || o->isPositioned()) {
1160                 RenderBox* box = toRenderBox(o);
1161
1162                 if (relayoutChildren || o->style()->width().isPercent() || o->style()->height().isPercent())
1163                     o->setChildNeedsLayout(true, false);
1164
1165                 // If relayoutChildren is set and we have percentage padding, we also need to invalidate the child's pref widths.
1166                 if (relayoutChildren && (o->style()->paddingStart().isPercent() || o->style()->paddingEnd().isPercent()))
1167                     o->setPreferredLogicalWidthsDirty(true, false);
1168
1169                 if (o->isPositioned())
1170                     o->containingBlock()->insertPositionedObject(box);
1171                 else if (o->isFloating())
1172                     floats.append(FloatWithRect(box));
1173                 else if (layoutState.isFullLayout() || o->needsLayout()) {
1174                     // Replaced elements
1175                     toRenderBox(o)->dirtyLineBoxes(layoutState.isFullLayout());
1176                     o->layoutIfNeeded();
1177                 }
1178             } else if (o->isText() || (o->isRenderInline() && !endOfInline)) {
1179                 if (!o->isText())
1180                     toRenderInline(o)->updateAlwaysCreateLineBoxes();
1181                 if (layoutState.isFullLayout() || o->selfNeedsLayout())
1182                     dirtyLineBoxesForRenderer(o, layoutState.isFullLayout());
1183                 o->setNeedsLayout(false);
1184             }
1185             o = bidiNext(this, o, 0, false, &endOfInline);
1186         }
1187
1188         layoutRunsAndFloats(layoutState, hasInlineChild, floats);
1189     }
1190
1191     // Expand the last line to accommodate Ruby and emphasis marks.
1192     int lastLineAnnotationsAdjustment = 0;
1193     if (lastRootBox()) {
1194         int lowestAllowedPosition = max(lastRootBox()->lineBottom(), logicalHeight() + paddingAfter());
1195         if (!style()->isFlippedLinesWritingMode())
1196             lastLineAnnotationsAdjustment = lastRootBox()->computeUnderAnnotationAdjustment(lowestAllowedPosition);
1197         else
1198             lastLineAnnotationsAdjustment = lastRootBox()->computeOverAnnotationAdjustment(lowestAllowedPosition);
1199     }
1200
1201     // Now add in the bottom border/padding.
1202     setLogicalHeight(logicalHeight() + lastLineAnnotationsAdjustment + borderAfter() + paddingAfter() + scrollbarLogicalHeight());
1203
1204     if (!firstLineBox() && hasLineIfEmpty())
1205         setLogicalHeight(logicalHeight() + lineHeight(true, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes));
1206
1207     // See if we have any lines that spill out of our block.  If we do, then we will possibly need to
1208     // truncate text.
1209     if (hasTextOverflow)
1210         checkLinesForTextOverflow();
1211 }
1212
1213 void RenderBlock::checkFloatsInCleanLine(RootInlineBox* line, Vector<FloatWithRect>& floats, size_t& floatIndex, bool& encounteredNewFloat, bool& dirtiedByFloat)
1214 {
1215     Vector<RenderBox*>* cleanLineFloats = line->floatsPtr();
1216     if (!cleanLineFloats)
1217         return;
1218
1219     Vector<RenderBox*>::iterator end = cleanLineFloats->end();
1220     for (Vector<RenderBox*>::iterator it = cleanLineFloats->begin(); it != end; ++it) {
1221         RenderBox* floatingBox = *it;
1222         floatingBox->layoutIfNeeded();
1223         IntSize newSize(floatingBox->width() + floatingBox->marginLeft() + floatingBox->marginRight(), floatingBox->height() + floatingBox->marginTop() + floatingBox->marginBottom());
1224         ASSERT(floatIndex < floats.size());
1225         if (floats[floatIndex].object != floatingBox) {
1226             encounteredNewFloat = true;
1227             return;
1228         }
1229
1230         if (floats[floatIndex].rect.size() != newSize) {
1231             int floatTop = isHorizontalWritingMode() ? floats[floatIndex].rect.y() : floats[floatIndex].rect.x();
1232             int floatHeight = isHorizontalWritingMode() ? max(floats[floatIndex].rect.height(), newSize.height())
1233                                                                  : max(floats[floatIndex].rect.width(), newSize.width());
1234             floatHeight = min(floatHeight, numeric_limits<int>::max() - floatTop);
1235             line->markDirty();
1236             markLinesDirtyInBlockRange(line->blockLogicalHeight(), floatTop + floatHeight, line);
1237             floats[floatIndex].rect.setSize(newSize);
1238             dirtiedByFloat = true;
1239         }
1240         floatIndex++;
1241     }
1242 }
1243
1244 RootInlineBox* RenderBlock::determineStartPosition(LineLayoutState& layoutState, LineInfo& lineInfo, InlineBidiResolver& resolver, Vector<FloatWithRect>& floats,
1245                                                    unsigned& numCleanFloats, bool& useRepaintBounds)
1246 {
1247     RootInlineBox* curr = 0;
1248     RootInlineBox* last = 0;
1249
1250     // FIXME: This entire float-checking block needs to be broken into a new function.
1251     bool dirtiedByFloat = false;
1252     if (!layoutState.isFullLayout()) {
1253         // Paginate all of the clean lines.
1254         bool paginated = view()->layoutState() && view()->layoutState()->isPaginated();
1255         int paginationDelta = 0;
1256         size_t floatIndex = 0;
1257         for (curr = firstRootBox(); curr && !curr->isDirty(); curr = curr->nextRootBox()) {
1258             if (paginated) {
1259                 paginationDelta -= curr->paginationStrut();
1260                 adjustLinePositionForPagination(curr, paginationDelta);
1261                 if (paginationDelta) {
1262                     if (containsFloats() || !floats.isEmpty()) {
1263                         // FIXME: Do better eventually.  For now if we ever shift because of pagination and floats are present just go to a full layout.
1264                         layoutState.markForFullLayout();
1265                         break;
1266                     }
1267
1268                     if (!useRepaintBounds)
1269                         useRepaintBounds = true;
1270
1271                     layoutState.updateRepaintRangeFromBox(curr, paginationDelta);
1272                     curr->adjustBlockDirectionPosition(paginationDelta);
1273                 }
1274             }
1275
1276             // If a new float has been inserted before this line or before its last known float, just do a full layout.
1277             bool encounteredNewFloat = false;
1278             checkFloatsInCleanLine(curr, floats, floatIndex, encounteredNewFloat, dirtiedByFloat);
1279             if (encounteredNewFloat)
1280                 layoutState.markForFullLayout();
1281
1282             if (dirtiedByFloat || layoutState.isFullLayout())
1283                 break;
1284         }
1285         // Check if a new float has been inserted after the last known float.
1286         if (!curr && floatIndex < floats.size())
1287             layoutState.markForFullLayout();
1288     }
1289
1290     if (layoutState.isFullLayout()) {
1291         // FIXME: This should just call deleteLineBoxTree, but that causes
1292         // crashes for fast/repaint tests.
1293         RenderArena* arena = renderArena();
1294         curr = firstRootBox();
1295         while (curr) {
1296             // Note: This uses nextRootBox() insted of nextLineBox() like deleteLineBoxTree does.
1297             RootInlineBox* next = curr->nextRootBox();
1298             curr->deleteLine(arena);
1299             curr = next;
1300         }
1301         ASSERT(!firstLineBox() && !lastLineBox());
1302     } else {
1303         if (curr) {
1304             // We have a dirty line.
1305             if (RootInlineBox* prevRootBox = curr->prevRootBox()) {
1306                 // We have a previous line.
1307                 if (!dirtiedByFloat && (!prevRootBox->endsWithBreak() || (prevRootBox->lineBreakObj()->isText() && prevRootBox->lineBreakPos() >= toRenderText(prevRootBox->lineBreakObj())->textLength())))
1308                     // The previous line didn't break cleanly or broke at a newline
1309                     // that has been deleted, so treat it as dirty too.
1310                     curr = prevRootBox;
1311             }
1312         } else {
1313             // No dirty lines were found.
1314             // If the last line didn't break cleanly, treat it as dirty.
1315             if (lastRootBox() && !lastRootBox()->endsWithBreak())
1316                 curr = lastRootBox();
1317         }
1318
1319         // If we have no dirty lines, then last is just the last root box.
1320         last = curr ? curr->prevRootBox() : lastRootBox();
1321     }
1322
1323     numCleanFloats = 0;
1324     if (!floats.isEmpty()) {
1325         int savedLogicalHeight = logicalHeight();
1326         // Restore floats from clean lines.
1327         RootInlineBox* line = firstRootBox();
1328         while (line != curr) {
1329             if (Vector<RenderBox*>* cleanLineFloats = line->floatsPtr()) {
1330                 Vector<RenderBox*>::iterator end = cleanLineFloats->end();
1331                 for (Vector<RenderBox*>::iterator f = cleanLineFloats->begin(); f != end; ++f) {
1332                     FloatingObject* floatingObject = insertFloatingObject(*f);
1333                     ASSERT(!floatingObject->m_originatingLine);
1334                     floatingObject->m_originatingLine = line;
1335                     setLogicalHeight(logicalTopForChild(*f) - marginBeforeForChild(*f));
1336                     positionNewFloats();
1337                     ASSERT(floats[numCleanFloats].object == *f);
1338                     numCleanFloats++;
1339                 }
1340             }
1341             line = line->nextRootBox();
1342         }
1343         setLogicalHeight(savedLogicalHeight);
1344     }
1345
1346     lineInfo.setFirstLine(!last);
1347     lineInfo.setPreviousLineBrokeCleanly(!last || last->endsWithBreak());
1348
1349     if (last) {
1350         setLogicalHeight(last->blockLogicalHeight());
1351         resolver.setPosition(InlineIterator(this, last->lineBreakObj(), last->lineBreakPos()));
1352         resolver.setStatus(last->lineBreakBidiStatus());
1353     } else {
1354         resolver.setStatus(BidiStatus(style()->direction(), style()->unicodeBidi() == Override));
1355         resolver.setPosition(InlineIterator(this, bidiFirstSkippingInlines(this, &resolver), 0));
1356     }
1357     return curr;
1358 }
1359
1360 RootInlineBox* RenderBlock::determineEndPosition(RootInlineBox* startLine, Vector<FloatWithRect>& floats, size_t floatIndex, InlineIterator& cleanLineStart, BidiStatus& cleanLineBidiStatus, int& logicalTop)
1361 {
1362     RootInlineBox* last = 0;
1363     for (RootInlineBox* curr = startLine->nextRootBox(); curr; curr = curr->nextRootBox()) {
1364         if (!curr->isDirty()) {
1365             bool encounteredNewFloat = false;
1366             bool dirtiedByFloat = false;
1367             checkFloatsInCleanLine(curr, floats, floatIndex, encounteredNewFloat, dirtiedByFloat);
1368             if (encounteredNewFloat)
1369                 return 0;
1370         }
1371         if (curr->isDirty())
1372             last = 0;
1373         else if (!last)
1374             last = curr;
1375     }
1376
1377     if (!last)
1378         return 0;
1379
1380     // At this point, |last| is the first line in a run of clean lines that ends with the last line
1381     // in the block.
1382
1383     RootInlineBox* prev = last->prevRootBox();
1384     cleanLineStart = InlineIterator(this, prev->lineBreakObj(), prev->lineBreakPos());
1385     cleanLineBidiStatus = prev->lineBreakBidiStatus();
1386     logicalTop = prev->blockLogicalHeight();
1387
1388     for (RootInlineBox* line = last; line; line = line->nextRootBox())
1389         line->extractLine(); // Disconnect all line boxes from their render objects while preserving
1390                              // their connections to one another.
1391
1392     return last;
1393 }
1394
1395 bool RenderBlock::matchedEndLine(LineLayoutState& layoutState, const InlineBidiResolver& resolver, const InlineIterator& endLineStart, const BidiStatus& endLineStatus, RootInlineBox*& endLine, int& endLogicalTop)
1396 {
1397     if (resolver.position() == endLineStart) {
1398         if (resolver.status() != endLineStatus)
1399             return false;
1400
1401         int delta = logicalHeight() - endLogicalTop;
1402         if (!delta || !m_floatingObjects)
1403             return true;
1404
1405         // See if any floats end in the range along which we want to shift the lines vertically.
1406         int logicalTop = min(logicalHeight(), endLogicalTop);
1407
1408         RootInlineBox* lastLine = endLine;
1409         while (RootInlineBox* nextLine = lastLine->nextRootBox())
1410             lastLine = nextLine;
1411
1412         int logicalBottom = lastLine->blockLogicalHeight() + abs(delta);
1413
1414         FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1415         FloatingObjectSetIterator end = floatingObjectSet.end();
1416         for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1417             FloatingObject* f = *it;
1418             if (logicalBottomForFloat(f) >= logicalTop && logicalBottomForFloat(f) < logicalBottom)
1419                 return false;
1420         }
1421
1422         return true;
1423     }
1424
1425     // The first clean line doesn't match, but we can check a handful of following lines to try
1426     // to match back up.
1427     static int numLines = 8; // The # of lines we're willing to match against.
1428     RootInlineBox* line = endLine;
1429     for (int i = 0; i < numLines && line; i++, line = line->nextRootBox()) {
1430         if (line->lineBreakObj() == resolver.position().m_obj && line->lineBreakPos() == resolver.position().m_pos) {
1431             // We have a match.
1432             if (line->lineBreakBidiStatus() != resolver.status())
1433                 return false; // ...but the bidi state doesn't match.
1434             RootInlineBox* result = line->nextRootBox();
1435
1436             // Set our logical top to be the block height of endLine.
1437             if (result)
1438                 endLogicalTop = line->blockLogicalHeight();
1439
1440             int delta = logicalHeight() - endLogicalTop;
1441             if (delta && m_floatingObjects) {
1442                 // See if any floats end in the range along which we want to shift the lines vertically.
1443                 int logicalTop = min(logicalHeight(), endLogicalTop);
1444
1445                 RootInlineBox* lastLine = endLine;
1446                 while (RootInlineBox* nextLine = lastLine->nextRootBox())
1447                     lastLine = nextLine;
1448
1449                 int logicalBottom = lastLine->blockLogicalHeight() + abs(delta);
1450
1451                 FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1452                 FloatingObjectSetIterator end = floatingObjectSet.end();
1453                 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1454                     FloatingObject* f = *it;
1455                     if (logicalBottomForFloat(f) >= logicalTop && logicalBottomForFloat(f) < logicalBottom)
1456                         return false;
1457                 }
1458             }
1459
1460             // Now delete the lines that we failed to sync.
1461             deleteLineRange(layoutState, renderArena(), endLine, result);
1462             endLine = result;
1463             return result;
1464         }
1465     }
1466
1467     return false;
1468 }
1469
1470 static inline bool skipNonBreakingSpace(const InlineIterator& it, const LineInfo& lineInfo)
1471 {
1472     if (it.m_obj->style()->nbspMode() != SPACE || it.current() != noBreakSpace)
1473         return false;
1474
1475     // FIXME: This is bad.  It makes nbsp inconsistent with space and won't work correctly
1476     // with m_minWidth/m_maxWidth.
1477     // Do not skip a non-breaking space if it is the first character
1478     // on a line after a clean line break (or on the first line, since previousLineBrokeCleanly starts off
1479     // |true|).
1480     if (lineInfo.isEmpty() && lineInfo.previousLineBrokeCleanly())
1481         return false;
1482
1483     return true;
1484 }
1485
1486 static inline bool shouldCollapseWhiteSpace(const RenderStyle* style, const LineInfo& lineInfo)
1487 {
1488     return style->collapseWhiteSpace() || (style->whiteSpace() == PRE_WRAP && (!lineInfo.isEmpty() || !lineInfo.previousLineBrokeCleanly()));
1489 }
1490
1491 static bool inlineFlowRequiresLineBox(RenderInline* flow)
1492 {
1493     // FIXME: Right now, we only allow line boxes for inlines that are truly empty.
1494     // We need to fix this, though, because at the very least, inlines containing only
1495     // ignorable whitespace should should also have line boxes.
1496     return !flow->firstChild() && flow->hasInlineDirectionBordersPaddingOrMargin();
1497 }
1498
1499 static bool requiresLineBox(const InlineIterator& it, const LineInfo& lineInfo = LineInfo())
1500 {
1501     if (it.m_obj->isFloatingOrPositioned())
1502         return false;
1503
1504     if (it.m_obj->isRenderInline() && !inlineFlowRequiresLineBox(toRenderInline(it.m_obj)))
1505         return false;
1506
1507     if (!shouldCollapseWhiteSpace(it.m_obj->style(), lineInfo) || it.m_obj->isBR())
1508         return true;
1509
1510     UChar current = it.current();
1511     return current != ' ' && current != '\t' && current != softHyphen && (current != '\n' || it.m_obj->preservesNewline())
1512     && !skipNonBreakingSpace(it, lineInfo);
1513 }
1514
1515 bool RenderBlock::generatesLineBoxesForInlineChild(RenderObject* inlineObj)
1516 {
1517     ASSERT(inlineObj->parent() == this);
1518
1519     InlineIterator it(this, inlineObj, 0);
1520     while (!it.atEnd() && !requiresLineBox(it))
1521         it.increment();
1522
1523     return !it.atEnd();
1524 }
1525
1526 // FIXME: The entire concept of the skipTrailingWhitespace function is flawed, since we really need to be building
1527 // line boxes even for containers that may ultimately collapse away. Otherwise we'll never get positioned
1528 // elements quite right. In other words, we need to build this function's work into the normal line
1529 // object iteration process.
1530 // NB. this function will insert any floating elements that would otherwise
1531 // be skipped but it will not position them.
1532 void RenderBlock::LineBreaker::skipTrailingWhitespace(InlineIterator& iterator, const LineInfo& lineInfo)
1533 {
1534     while (!iterator.atEnd() && !requiresLineBox(iterator, lineInfo)) {
1535         RenderObject* object = iterator.m_obj;
1536         if (object->isFloating()) {
1537             m_block->insertFloatingObject(toRenderBox(object));
1538         } else if (object->isPositioned())
1539             setStaticPositions(m_block, toRenderBox(object));
1540         iterator.increment();
1541     }
1542 }
1543
1544 void RenderBlock::LineBreaker::skipLeadingWhitespace(InlineBidiResolver& resolver, const LineInfo& lineInfo,
1545                                                      FloatingObject* lastFloatFromPreviousLine, LineWidth& width)
1546 {
1547     while (!resolver.position().atEnd() && !requiresLineBox(resolver.position(), lineInfo)) {
1548         RenderObject* object = resolver.position().m_obj;
1549         if (object->isFloating())
1550             m_block->positionNewFloatOnLine(m_block->insertFloatingObject(toRenderBox(object)), lastFloatFromPreviousLine, width);
1551         else if (object->isPositioned())
1552             setStaticPositions(m_block, toRenderBox(object));
1553         resolver.increment();
1554     }
1555     resolver.commitExplicitEmbedding();
1556 }
1557
1558 // This is currently just used for list markers and inline flows that have line boxes. Neither should
1559 // have an effect on whitespace at the start of the line.
1560 static bool shouldSkipWhitespaceAfterStartObject(RenderBlock* block, RenderObject* o, LineMidpointState& lineMidpointState)
1561 {
1562     RenderObject* next = bidiNext(block, o);
1563     if (next && !next->isBR() && next->isText() && toRenderText(next)->textLength() > 0) {
1564         RenderText* nextText = toRenderText(next);
1565         UChar nextChar = nextText->characters()[0];
1566         if (nextText->style()->isCollapsibleWhiteSpace(nextChar)) {
1567             addMidpoint(lineMidpointState, InlineIterator(0, o, 0));
1568             return true;
1569         }
1570     }
1571
1572     return false;
1573 }
1574
1575 static inline float textWidth(RenderText* text, unsigned from, unsigned len, const Font& font, float xPos, bool isFixedPitch, bool collapseWhiteSpace)
1576 {
1577     if (isFixedPitch || (!from && len == text->textLength()) || text->style()->hasTextCombine())
1578         return text->width(from, len, font, xPos);
1579     return font.width(TextRun(text->characters() + from, len, !collapseWhiteSpace, xPos));
1580 }
1581
1582 static void tryHyphenating(RenderText* text, const Font& font, const AtomicString& localeIdentifier, int minimumPrefixLength, int minimumSuffixLength, int lastSpace, int pos, float xPos, int availableWidth, bool isFixedPitch, bool collapseWhiteSpace, int lastSpaceWordSpacing, InlineIterator& lineBreak, int nextBreakable, bool& hyphenated)
1583 {
1584     // Map 'hyphenate-limit-{before,after}: auto;' to 2.
1585     if (minimumPrefixLength < 0)
1586         minimumPrefixLength = 2;
1587
1588     if (minimumSuffixLength < 0)
1589         minimumSuffixLength = 2;
1590
1591     if (pos - lastSpace <= minimumSuffixLength)
1592         return;
1593
1594     const AtomicString& hyphenString = text->style()->hyphenString();
1595     int hyphenWidth = font.width(TextRun(hyphenString.characters(), hyphenString.length()));
1596
1597     float maxPrefixWidth = availableWidth - xPos - hyphenWidth - lastSpaceWordSpacing;
1598     // If the maximum width available for the prefix before the hyphen is small, then it is very unlikely
1599     // that an hyphenation opportunity exists, so do not bother to look for it.
1600     if (maxPrefixWidth <= font.pixelSize() * 5 / 4)
1601         return;
1602
1603     unsigned prefixLength = font.offsetForPosition(TextRun(text->characters() + lastSpace, pos - lastSpace, !collapseWhiteSpace, xPos + lastSpaceWordSpacing), maxPrefixWidth, false);
1604     if (prefixLength < static_cast<unsigned>(minimumPrefixLength))
1605         return;
1606
1607     prefixLength = lastHyphenLocation(text->characters() + lastSpace, pos - lastSpace, min(prefixLength, static_cast<unsigned>(pos - lastSpace - minimumSuffixLength)) + 1, localeIdentifier);
1608     // FIXME: The following assumes that the character at lastSpace is a space (and therefore should not factor
1609     // into hyphenate-limit-before) unless lastSpace is 0. This is wrong in the rare case of hyphenating
1610     // the first word in a text node which has leading whitespace.
1611     if (!prefixLength || prefixLength - (lastSpace ? 1 : 0) < static_cast<unsigned>(minimumPrefixLength))
1612         return;
1613
1614     ASSERT(pos - lastSpace - prefixLength >= static_cast<unsigned>(minimumSuffixLength));
1615
1616 #if !ASSERT_DISABLED
1617     float prefixWidth = hyphenWidth + textWidth(text, lastSpace, prefixLength, font, xPos, isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing;
1618     ASSERT(xPos + prefixWidth <= availableWidth);
1619 #else
1620     UNUSED_PARAM(isFixedPitch);
1621 #endif
1622
1623     lineBreak.moveTo(text, lastSpace + prefixLength, nextBreakable);
1624     hyphenated = true;
1625 }
1626
1627 class LineWidth {
1628 public:
1629     LineWidth(RenderBlock* block, bool isFirstLine)
1630         : m_block(block)
1631         , m_uncommittedWidth(0)
1632         , m_committedWidth(0)
1633         , m_overhangWidth(0)
1634         , m_left(0)
1635         , m_right(0)
1636         , m_availableWidth(0)
1637         , m_isFirstLine(isFirstLine)
1638     {
1639         ASSERT(block);
1640         updateAvailableWidth();
1641     }
1642     bool fitsOnLine() const { return currentWidth() <= m_availableWidth; }
1643     bool fitsOnLine(float extra) const { return currentWidth() + extra <= m_availableWidth; }
1644     float currentWidth() const { return m_committedWidth + m_uncommittedWidth; }
1645
1646     // FIXME: We should eventually replace these three functions by ones that work on a higher abstraction.
1647     float uncommittedWidth() const { return m_uncommittedWidth; }
1648     float committedWidth() const { return m_committedWidth; }
1649     float availableWidth() const { return m_availableWidth; }
1650
1651     void updateAvailableWidth();
1652     void shrinkAvailableWidthForNewFloatIfNeeded(RenderBlock::FloatingObject*);
1653     void addUncommittedWidth(float delta) { m_uncommittedWidth += delta; }
1654     void commit()
1655     {
1656         m_committedWidth += m_uncommittedWidth;
1657         m_uncommittedWidth = 0;
1658     }
1659     void applyOverhang(RenderRubyRun*, RenderObject* startRenderer, RenderObject* endRenderer);
1660     void fitBelowFloats();
1661
1662 private:
1663     void computeAvailableWidthFromLeftAndRight()
1664     {
1665         m_availableWidth = max(0, m_right - m_left) + m_overhangWidth;
1666     }
1667
1668 private:
1669     RenderBlock* m_block;
1670     float m_uncommittedWidth;
1671     float m_committedWidth;
1672     float m_overhangWidth; // The amount by which |m_availableWidth| has been inflated to account for possible contraction due to ruby overhang.
1673     int m_left;
1674     int m_right;
1675     float m_availableWidth;
1676     bool m_isFirstLine;
1677 };
1678
1679 inline void LineWidth::updateAvailableWidth()
1680 {
1681     int height = m_block->logicalHeight();
1682     m_left = m_block->logicalLeftOffsetForLine(height, m_isFirstLine);
1683     m_right = m_block->logicalRightOffsetForLine(height, m_isFirstLine);
1684
1685     computeAvailableWidthFromLeftAndRight();
1686 }
1687
1688 inline void LineWidth::shrinkAvailableWidthForNewFloatIfNeeded(RenderBlock::FloatingObject* newFloat)
1689 {
1690     int height = m_block->logicalHeight();
1691     if (height < m_block->logicalTopForFloat(newFloat) || height >= m_block->logicalBottomForFloat(newFloat))
1692         return;
1693
1694     if (newFloat->type() == RenderBlock::FloatingObject::FloatLeft)
1695         m_left = m_block->logicalRightForFloat(newFloat);
1696     else
1697         m_right = m_block->logicalLeftForFloat(newFloat);
1698
1699     computeAvailableWidthFromLeftAndRight();
1700 }
1701
1702 void LineWidth::applyOverhang(RenderRubyRun* rubyRun, RenderObject* startRenderer, RenderObject* endRenderer)
1703 {
1704     int startOverhang;
1705     int endOverhang;
1706     rubyRun->getOverhang(m_isFirstLine, startRenderer, endRenderer, startOverhang, endOverhang);
1707
1708     startOverhang = min<int>(startOverhang, m_committedWidth);
1709     m_availableWidth += startOverhang;
1710
1711     endOverhang = max(min<int>(endOverhang, m_availableWidth - currentWidth()), 0);
1712     m_availableWidth += endOverhang;
1713     m_overhangWidth += startOverhang + endOverhang;
1714 }
1715
1716 void LineWidth::fitBelowFloats()
1717 {
1718     ASSERT(!m_committedWidth);
1719     ASSERT(!fitsOnLine());
1720
1721     int floatLogicalBottom;
1722     int lastFloatLogicalBottom = m_block->logicalHeight();
1723     float newLineWidth = m_availableWidth;
1724     while (true) {
1725         floatLogicalBottom = m_block->nextFloatLogicalBottomBelow(lastFloatLogicalBottom);
1726         if (!floatLogicalBottom)
1727             break;
1728
1729         newLineWidth = m_block->availableLogicalWidthForLine(floatLogicalBottom, m_isFirstLine);
1730         lastFloatLogicalBottom = floatLogicalBottom;
1731         if (newLineWidth >= m_uncommittedWidth)
1732             break;
1733     }
1734
1735     if (newLineWidth > m_availableWidth) {
1736         m_block->setLogicalHeight(lastFloatLogicalBottom);
1737         m_availableWidth = newLineWidth + m_overhangWidth;
1738     }
1739 }
1740
1741 class TrailingObjects {
1742 public:
1743     TrailingObjects();
1744     void setTrailingWhitespace(RenderText*);
1745     void clear();
1746     void appendBoxIfNeeded(RenderBox*);
1747
1748     enum CollapseFirstSpaceOrNot { DoNotCollapseFirstSpace, CollapseFirstSpace };
1749
1750     void updateMidpointsForTrailingBoxes(LineMidpointState&, const InlineIterator& lBreak, CollapseFirstSpaceOrNot);
1751
1752 private:
1753     RenderText* m_whitespace;
1754     Vector<RenderBox*, 4> m_boxes;
1755 };
1756
1757 TrailingObjects::TrailingObjects()
1758     : m_whitespace(0)
1759 {
1760 }
1761
1762 inline void TrailingObjects::setTrailingWhitespace(RenderText* whitespace)
1763 {
1764     ASSERT(whitespace);
1765     m_whitespace = whitespace;
1766 }
1767
1768 inline void TrailingObjects::clear()
1769 {
1770     m_whitespace = 0;
1771     m_boxes.clear();
1772 }
1773
1774 inline void TrailingObjects::appendBoxIfNeeded(RenderBox* box)
1775 {
1776     if (m_whitespace)
1777         m_boxes.append(box);
1778 }
1779
1780 void TrailingObjects::updateMidpointsForTrailingBoxes(LineMidpointState& lineMidpointState, const InlineIterator& lBreak, CollapseFirstSpaceOrNot collapseFirstSpace)
1781 {
1782     if (!m_whitespace)
1783         return;
1784
1785     // This object is either going to be part of the last midpoint, or it is going to be the actual endpoint.
1786     // In both cases we just decrease our pos by 1 level to exclude the space, allowing it to - in effect - collapse into the newline.
1787     if (lineMidpointState.numMidpoints % 2) {
1788         // Find the trailing space object's midpoint.
1789         int trailingSpaceMidpoint = lineMidpointState.numMidpoints - 1;
1790         for ( ; trailingSpaceMidpoint >= 0 && lineMidpointState.midpoints[trailingSpaceMidpoint].m_obj != m_whitespace; --trailingSpaceMidpoint) { }
1791         ASSERT(trailingSpaceMidpoint >= 0);
1792         if (collapseFirstSpace == CollapseFirstSpace)
1793             lineMidpointState.midpoints[trailingSpaceMidpoint].m_pos--;
1794
1795         // Now make sure every single trailingPositionedBox following the trailingSpaceMidpoint properly stops and starts
1796         // ignoring spaces.
1797         size_t currentMidpoint = trailingSpaceMidpoint + 1;
1798         for (size_t i = 0; i < m_boxes.size(); ++i) {
1799             if (currentMidpoint >= lineMidpointState.numMidpoints) {
1800                 // We don't have a midpoint for this box yet.
1801                 InlineIterator ignoreStart(0, m_boxes[i], 0);
1802                 addMidpoint(lineMidpointState, ignoreStart); // Stop ignoring.
1803                 addMidpoint(lineMidpointState, ignoreStart); // Start ignoring again.
1804             } else {
1805                 ASSERT(lineMidpointState.midpoints[currentMidpoint].m_obj == m_boxes[i]);
1806                 ASSERT(lineMidpointState.midpoints[currentMidpoint + 1].m_obj == m_boxes[i]);
1807             }
1808             currentMidpoint += 2;
1809         }
1810     } else if (!lBreak.m_obj) {
1811         ASSERT(m_whitespace->isText());
1812         ASSERT(collapseFirstSpace == CollapseFirstSpace);
1813         // Add a new end midpoint that stops right at the very end.
1814         unsigned length = m_whitespace->textLength();
1815         unsigned pos = length >= 2 ? length - 2 : UINT_MAX;
1816         InlineIterator endMid(0, m_whitespace, pos);
1817         addMidpoint(lineMidpointState, endMid);
1818         for (size_t i = 0; i < m_boxes.size(); ++i) {
1819             InlineIterator ignoreStart(0, m_boxes[i], 0);
1820             addMidpoint(lineMidpointState, ignoreStart); // Stop ignoring spaces.
1821             addMidpoint(lineMidpointState, ignoreStart); // Start ignoring again.
1822         }
1823     }
1824 }
1825
1826 void RenderBlock::LineBreaker::reset()
1827 {
1828     m_positionedObjects.clear();
1829     m_hyphenated = false;
1830     m_clear = CNONE;
1831 }
1832
1833 InlineIterator RenderBlock::LineBreaker::nextLineBreak(InlineBidiResolver& resolver, LineInfo& lineInfo,
1834     LineBreakIteratorInfo& lineBreakIteratorInfo, FloatingObject* lastFloatFromPreviousLine)
1835 {
1836     reset();
1837
1838     ASSERT(resolver.position().root() == m_block);
1839
1840     bool appliedStartWidth = resolver.position().m_pos > 0;
1841     LineMidpointState& lineMidpointState = resolver.midpointState();
1842
1843     LineWidth width(m_block, lineInfo.isFirstLine());
1844
1845     skipLeadingWhitespace(resolver, lineInfo, lastFloatFromPreviousLine, width);
1846
1847     if (resolver.position().atEnd())
1848         return resolver.position();
1849
1850     // This variable is used only if whitespace isn't set to PRE, and it tells us whether
1851     // or not we are currently ignoring whitespace.
1852     bool ignoringSpaces = false;
1853     InlineIterator ignoreStart;
1854
1855     // This variable tracks whether the very last character we saw was a space.  We use
1856     // this to detect when we encounter a second space so we know we have to terminate
1857     // a run.
1858     bool currentCharacterIsSpace = false;
1859     bool currentCharacterIsWS = false;
1860     TrailingObjects trailingObjects;
1861
1862     InlineIterator lBreak = resolver.position();
1863
1864     // FIXME: It is error-prone to split the position object out like this.
1865     // Teach this code to work with objects instead of this split tuple.
1866     InlineIterator current = resolver.position();
1867     RenderObject* last = current.m_obj;
1868     bool atStart = true;
1869
1870     bool startingNewParagraph = lineInfo.previousLineBrokeCleanly();
1871     lineInfo.setPreviousLineBrokeCleanly(false);
1872
1873     bool autoWrapWasEverTrueOnLine = false;
1874     bool floatsFitOnLine = true;
1875
1876     // Firefox and Opera will allow a table cell to grow to fit an image inside it under
1877     // very specific circumstances (in order to match common WinIE renderings).
1878     // Not supporting the quirk has caused us to mis-render some real sites. (See Bugzilla 10517.)
1879     bool allowImagesToBreak = !m_block->document()->inQuirksMode() || !m_block->isTableCell() || !m_block->style()->logicalWidth().isIntrinsicOrAuto();
1880
1881     EWhiteSpace currWS = m_block->style()->whiteSpace();
1882     EWhiteSpace lastWS = currWS;
1883     while (current.m_obj) {
1884         RenderObject* next = bidiNext(m_block, current.m_obj);
1885
1886         currWS = current.m_obj->isReplaced() ? current.m_obj->parent()->style()->whiteSpace() : current.m_obj->style()->whiteSpace();
1887         lastWS = last->isReplaced() ? last->parent()->style()->whiteSpace() : last->style()->whiteSpace();
1888
1889         bool autoWrap = RenderStyle::autoWrap(currWS);
1890         autoWrapWasEverTrueOnLine = autoWrapWasEverTrueOnLine || autoWrap;
1891
1892 #if ENABLE(SVG)
1893         bool preserveNewline = current.m_obj->isSVGInlineText() ? false : RenderStyle::preserveNewline(currWS);
1894 #else
1895         bool preserveNewline = RenderStyle::preserveNewline(currWS);
1896 #endif
1897
1898         bool collapseWhiteSpace = RenderStyle::collapseWhiteSpace(currWS);
1899
1900         if (current.m_obj->isBR()) {
1901             if (width.fitsOnLine()) {
1902                 lBreak.moveToStartOf(current.m_obj);
1903                 lBreak.increment();
1904
1905                 // A <br> always breaks a line, so don't let the line be collapsed
1906                 // away. Also, the space at the end of a line with a <br> does not
1907                 // get collapsed away.  It only does this if the previous line broke
1908                 // cleanly.  Otherwise the <br> has no effect on whether the line is
1909                 // empty or not.
1910                 if (startingNewParagraph)
1911                     lineInfo.setEmpty(false);
1912                 trailingObjects.clear();
1913                 lineInfo.setPreviousLineBrokeCleanly(true);
1914
1915                 if (!lineInfo.isEmpty())
1916                     m_clear = current.m_obj->style()->clear();
1917             }
1918             goto end;
1919         }
1920
1921         if (current.m_obj->isFloating()) {
1922             RenderBox* floatBox = toRenderBox(current.m_obj);
1923             FloatingObject* f = m_block->insertFloatingObject(floatBox);
1924             // check if it fits in the current line.
1925             // If it does, position it now, otherwise, position
1926             // it after moving to next line (in newLine() func)
1927             if (floatsFitOnLine && width.fitsOnLine(m_block->logicalWidthForFloat(f))) {
1928                 m_block->positionNewFloatOnLine(f, lastFloatFromPreviousLine, width);
1929                 if (lBreak.m_obj == current.m_obj) {
1930                     ASSERT(!lBreak.m_pos);
1931                     lBreak.increment();
1932                 }
1933             } else
1934                 floatsFitOnLine = false;
1935         } else if (current.m_obj->isPositioned()) {
1936             // If our original display wasn't an inline type, then we can
1937             // go ahead and determine our static inline position now.
1938             RenderBox* box = toRenderBox(current.m_obj);
1939             bool isInlineType = box->style()->isOriginalDisplayInlineType();
1940             if (!isInlineType)
1941                 box->layer()->setStaticInlinePosition(m_block->borderAndPaddingStart());
1942             else  {
1943                 // If our original display was an INLINE type, then we can go ahead
1944                 // and determine our static y position now.
1945                 box->layer()->setStaticBlockPosition(m_block->logicalHeight());
1946             }
1947
1948             // If we're ignoring spaces, we have to stop and include this object and
1949             // then start ignoring spaces again.
1950             if (isInlineType || current.m_obj->container()->isRenderInline()) {
1951                 if (ignoringSpaces) {
1952                     ignoreStart.m_obj = current.m_obj;
1953                     ignoreStart.m_pos = 0;
1954                     addMidpoint(lineMidpointState, ignoreStart); // Stop ignoring spaces.
1955                     addMidpoint(lineMidpointState, ignoreStart); // Start ignoring again.
1956                 }
1957                 trailingObjects.appendBoxIfNeeded(box);
1958             } else
1959                 m_positionedObjects.append(box);
1960         } else if (current.m_obj->isRenderInline()) {
1961             // Right now, we should only encounter empty inlines here.
1962             ASSERT(!current.m_obj->firstChild());
1963
1964             RenderInline* flowBox = toRenderInline(current.m_obj);
1965
1966             // Now that some inline flows have line boxes, if we are already ignoring spaces, we need
1967             // to make sure that we stop to include this object and then start ignoring spaces again.
1968             // If this object is at the start of the line, we need to behave like list markers and
1969             // start ignoring spaces.
1970             if (inlineFlowRequiresLineBox(flowBox)) {
1971                 lineInfo.setEmpty(false);
1972                 if (ignoringSpaces) {
1973                     trailingObjects.clear();
1974                     addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, 0)); // Stop ignoring spaces.
1975                     addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, 0)); // Start ignoring again.
1976                 } else if (m_block->style()->collapseWhiteSpace() && resolver.position().m_obj == current.m_obj
1977                     && shouldSkipWhitespaceAfterStartObject(m_block, current.m_obj, lineMidpointState)) {
1978                     // Like with list markers, we start ignoring spaces to make sure that any
1979                     // additional spaces we see will be discarded.
1980                     currentCharacterIsSpace = true;
1981                     currentCharacterIsWS = true;
1982                     ignoringSpaces = true;
1983                 }
1984             }
1985
1986             width.addUncommittedWidth(borderPaddingMarginStart(flowBox) + borderPaddingMarginEnd(flowBox));
1987         } else if (current.m_obj->isReplaced()) {
1988             RenderBox* replacedBox = toRenderBox(current.m_obj);
1989
1990             // Break on replaced elements if either has normal white-space.
1991             if ((autoWrap || RenderStyle::autoWrap(lastWS)) && (!current.m_obj->isImage() || allowImagesToBreak)) {
1992                 width.commit();
1993                 lBreak.moveToStartOf(current.m_obj);
1994             }
1995
1996             if (ignoringSpaces)
1997                 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, 0));
1998
1999             lineInfo.setEmpty(false);
2000             ignoringSpaces = false;
2001             currentCharacterIsSpace = false;
2002             currentCharacterIsWS = false;
2003             trailingObjects.clear();
2004
2005             // Optimize for a common case. If we can't find whitespace after the list
2006             // item, then this is all moot.
2007             int replacedLogicalWidth = m_block->logicalWidthForChild(replacedBox) + m_block->marginStartForChild(replacedBox) + m_block->marginEndForChild(replacedBox) + inlineLogicalWidth(current.m_obj);
2008             if (current.m_obj->isListMarker()) {
2009                 if (m_block->style()->collapseWhiteSpace() && shouldSkipWhitespaceAfterStartObject(m_block, current.m_obj, lineMidpointState)) {
2010                     // Like with inline flows, we start ignoring spaces to make sure that any
2011                     // additional spaces we see will be discarded.
2012                     currentCharacterIsSpace = true;
2013                     currentCharacterIsWS = true;
2014                     ignoringSpaces = true;
2015                 }
2016                 if (toRenderListMarker(current.m_obj)->isInside())
2017                     width.addUncommittedWidth(replacedLogicalWidth);
2018             } else
2019                 width.addUncommittedWidth(replacedLogicalWidth);
2020             if (current.m_obj->isRubyRun())
2021                 width.applyOverhang(toRenderRubyRun(current.m_obj), last, next);
2022         } else if (current.m_obj->isText()) {
2023             if (!current.m_pos)
2024                 appliedStartWidth = false;
2025
2026             RenderText* t = toRenderText(current.m_obj);
2027
2028 #if ENABLE(SVG)
2029             bool isSVGText = t->isSVGInlineText();
2030 #endif
2031
2032             RenderStyle* style = t->style(lineInfo.isFirstLine());
2033             if (style->hasTextCombine() && current.m_obj->isCombineText())
2034                 toRenderCombineText(current.m_obj)->combineText();
2035
2036             const Font& f = style->font();
2037             bool isFixedPitch = f.isFixedPitch();
2038             bool canHyphenate = style->hyphens() == HyphensAuto && WebCore::canHyphenate(style->locale());
2039
2040             int lastSpace = current.m_pos;
2041             float wordSpacing = current.m_obj->style()->wordSpacing();
2042             float lastSpaceWordSpacing = 0;
2043
2044             // Non-zero only when kerning is enabled, in which case we measure words with their trailing
2045             // space, then subtract its width.
2046             float wordTrailingSpaceWidth = f.typesettingFeatures() & Kerning ? f.width(TextRun(&space, 1)) + wordSpacing : 0;
2047
2048             float wrapW = width.uncommittedWidth() + inlineLogicalWidth(current.m_obj, !appliedStartWidth, true);
2049             float charWidth = 0;
2050             bool breakNBSP = autoWrap && current.m_obj->style()->nbspMode() == SPACE;
2051             // Auto-wrapping text should wrap in the middle of a word only if it could not wrap before the word,
2052             // which is only possible if the word is the first thing on the line, that is, if |w| is zero.
2053             bool breakWords = current.m_obj->style()->breakWords() && ((autoWrap && !width.committedWidth()) || currWS == PRE);
2054             bool midWordBreak = false;
2055             bool breakAll = current.m_obj->style()->wordBreak() == BreakAllWordBreak && autoWrap;
2056             float hyphenWidth = 0;
2057
2058             if (t->isWordBreak()) {
2059                 width.commit();
2060                 lBreak.moveToStartOf(current.m_obj);
2061                 ASSERT(current.m_pos == t->textLength());
2062             }
2063
2064             for (; current.m_pos < t->textLength(); current.fastIncrementInTextNode()) {
2065                 bool previousCharacterIsSpace = currentCharacterIsSpace;
2066                 bool previousCharacterIsWS = currentCharacterIsWS;
2067                 UChar c = current.current();
2068                 currentCharacterIsSpace = c == ' ' || c == '\t' || (!preserveNewline && (c == '\n'));
2069
2070                 if (!collapseWhiteSpace || !currentCharacterIsSpace)
2071                     lineInfo.setEmpty(false);
2072
2073                 if (c == softHyphen && autoWrap && !hyphenWidth && style->hyphens() != HyphensNone) {
2074                     const AtomicString& hyphenString = style->hyphenString();
2075                     hyphenWidth = f.width(TextRun(hyphenString.characters(), hyphenString.length()));
2076                     width.addUncommittedWidth(hyphenWidth);
2077                 }
2078
2079                 bool applyWordSpacing = false;
2080
2081                 currentCharacterIsWS = currentCharacterIsSpace || (breakNBSP && c == noBreakSpace);
2082
2083                 if ((breakAll || breakWords) && !midWordBreak) {
2084                     wrapW += charWidth;
2085                     charWidth = textWidth(t, current.m_pos, 1, f, width.committedWidth() + wrapW, isFixedPitch, collapseWhiteSpace);
2086                     midWordBreak = width.committedWidth() + wrapW + charWidth > width.availableWidth();
2087                 }
2088
2089                 if (lineBreakIteratorInfo.first != t) {
2090                     lineBreakIteratorInfo.first = t;
2091                     lineBreakIteratorInfo.second.reset(t->characters(), t->textLength());
2092                 }
2093
2094                 bool betweenWords = c == '\n' || (currWS != PRE && !atStart && isBreakable(lineBreakIteratorInfo.second, current.m_pos, current.m_nextBreakablePosition, breakNBSP)
2095                     && (style->hyphens() != HyphensNone || (current.previousInSameNode() != softHyphen)));
2096
2097                 if (betweenWords || midWordBreak) {
2098                     bool stoppedIgnoringSpaces = false;
2099                     if (ignoringSpaces) {
2100                         if (!currentCharacterIsSpace) {
2101                             // Stop ignoring spaces and begin at this
2102                             // new point.
2103                             ignoringSpaces = false;
2104                             lastSpaceWordSpacing = 0;
2105                             lastSpace = current.m_pos; // e.g., "Foo    goo", don't add in any of the ignored spaces.
2106                             addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos));
2107                             stoppedIgnoringSpaces = true;
2108                         } else {
2109                             // Just keep ignoring these spaces.
2110                             continue;
2111                         }
2112                     }
2113
2114                     float additionalTmpW;
2115                     if (wordTrailingSpaceWidth && currentCharacterIsSpace)
2116                         additionalTmpW = textWidth(t, lastSpace, current.m_pos + 1 - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) - wordTrailingSpaceWidth + lastSpaceWordSpacing;
2117                     else
2118                         additionalTmpW = textWidth(t, lastSpace, current.m_pos - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing;
2119                     width.addUncommittedWidth(additionalTmpW);
2120                     if (!appliedStartWidth) {
2121                         width.addUncommittedWidth(inlineLogicalWidth(current.m_obj, true, false));
2122                         appliedStartWidth = true;
2123                     }
2124
2125                     applyWordSpacing =  wordSpacing && currentCharacterIsSpace && !previousCharacterIsSpace;
2126
2127                     if (!width.committedWidth() && autoWrap && !width.fitsOnLine())
2128                         width.fitBelowFloats();
2129
2130                     if (autoWrap || breakWords) {
2131                         // If we break only after white-space, consider the current character
2132                         // as candidate width for this line.
2133                         bool lineWasTooWide = false;
2134                         if (width.fitsOnLine() && currentCharacterIsWS && current.m_obj->style()->breakOnlyAfterWhiteSpace() && !midWordBreak) {
2135                             float charWidth = textWidth(t, current.m_pos, 1, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) + (applyWordSpacing ? wordSpacing : 0);
2136                             // Check if line is too big even without the extra space
2137                             // at the end of the line. If it is not, do nothing.
2138                             // If the line needs the extra whitespace to be too long,
2139                             // then move the line break to the space and skip all
2140                             // additional whitespace.
2141                             if (!width.fitsOnLine(charWidth)) {
2142                                 lineWasTooWide = true;
2143                                 lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2144                                 skipTrailingWhitespace(lBreak, lineInfo);
2145                             }
2146                         }
2147                         if (lineWasTooWide || !width.fitsOnLine()) {
2148                             if (canHyphenate && !width.fitsOnLine()) {
2149                                 tryHyphenating(t, f, style->locale(), style->hyphenationLimitBefore(), style->hyphenationLimitAfter(), lastSpace, current.m_pos, width.currentWidth() - additionalTmpW, width.availableWidth(), isFixedPitch, collapseWhiteSpace, lastSpaceWordSpacing, lBreak, current.m_nextBreakablePosition, m_hyphenated);
2150                                 if (m_hyphenated)
2151                                     goto end;
2152                             }
2153                             if (lBreak.atTextParagraphSeparator()) {
2154                                 if (!stoppedIgnoringSpaces && current.m_pos > 0) {
2155                                     // We need to stop right before the newline and then start up again.
2156                                     addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos - 1)); // Stop
2157                                     addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos)); // Start
2158                                 }
2159                                 lBreak.increment();
2160                                 lineInfo.setPreviousLineBrokeCleanly(true);
2161                             }
2162                             if (lBreak.m_obj && lBreak.m_pos && lBreak.m_obj->isText() && toRenderText(lBreak.m_obj)->textLength() && toRenderText(lBreak.m_obj)->characters()[lBreak.m_pos - 1] == softHyphen && style->hyphens() != HyphensNone)
2163                                 m_hyphenated = true;
2164                             goto end; // Didn't fit. Jump to the end.
2165                         } else {
2166                             if (!betweenWords || (midWordBreak && !autoWrap))
2167                                 width.addUncommittedWidth(-additionalTmpW);
2168                             if (hyphenWidth) {
2169                                 // Subtract the width of the soft hyphen out since we fit on a line.
2170                                 width.addUncommittedWidth(-hyphenWidth);
2171                                 hyphenWidth = 0;
2172                             }
2173                         }
2174                     }
2175
2176                     if (c == '\n' && preserveNewline) {
2177                         if (!stoppedIgnoringSpaces && current.m_pos > 0) {
2178                             // We need to stop right before the newline and then start up again.
2179                             addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos - 1)); // Stop
2180                             addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos)); // Start
2181                         }
2182                         lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2183                         lBreak.increment();
2184                         lineInfo.setPreviousLineBrokeCleanly(true);
2185                         return lBreak;
2186                     }
2187
2188                     if (autoWrap && betweenWords) {
2189                         width.commit();
2190                         wrapW = 0;
2191                         lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2192                         // Auto-wrapping text should not wrap in the middle of a word once it has had an
2193                         // opportunity to break after a word.
2194                         breakWords = false;
2195                     }
2196
2197                     if (midWordBreak) {
2198                         // Remember this as a breakable position in case
2199                         // adding the end width forces a break.
2200                         lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2201                         midWordBreak &= (breakWords || breakAll);
2202                     }
2203
2204                     if (betweenWords) {
2205                         lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
2206                         lastSpace = current.m_pos;
2207                     }
2208
2209                     if (!ignoringSpaces && current.m_obj->style()->collapseWhiteSpace()) {
2210                         // If we encounter a newline, or if we encounter a
2211                         // second space, we need to go ahead and break up this
2212                         // run and enter a mode where we start collapsing spaces.
2213                         if (currentCharacterIsSpace && previousCharacterIsSpace) {
2214                             ignoringSpaces = true;
2215
2216                             // We just entered a mode where we are ignoring
2217                             // spaces. Create a midpoint to terminate the run
2218                             // before the second space.
2219                             addMidpoint(lineMidpointState, ignoreStart);
2220                             trailingObjects.updateMidpointsForTrailingBoxes(lineMidpointState, InlineIterator(), TrailingObjects::DoNotCollapseFirstSpace);
2221                         }
2222                     }
2223                 } else if (ignoringSpaces) {
2224                     // Stop ignoring spaces and begin at this
2225                     // new point.
2226                     ignoringSpaces = false;
2227                     lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
2228                     lastSpace = current.m_pos; // e.g., "Foo    goo", don't add in any of the ignored spaces.
2229                     addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos));
2230                 }
2231
2232 #if ENABLE(SVG)
2233                 if (isSVGText && current.m_pos > 0) {
2234                     // Force creation of new InlineBoxes for each absolute positioned character (those that start new text chunks).
2235                     if (static_cast<RenderSVGInlineText*>(t)->characterStartsNewTextChunk(current.m_pos)) {
2236                         addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos - 1));
2237                         addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos));
2238                     }
2239                 }
2240 #endif
2241
2242                 if (currentCharacterIsSpace && !previousCharacterIsSpace) {
2243                     ignoreStart.m_obj = current.m_obj;
2244                     ignoreStart.m_pos = current.m_pos;
2245                 }
2246
2247                 if (!currentCharacterIsWS && previousCharacterIsWS) {
2248                     if (autoWrap && current.m_obj->style()->breakOnlyAfterWhiteSpace())
2249                         lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2250                 }
2251
2252                 if (collapseWhiteSpace && currentCharacterIsSpace && !ignoringSpaces)
2253                     trailingObjects.setTrailingWhitespace(static_cast<RenderText*>(current.m_obj));
2254                 else if (!current.m_obj->style()->collapseWhiteSpace() || !currentCharacterIsSpace)
2255                     trailingObjects.clear();
2256
2257                 atStart = false;
2258             }
2259
2260             // IMPORTANT: current.m_pos is > length here!
2261             float additionalTmpW = ignoringSpaces ? 0 : textWidth(t, lastSpace, current.m_pos - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing;
2262             width.addUncommittedWidth(additionalTmpW + inlineLogicalWidth(current.m_obj, !appliedStartWidth, true));
2263
2264             if (!width.fitsOnLine()) {
2265                 if (canHyphenate)
2266                     tryHyphenating(t, f, style->locale(), style->hyphenationLimitBefore(), style->hyphenationLimitAfter(), lastSpace, current.m_pos, width.currentWidth() - additionalTmpW, width.availableWidth(), isFixedPitch, collapseWhiteSpace, lastSpaceWordSpacing, lBreak, current.m_nextBreakablePosition, m_hyphenated);
2267
2268                 if (!m_hyphenated && lBreak.previousInSameNode() == softHyphen && style->hyphens() != HyphensNone)
2269                     m_hyphenated = true;
2270
2271                 if (m_hyphenated)
2272                     goto end;
2273             }
2274         } else
2275             ASSERT_NOT_REACHED();
2276
2277         bool checkForBreak = autoWrap;
2278         if (width.committedWidth() && !width.fitsOnLine() && lBreak.m_obj && currWS == NOWRAP)
2279             checkForBreak = true;
2280         else if (next && current.m_obj->isText() && next->isText() && !next->isBR() && (autoWrap || (next->style()->autoWrap()))) {
2281             if (currentCharacterIsSpace)
2282                 checkForBreak = true;
2283             else {
2284                 RenderText* nextText = toRenderText(next);
2285                 if (nextText->textLength()) {
2286                     UChar c = nextText->characters()[0];
2287                     checkForBreak = (c == ' ' || c == '\t' || (c == '\n' && !next->preservesNewline()));
2288                     // If the next item on the line is text, and if we did not end with
2289                     // a space, then the next text run continues our word (and so it needs to
2290                     // keep adding to |tmpW|. Just update and continue.
2291                 } else if (nextText->isWordBreak())
2292                     checkForBreak = true;
2293
2294                 if (!width.fitsOnLine() && !width.committedWidth())
2295                     width.fitBelowFloats();
2296
2297                 bool canPlaceOnLine = width.fitsOnLine() || !autoWrapWasEverTrueOnLine;
2298                 if (canPlaceOnLine && checkForBreak) {
2299                     width.commit();
2300                     lBreak.moveToStartOf(next);
2301                 }
2302             }
2303         }
2304
2305         if (checkForBreak && !width.fitsOnLine()) {
2306             // if we have floats, try to get below them.
2307             if (currentCharacterIsSpace && !ignoringSpaces && current.m_obj->style()->collapseWhiteSpace())
2308                 trailingObjects.clear();
2309
2310             if (width.committedWidth())
2311                 goto end;
2312
2313             width.fitBelowFloats();
2314
2315             // |width| may have been adjusted because we got shoved down past a float (thus
2316             // giving us more room), so we need to retest, and only jump to
2317             // the end label if we still don't fit on the line. -dwh
2318             if (!width.fitsOnLine())
2319                 goto end;
2320         }
2321
2322         if (!current.m_obj->isFloatingOrPositioned()) {
2323             last = current.m_obj;
2324             if (last->isReplaced() && autoWrap && (!last->isImage() || allowImagesToBreak) && (!last->isListMarker() || toRenderListMarker(last)->isInside())) {
2325                 width.commit();
2326                 lBreak.moveToStartOf(next);
2327             }
2328         }
2329
2330         // Clear out our character space bool, since inline <pre>s don't collapse whitespace
2331         // with adjacent inline normal/nowrap spans.
2332         if (!collapseWhiteSpace)
2333             currentCharacterIsSpace = false;
2334
2335         current.moveToStartOf(next);
2336         atStart = false;
2337     }
2338
2339     if (width.fitsOnLine() || lastWS == NOWRAP)
2340         lBreak.clear();
2341
2342  end:
2343     if (lBreak == resolver.position() && (!lBreak.m_obj || !lBreak.m_obj->isBR())) {
2344         // we just add as much as possible
2345         if (m_block->style()->whiteSpace() == PRE) {
2346             // FIXME: Don't really understand this case.
2347             if (current.m_pos) {
2348                 // FIXME: This should call moveTo which would clear m_nextBreakablePosition
2349                 // this code as-is is likely wrong.
2350                 lBreak.m_obj = current.m_obj;
2351                 lBreak.m_pos = current.m_pos - 1;
2352             } else
2353                 lBreak.moveTo(last, last->isText() ? last->length() : 0);
2354         } else if (lBreak.m_obj) {
2355             // Don't ever break in the middle of a word if we can help it.
2356             // There's no room at all. We just have to be on this line,
2357             // even though we'll spill out.
2358             lBreak.moveTo(current.m_obj, current.m_pos);
2359         }
2360     }
2361
2362     // make sure we consume at least one char/object.
2363     if (lBreak == resolver.position())
2364         lBreak.increment();
2365
2366     // Sanity check our midpoints.
2367     checkMidpoints(lineMidpointState, lBreak);
2368
2369     trailingObjects.updateMidpointsForTrailingBoxes(lineMidpointState, lBreak, TrailingObjects::CollapseFirstSpace);
2370
2371     // We might have made lBreak an iterator that points past the end
2372     // of the object. Do this adjustment to make it point to the start
2373     // of the next object instead to avoid confusing the rest of the
2374     // code.
2375     if (lBreak.m_pos > 0) {
2376         lBreak.m_pos--;
2377         lBreak.increment();
2378     }
2379
2380     return lBreak;
2381 }
2382
2383 void RenderBlock::addOverflowFromInlineChildren()
2384 {
2385     int endPadding = hasOverflowClip() ? paddingEnd() : 0;
2386     // FIXME: Need to find another way to do this, since scrollbars could show when we don't want them to.
2387     if (hasOverflowClip() && !endPadding && node() && node()->rendererIsEditable() && node() == node()->rootEditableElement() && style()->isLeftToRightDirection())
2388         endPadding = 1;
2389     for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
2390         addLayoutOverflow(curr->paddedLayoutOverflowRect(endPadding));
2391         if (!hasOverflowClip())
2392             addVisualOverflow(curr->visualOverflowRect(curr->lineTop(), curr->lineBottom()));
2393     }
2394 }
2395
2396 void RenderBlock::deleteEllipsisLineBoxes()
2397 {
2398     for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox())
2399         curr->clearTruncation();
2400 }
2401
2402 void RenderBlock::checkLinesForTextOverflow()
2403 {
2404     // Determine the width of the ellipsis using the current font.
2405     // FIXME: CSS3 says this is configurable, also need to use 0x002E (FULL STOP) if horizontal ellipsis is "not renderable"
2406     TextRun ellipsisRun(&horizontalEllipsis, 1);
2407     DEFINE_STATIC_LOCAL(AtomicString, ellipsisStr, (&horizontalEllipsis, 1));
2408     const Font& firstLineFont = firstLineStyle()->font();
2409     const Font& font = style()->font();
2410     int firstLineEllipsisWidth = firstLineFont.width(ellipsisRun);
2411     int ellipsisWidth = (font == firstLineFont) ? firstLineEllipsisWidth : font.width(ellipsisRun);
2412
2413     // For LTR text truncation, we want to get the right edge of our padding box, and then we want to see
2414     // if the right edge of a line box exceeds that.  For RTL, we use the left edge of the padding box and
2415     // check the left edge of the line box to see if it is less
2416     // Include the scrollbar for overflow blocks, which means we want to use "contentWidth()"
2417     bool ltr = style()->isLeftToRightDirection();
2418     for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
2419         int blockRightEdge = logicalRightOffsetForLine(curr->y(), curr == firstRootBox());
2420         int blockLeftEdge = logicalLeftOffsetForLine(curr->y(), curr == firstRootBox());
2421         int lineBoxEdge = ltr ? curr->x() + curr->logicalWidth() : curr->x();
2422         if ((ltr && lineBoxEdge > blockRightEdge) || (!ltr && lineBoxEdge < blockLeftEdge)) {
2423             // This line spills out of our box in the appropriate direction.  Now we need to see if the line
2424             // can be truncated.  In order for truncation to be possible, the line must have sufficient space to
2425             // accommodate our truncation string, and no replaced elements (images, tables) can overlap the ellipsis
2426             // space.
2427             int width = curr == firstRootBox() ? firstLineEllipsisWidth : ellipsisWidth;
2428             int blockEdge = ltr ? blockRightEdge : blockLeftEdge;
2429             if (curr->lineCanAccommodateEllipsis(ltr, blockEdge, lineBoxEdge, width))
2430                 curr->placeEllipsis(ellipsisStr, ltr, blockLeftEdge, blockRightEdge, width);
2431         }
2432     }
2433 }
2434
2435 bool RenderBlock::positionNewFloatOnLine(FloatingObject* newFloat, FloatingObject* lastFloatFromPreviousLine, LineWidth& width)
2436 {
2437     if (!positionNewFloats())
2438         return false;
2439
2440     width.shrinkAvailableWidthForNewFloatIfNeeded(newFloat);
2441
2442     if (!newFloat->m_paginationStrut)
2443         return true;
2444
2445     FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2446     ASSERT(floatingObjectSet.last() == newFloat);
2447
2448     int floatLogicalTop = logicalTopForFloat(newFloat);
2449     int paginationStrut = newFloat->m_paginationStrut;
2450
2451     if (floatLogicalTop - paginationStrut != logicalHeight())
2452         return true;
2453
2454     FloatingObjectSetIterator it = floatingObjectSet.end();
2455     --it; // Last float is newFloat, skip that one.
2456     FloatingObjectSetIterator begin = floatingObjectSet.begin();
2457     while (it != begin) {
2458         --it;
2459         FloatingObject* f = *it;
2460         if (f == lastFloatFromPreviousLine)
2461             break;
2462         if (logicalTopForFloat(f) == logicalHeight()) {
2463             ASSERT(!f->m_paginationStrut);
2464             f->m_paginationStrut = paginationStrut;
2465             RenderBox* o = f->m_renderer;
2466             setLogicalTopForChild(o, logicalTopForChild(o) + marginBeforeForChild(o) + paginationStrut);
2467             if (o->isRenderBlock())
2468                 toRenderBlock(o)->setChildNeedsLayout(true, false);
2469             o->layoutIfNeeded();
2470             setLogicalTopForFloat(f, logicalTopForFloat(f) + f->m_paginationStrut);
2471         }
2472     }
2473
2474     setLogicalHeight(logicalHeight() + paginationStrut);
2475     width.updateAvailableWidth();
2476
2477     return true;
2478 }
2479
2480 }