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