Source/WebCore: The initial value of text-align should be start instead of -webkit...
[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 = TASTART;
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 RIGHT:
718     case WEBKIT_RIGHT:
719         updateLogicalWidthForRightAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
720         break;
721     case CENTER:
722     case WEBKIT_CENTER:
723         updateLogicalWidthForCenterAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
724         break;
725     case JUSTIFY:
726         adjustInlineDirectionLineBounds(expansionOpportunityCount, logicalLeft, availableLogicalWidth);
727         if (expansionOpportunityCount) {
728             if (trailingSpaceRun) {
729                 totalLogicalWidth -= trailingSpaceRun->m_box->logicalWidth();
730                 trailingSpaceRun->m_box->setLogicalWidth(0);
731             }
732             break;
733         }
734         // Fall through
735     case TASTART:
736         if (style()->isLeftToRightDirection())
737             updateLogicalWidthForLeftAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
738         else
739             updateLogicalWidthForRightAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
740         break;
741     case TAEND:
742         if (style()->isLeftToRightDirection())
743             updateLogicalWidthForRightAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
744         else
745             updateLogicalWidthForLeftAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
746         break;
747     }
748 }
749
750 void RenderBlock::computeInlineDirectionPositionsForLine(RootInlineBox* lineBox, const LineInfo& lineInfo, BidiRun* firstRun, BidiRun* trailingSpaceRun, bool reachedEnd,
751                                                          GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache)
752 {
753     ETextAlign textAlign = textAlignmentForLine(!reachedEnd && !lineBox->endsWithBreak());
754     float logicalLeft = pixelSnappedLogicalLeftOffsetForLine(logicalHeight(), lineInfo.isFirstLine());
755     float availableLogicalWidth = pixelSnappedLogicalRightOffsetForLine(logicalHeight(), lineInfo.isFirstLine()) - logicalLeft;
756
757     bool needsWordSpacing = false;
758     float totalLogicalWidth = lineBox->getFlowSpacingLogicalWidth();
759     unsigned expansionOpportunityCount = 0;
760     bool isAfterExpansion = true;
761     Vector<unsigned, 16> expansionOpportunities;
762     RenderObject* previousObject = 0;
763
764     for (BidiRun* r = firstRun; r; r = r->next()) {
765         if (!r->m_box || r->m_object->isPositioned() || r->m_box->isLineBreak())
766             continue; // Positioned objects are only participating to figure out their
767                       // correct static x position.  They have no effect on the width.
768                       // Similarly, line break boxes have no effect on the width.
769         if (r->m_object->isText()) {
770             RenderText* rt = toRenderText(r->m_object);
771             if (textAlign == JUSTIFY && r != trailingSpaceRun) {
772                 if (!isAfterExpansion)
773                     toInlineTextBox(r->m_box)->setCanHaveLeadingExpansion(true);
774                 unsigned opportunitiesInRun = Font::expansionOpportunityCount(rt->characters() + r->m_start, r->m_stop - r->m_start, r->m_box->direction(), isAfterExpansion);
775                 expansionOpportunities.append(opportunitiesInRun);
776                 expansionOpportunityCount += opportunitiesInRun;
777             }
778
779             if (int length = rt->textLength()) {
780                 if (!r->m_start && needsWordSpacing && isSpaceOrNewline(rt->characters()[r->m_start]))
781                     totalLogicalWidth += rt->style(lineInfo.isFirstLine())->font().wordSpacing();
782                 needsWordSpacing = !isSpaceOrNewline(rt->characters()[r->m_stop - 1]) && r->m_stop == length;
783             }
784
785             setLogicalWidthForTextRun(lineBox, r, rt, totalLogicalWidth, lineInfo, textBoxDataMap, verticalPositionCache);
786         } else {
787             isAfterExpansion = false;
788             if (!r->m_object->isRenderInline()) {
789                 RenderBox* renderBox = toRenderBox(r->m_object);
790                 if (renderBox->isRubyRun())
791                     setMarginsForRubyRun(r, toRenderRubyRun(renderBox), previousObject, lineInfo);
792                 r->m_box->setLogicalWidth(logicalWidthForChild(renderBox));
793                 totalLogicalWidth += marginStartForChild(renderBox) + marginEndForChild(renderBox);
794             }
795         }
796
797         totalLogicalWidth += r->m_box->logicalWidth();
798         previousObject = r->m_object;
799     }
800
801     if (isAfterExpansion && !expansionOpportunities.isEmpty()) {
802         expansionOpportunities.last()--;
803         expansionOpportunityCount--;
804     }
805
806     updateLogicalWidthForAlignment(textAlign, trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth, expansionOpportunityCount);
807
808     computeExpansionForJustifiedText(firstRun, trailingSpaceRun, expansionOpportunities, expansionOpportunityCount, totalLogicalWidth, availableLogicalWidth);
809
810     // The widths of all runs are now known.  We can now place every inline box (and
811     // compute accurate widths for the inline flow boxes).
812     needsWordSpacing = false;
813     lineBox->placeBoxesInInlineDirection(logicalLeft, needsWordSpacing, textBoxDataMap);
814 }
815
816 void RenderBlock::computeBlockDirectionPositionsForLine(RootInlineBox* lineBox, BidiRun* firstRun, GlyphOverflowAndFallbackFontsMap& textBoxDataMap,
817                                                         VerticalPositionCache& verticalPositionCache)
818 {
819     setLogicalHeight(lineBox->alignBoxesInBlockDirection(logicalHeight(), textBoxDataMap, verticalPositionCache));
820
821     // Now make sure we place replaced render objects correctly.
822     for (BidiRun* r = firstRun; r; r = r->next()) {
823         ASSERT(r->m_box);
824         if (!r->m_box)
825             continue; // Skip runs with no line boxes.
826
827         // Align positioned boxes with the top of the line box.  This is
828         // a reasonable approximation of an appropriate y position.
829         if (r->m_object->isPositioned())
830             r->m_box->setLogicalTop(logicalHeight());
831
832         // Position is used to properly position both replaced elements and
833         // to update the static normal flow x/y of positioned elements.
834         if (r->m_object->isText())
835             toRenderText(r->m_object)->positionLineBox(r->m_box);
836         else if (r->m_object->isBox())
837             toRenderBox(r->m_object)->positionLineBox(r->m_box);
838     }
839     // Positioned objects and zero-length text nodes destroy their boxes in
840     // position(), which unnecessarily dirties the line.
841     lineBox->markDirty(false);
842 }
843
844 static inline bool isCollapsibleSpace(UChar character, RenderText* renderer)
845 {
846     if (character == ' ' || character == '\t' || character == softHyphen)
847         return true;
848     if (character == '\n')
849         return !renderer->style()->preserveNewline();
850     if (character == noBreakSpace)
851         return renderer->style()->nbspMode() == SPACE;
852     return false;
853 }
854
855
856 static void setStaticPositions(RenderBlock* block, RenderBox* child)
857 {
858     // FIXME: The math here is actually not really right. It's a best-guess approximation that
859     // will work for the common cases
860     RenderObject* containerBlock = child->container();
861     LayoutUnit blockHeight = block->logicalHeight();
862     if (containerBlock->isRenderInline()) {
863         // A relative positioned inline encloses us. In this case, we also have to determine our
864         // position as though we were an inline. Set |staticInlinePosition| and |staticBlockPosition| on the relative positioned
865         // inline so that we can obtain the value later.
866         toRenderInline(containerBlock)->layer()->setStaticInlinePosition(block->startAlignedOffsetForLine(child, blockHeight, false));
867         toRenderInline(containerBlock)->layer()->setStaticBlockPosition(blockHeight);
868     }
869
870     if (child->style()->isOriginalDisplayInlineType())
871         block->setStaticInlinePositionForChild(child, blockHeight, block->startAlignedOffsetForLine(child, blockHeight, false));
872     else
873         block->setStaticInlinePositionForChild(child, blockHeight, block->startOffsetForContent(blockHeight));
874     child->layer()->setStaticBlockPosition(blockHeight);
875 }
876
877 inline BidiRun* RenderBlock::handleTrailingSpaces(BidiRunList<BidiRun>& bidiRuns, BidiContext* currentContext)
878 {
879     if (!bidiRuns.runCount()
880         || !bidiRuns.logicallyLastRun()->m_object->style()->breakOnlyAfterWhiteSpace()
881         || !bidiRuns.logicallyLastRun()->m_object->style()->autoWrap())
882         return 0;
883
884     BidiRun* trailingSpaceRun = bidiRuns.logicallyLastRun();
885     RenderObject* lastObject = trailingSpaceRun->m_object;
886     if (!lastObject->isText())
887         return 0;
888
889     RenderText* lastText = toRenderText(lastObject);
890     const UChar* characters = lastText->characters();
891     int firstSpace = trailingSpaceRun->stop();
892     while (firstSpace > trailingSpaceRun->start()) {
893         UChar current = characters[firstSpace - 1];
894         if (!isCollapsibleSpace(current, lastText))
895             break;
896         firstSpace--;
897     }
898     if (firstSpace == trailingSpaceRun->stop())
899         return 0;
900
901     TextDirection direction = style()->direction();
902     bool shouldReorder = trailingSpaceRun != (direction == LTR ? bidiRuns.lastRun() : bidiRuns.firstRun());
903     if (firstSpace != trailingSpaceRun->start()) {
904         BidiContext* baseContext = currentContext;
905         while (BidiContext* parent = baseContext->parent())
906             baseContext = parent;
907
908         BidiRun* newTrailingRun = new (renderArena()) BidiRun(firstSpace, trailingSpaceRun->m_stop, trailingSpaceRun->m_object, baseContext, OtherNeutral);
909         trailingSpaceRun->m_stop = firstSpace;
910         if (direction == LTR)
911             bidiRuns.addRun(newTrailingRun);
912         else
913             bidiRuns.prependRun(newTrailingRun);
914         trailingSpaceRun = newTrailingRun;
915         return trailingSpaceRun;
916     }
917     if (!shouldReorder)
918         return trailingSpaceRun;
919
920     if (direction == LTR) {
921         bidiRuns.moveRunToEnd(trailingSpaceRun);
922         trailingSpaceRun->m_level = 0;
923     } else {
924         bidiRuns.moveRunToBeginning(trailingSpaceRun);
925         trailingSpaceRun->m_level = 1;
926     }
927     return trailingSpaceRun;
928 }
929
930 void RenderBlock::appendFloatingObjectToLastLine(FloatingObject* floatingObject)
931 {
932     ASSERT(!floatingObject->m_originatingLine);
933     floatingObject->m_originatingLine = lastRootBox();
934     lastRootBox()->appendFloat(floatingObject->renderer());
935 }
936
937 // FIXME: This should be a BidiStatus constructor or create method.
938 static inline BidiStatus statusWithDirection(TextDirection textDirection, bool isOverride)
939 {
940     WTF::Unicode::Direction direction = textDirection == LTR ? LeftToRight : RightToLeft;
941     RefPtr<BidiContext> context = BidiContext::create(textDirection == LTR ? 0 : 1, direction, isOverride, FromStyleOrDOM);
942
943     // This copies BidiStatus and may churn the ref on BidiContext. I doubt it matters.
944     return BidiStatus(direction, direction, direction, context.release());
945 }
946
947 // FIXME: BidiResolver should have this logic.
948 static inline void constructBidiRuns(InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfLine, VisualDirectionOverride override, bool previousLineBrokeCleanly)
949 {
950     // FIXME: We should pass a BidiRunList into createBidiRunsForLine instead
951     // of the resolver owning the runs.
952     ASSERT(&topResolver.runs() == &bidiRuns);
953     RenderObject* currentRoot = topResolver.position().root();
954     topResolver.createBidiRunsForLine(endOfLine, override, previousLineBrokeCleanly);
955
956     while (!topResolver.isolatedRuns().isEmpty()) {
957         // It does not matter which order we resolve the runs as long as we resolve them all.
958         BidiRun* isolatedRun = topResolver.isolatedRuns().last();
959         topResolver.isolatedRuns().removeLast();
960
961         RenderObject* startObj = isolatedRun->object();
962
963         // Only inlines make sense with unicode-bidi: isolate (blocks are already isolated).
964         // FIXME: Because enterIsolate is not passed a RenderObject, we have to crawl up the
965         // tree to see which parent inline is the isolate. We could change enterIsolate
966         // to take a RenderObject and do this logic there, but that would be a layering
967         // violation for BidiResolver (which knows nothing about RenderObject).
968         RenderInline* isolatedInline = toRenderInline(containingIsolate(startObj, currentRoot));
969         InlineBidiResolver isolatedResolver;
970         EUnicodeBidi unicodeBidi = isolatedInline->style()->unicodeBidi();
971         TextDirection direction;
972         if (unicodeBidi == Plaintext)
973             determineDirectionality(direction, InlineIterator(isolatedInline, isolatedRun->object(), 0));
974         else {
975             ASSERT(unicodeBidi == Isolate || unicodeBidi == OverrideIsolate);
976             direction = isolatedInline->style()->direction();
977         }
978         isolatedResolver.setStatus(statusWithDirection(direction, isOverride(unicodeBidi)));
979
980         // FIXME: The fact that we have to construct an Iterator here
981         // currently prevents this code from moving into BidiResolver.
982         if (!bidiFirstSkippingEmptyInlines(isolatedInline, &isolatedResolver))
983             continue;
984
985         // The starting position is the beginning of the first run within the isolate that was identified
986         // during the earlier call to createBidiRunsForLine. This can be but is not necessarily the
987         // first run within the isolate.
988         InlineIterator iter = InlineIterator(isolatedInline, startObj, isolatedRun->m_start);
989         isolatedResolver.setPositionIgnoringNestedIsolates(iter);
990
991         // We stop at the next end of line; we may re-enter this isolate in the next call to constructBidiRuns().
992         // FIXME: What should end and previousLineBrokeCleanly be?
993         // rniwa says previousLineBrokeCleanly is just a WinIE hack and could always be false here?
994         isolatedResolver.createBidiRunsForLine(endOfLine, NoVisualOverride, previousLineBrokeCleanly);
995         // Note that we do not delete the runs from the resolver.
996         // We're not guaranteed to get any BidiRuns in the previous step. If we don't, we allow the placeholder
997         // itself to be turned into an InlineBox. We can't remove it here without potentially losing track of
998         // the logically last run.
999         if (isolatedResolver.runs().runCount())
1000             bidiRuns.replaceRunWithRuns(isolatedRun, isolatedResolver.runs());
1001
1002         // If we encountered any nested isolate runs, just move them
1003         // to the top resolver's list for later processing.
1004         if (!isolatedResolver.isolatedRuns().isEmpty()) {
1005             topResolver.isolatedRuns().append(isolatedResolver.isolatedRuns());
1006             isolatedResolver.isolatedRuns().clear();
1007         }
1008     }
1009 }
1010
1011 // This function constructs line boxes for all of the text runs in the resolver and computes their position.
1012 RootInlineBox* RenderBlock::createLineBoxesFromBidiRuns(BidiRunList<BidiRun>& bidiRuns, const InlineIterator& end, LineInfo& lineInfo, VerticalPositionCache& verticalPositionCache, BidiRun* trailingSpaceRun)
1013 {
1014     if (!bidiRuns.runCount())
1015         return 0;
1016
1017     // FIXME: Why is this only done when we had runs?
1018     lineInfo.setLastLine(!end.m_obj);
1019
1020     RootInlineBox* lineBox = constructLine(bidiRuns, lineInfo);
1021     if (!lineBox)
1022         return 0;
1023
1024     lineBox->setEndsWithBreak(lineInfo.previousLineBrokeCleanly());
1025     
1026 #if ENABLE(SVG)
1027     bool isSVGRootInlineBox = lineBox->isSVGRootInlineBox();
1028 #else
1029     bool isSVGRootInlineBox = false;
1030 #endif
1031     
1032     GlyphOverflowAndFallbackFontsMap textBoxDataMap;
1033     
1034     // Now we position all of our text runs horizontally.
1035     if (!isSVGRootInlineBox)
1036         computeInlineDirectionPositionsForLine(lineBox, lineInfo, bidiRuns.firstRun(), trailingSpaceRun, end.atEnd(), textBoxDataMap, verticalPositionCache);
1037     
1038     // Now position our text runs vertically.
1039     computeBlockDirectionPositionsForLine(lineBox, bidiRuns.firstRun(), textBoxDataMap, verticalPositionCache);
1040     
1041 #if ENABLE(SVG)
1042     // SVG text layout code computes vertical & horizontal positions on its own.
1043     // Note that we still need to execute computeVerticalPositionsForLine() as
1044     // it calls InlineTextBox::positionLineBox(), which tracks whether the box
1045     // contains reversed text or not. If we wouldn't do that editing and thus
1046     // text selection in RTL boxes would not work as expected.
1047     if (isSVGRootInlineBox) {
1048         ASSERT(isSVGText());
1049         static_cast<SVGRootInlineBox*>(lineBox)->computePerCharacterLayoutInformation();
1050     }
1051 #endif
1052     
1053     // Compute our overflow now.
1054     lineBox->computeOverflow(lineBox->lineTop(), lineBox->lineBottom(), textBoxDataMap);
1055     
1056 #if PLATFORM(MAC)
1057     // Highlight acts as an overflow inflation.
1058     if (style()->highlight() != nullAtom)
1059         lineBox->addHighlightOverflow();
1060 #endif
1061     return lineBox;
1062 }
1063
1064 // Like LayoutState for layout(), LineLayoutState keeps track of global information
1065 // during an entire linebox tree layout pass (aka layoutInlineChildren).
1066 class LineLayoutState {
1067 public:
1068     LineLayoutState(bool fullLayout, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom)
1069         : m_lastFloat(0)
1070         , m_endLine(0)
1071         , m_floatIndex(0)
1072         , m_endLineLogicalTop(0)
1073         , m_endLineMatched(false)
1074         , m_checkForFloatsFromLastLine(false)
1075         , m_isFullLayout(fullLayout)
1076         , m_repaintLogicalTop(repaintLogicalTop)
1077         , m_repaintLogicalBottom(repaintLogicalBottom)
1078         , m_usesRepaintBounds(false)
1079     { }
1080
1081     void markForFullLayout() { m_isFullLayout = true; }
1082     bool isFullLayout() const { return m_isFullLayout; }
1083
1084     bool usesRepaintBounds() const { return m_usesRepaintBounds; }
1085
1086     void setRepaintRange(LayoutUnit logicalHeight)
1087     { 
1088         m_usesRepaintBounds = true;
1089         m_repaintLogicalTop = m_repaintLogicalBottom = logicalHeight; 
1090     }
1091     
1092     void updateRepaintRangeFromBox(RootInlineBox* box, LayoutUnit paginationDelta = 0)
1093     {
1094         m_usesRepaintBounds = true;
1095         m_repaintLogicalTop = min(m_repaintLogicalTop, box->logicalTopVisualOverflow() + min(paginationDelta, ZERO_LAYOUT_UNIT));
1096         m_repaintLogicalBottom = max(m_repaintLogicalBottom, box->logicalBottomVisualOverflow() + max(paginationDelta, ZERO_LAYOUT_UNIT));
1097     }
1098     
1099     bool endLineMatched() const { return m_endLineMatched; }
1100     void setEndLineMatched(bool endLineMatched) { m_endLineMatched = endLineMatched; }
1101
1102     bool checkForFloatsFromLastLine() const { return m_checkForFloatsFromLastLine; }
1103     void setCheckForFloatsFromLastLine(bool check) { m_checkForFloatsFromLastLine = check; }
1104
1105     LineInfo& lineInfo() { return m_lineInfo; }
1106     const LineInfo& lineInfo() const { return m_lineInfo; }
1107
1108     LayoutUnit endLineLogicalTop() const { return m_endLineLogicalTop; }
1109     void setEndLineLogicalTop(LayoutUnit logicalTop) { m_endLineLogicalTop = logicalTop; }
1110
1111     RootInlineBox* endLine() const { return m_endLine; }
1112     void setEndLine(RootInlineBox* line) { m_endLine = line; }
1113
1114     RenderBlock::FloatingObject* lastFloat() const { return m_lastFloat; }
1115     void setLastFloat(RenderBlock::FloatingObject* lastFloat) { m_lastFloat = lastFloat; }
1116
1117     Vector<RenderBlock::FloatWithRect>& floats() { return m_floats; }
1118     
1119     unsigned floatIndex() const { return m_floatIndex; }
1120     void setFloatIndex(unsigned floatIndex) { m_floatIndex = floatIndex; }
1121     
1122 private:
1123     Vector<RenderBlock::FloatWithRect> m_floats;
1124     RenderBlock::FloatingObject* m_lastFloat;
1125     RootInlineBox* m_endLine;
1126     LineInfo m_lineInfo;
1127     unsigned m_floatIndex;
1128     LayoutUnit m_endLineLogicalTop;
1129     bool m_endLineMatched;
1130     bool m_checkForFloatsFromLastLine;
1131     
1132     bool m_isFullLayout;
1133
1134     // FIXME: Should this be a range object instead of two ints?
1135     LayoutUnit& m_repaintLogicalTop;
1136     LayoutUnit& m_repaintLogicalBottom;
1137
1138     bool m_usesRepaintBounds;
1139 };
1140
1141 static void deleteLineRange(LineLayoutState& layoutState, RenderArena* arena, RootInlineBox* startLine, RootInlineBox* stopLine = 0)
1142 {
1143     RootInlineBox* boxToDelete = startLine;
1144     while (boxToDelete && boxToDelete != stopLine) {
1145         layoutState.updateRepaintRangeFromBox(boxToDelete);
1146         // Note: deleteLineRange(renderArena(), firstRootBox()) is not identical to deleteLineBoxTree().
1147         // deleteLineBoxTree uses nextLineBox() instead of nextRootBox() when traversing.
1148         RootInlineBox* next = boxToDelete->nextRootBox();
1149         boxToDelete->deleteLine(arena);
1150         boxToDelete = next;
1151     }
1152 }
1153
1154 void RenderBlock::layoutRunsAndFloats(LineLayoutState& layoutState, bool hasInlineChild)
1155 {
1156     // We want to skip ahead to the first dirty line
1157     InlineBidiResolver resolver;
1158     RootInlineBox* startLine = determineStartPosition(layoutState, resolver);
1159
1160     unsigned consecutiveHyphenatedLines = 0;
1161     if (startLine) {
1162         for (RootInlineBox* line = startLine->prevRootBox(); line && line->isHyphenated(); line = line->prevRootBox())
1163             consecutiveHyphenatedLines++;
1164     }
1165
1166     // FIXME: This would make more sense outside of this function, but since
1167     // determineStartPosition can change the fullLayout flag we have to do this here. Failure to call
1168     // determineStartPosition first will break fast/repaint/line-flow-with-floats-9.html.
1169     if (layoutState.isFullLayout() && hasInlineChild && !selfNeedsLayout()) {
1170         setNeedsLayout(true, MarkOnlyThis); // Mark as needing a full layout to force us to repaint.
1171         RenderView* v = view();
1172         if (v && !v->doingFullRepaint() && hasLayer()) {
1173             // Because we waited until we were already inside layout to discover
1174             // that the block really needed a full layout, we missed our chance to repaint the layer
1175             // before layout started.  Luckily the layer has cached the repaint rect for its original
1176             // position and size, and so we can use that to make a repaint happen now.
1177             repaintUsingContainer(containerForRepaint(), layer()->repaintRect());
1178         }
1179     }
1180
1181     if (m_floatingObjects && !m_floatingObjects->set().isEmpty())
1182         layoutState.setLastFloat(m_floatingObjects->set().last());
1183
1184     // We also find the first clean line and extract these lines.  We will add them back
1185     // if we determine that we're able to synchronize after handling all our dirty lines.
1186     InlineIterator cleanLineStart;
1187     BidiStatus cleanLineBidiStatus;
1188     if (!layoutState.isFullLayout() && startLine)
1189         determineEndPosition(layoutState, startLine, cleanLineStart, cleanLineBidiStatus);
1190
1191     if (startLine) {
1192         if (!layoutState.usesRepaintBounds())
1193             layoutState.setRepaintRange(logicalHeight());
1194         deleteLineRange(layoutState, renderArena(), startLine);
1195     }
1196
1197     if (!layoutState.isFullLayout() && lastRootBox() && lastRootBox()->endsWithBreak()) {
1198         // If the last line before the start line ends with a line break that clear floats,
1199         // adjust the height accordingly.
1200         // A line break can be either the first or the last object on a line, depending on its direction.
1201         if (InlineBox* lastLeafChild = lastRootBox()->lastLeafChild()) {
1202             RenderObject* lastObject = lastLeafChild->renderer();
1203             if (!lastObject->isBR())
1204                 lastObject = lastRootBox()->firstLeafChild()->renderer();
1205             if (lastObject->isBR()) {
1206                 EClear clear = lastObject->style()->clear();
1207                 if (clear != CNONE)
1208                     newLine(clear);
1209             }
1210         }
1211     }
1212
1213     layoutRunsAndFloatsInRange(layoutState, resolver, cleanLineStart, cleanLineBidiStatus, consecutiveHyphenatedLines);
1214     linkToEndLineIfNeeded(layoutState);
1215     repaintDirtyFloats(layoutState.floats());
1216 }
1217
1218 void RenderBlock::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, InlineBidiResolver& resolver, const InlineIterator& cleanLineStart, const BidiStatus& cleanLineBidiStatus, unsigned consecutiveHyphenatedLines)
1219 {
1220     RenderStyle* styleToUse = style();
1221     bool paginated = view()->layoutState() && view()->layoutState()->isPaginated();
1222     LineMidpointState& lineMidpointState = resolver.midpointState();
1223     InlineIterator end = resolver.position();
1224     bool checkForEndLineMatch = layoutState.endLine();
1225     LineBreakIteratorInfo lineBreakIteratorInfo;
1226     VerticalPositionCache verticalPositionCache;
1227
1228     LineBreaker lineBreaker(this);
1229
1230     while (!end.atEnd()) {
1231         // FIXME: Is this check necessary before the first iteration or can it be moved to the end?
1232         if (checkForEndLineMatch) {
1233             layoutState.setEndLineMatched(matchedEndLine(layoutState, resolver, cleanLineStart, cleanLineBidiStatus));
1234             if (layoutState.endLineMatched()) {
1235                 resolver.setPosition(InlineIterator(resolver.position().root(), 0, 0), 0);
1236                 break;
1237             }
1238         }
1239
1240         lineMidpointState.reset();
1241
1242         layoutState.lineInfo().setEmpty(true);
1243         layoutState.lineInfo().resetRunsFromLeadingWhitespace();
1244
1245         const InlineIterator oldEnd = end;
1246         bool isNewUBAParagraph = layoutState.lineInfo().previousLineBrokeCleanly();
1247         FloatingObject* lastFloatFromPreviousLine = (m_floatingObjects && !m_floatingObjects->set().isEmpty()) ? m_floatingObjects->set().last() : 0;
1248         end = lineBreaker.nextLineBreak(resolver, layoutState.lineInfo(), lineBreakIteratorInfo, lastFloatFromPreviousLine, consecutiveHyphenatedLines);
1249         if (resolver.position().atEnd()) {
1250             // FIXME: We shouldn't be creating any runs in nextLineBreak to begin with!
1251             // Once BidiRunList is separated from BidiResolver this will not be needed.
1252             resolver.runs().deleteRuns();
1253             resolver.markCurrentRunEmpty(); // FIXME: This can probably be replaced by an ASSERT (or just removed).
1254             layoutState.setCheckForFloatsFromLastLine(true);
1255             resolver.setPosition(InlineIterator(resolver.position().root(), 0, 0), 0);
1256             break;
1257         }
1258         ASSERT(end != resolver.position());
1259
1260         // This is a short-cut for empty lines.
1261         if (layoutState.lineInfo().isEmpty()) {
1262             if (lastRootBox())
1263                 lastRootBox()->setLineBreakInfo(end.m_obj, end.m_pos, resolver.status());
1264         } else {
1265             VisualDirectionOverride override = (styleToUse->rtlOrdering() == VisualOrder ? (styleToUse->direction() == LTR ? VisualLeftToRightOverride : VisualRightToLeftOverride) : NoVisualOverride);
1266
1267             if (isNewUBAParagraph && styleToUse->unicodeBidi() == Plaintext && !resolver.context()->parent()) {
1268                 TextDirection direction = styleToUse->direction();
1269                 determineDirectionality(direction, resolver.position());
1270                 resolver.setStatus(BidiStatus(direction, isOverride(styleToUse->unicodeBidi())));
1271             }
1272             // FIXME: This ownership is reversed. We should own the BidiRunList and pass it to createBidiRunsForLine.
1273             BidiRunList<BidiRun>& bidiRuns = resolver.runs();
1274             constructBidiRuns(resolver, bidiRuns, end, override, layoutState.lineInfo().previousLineBrokeCleanly());
1275             ASSERT(resolver.position() == end);
1276
1277             BidiRun* trailingSpaceRun = !layoutState.lineInfo().previousLineBrokeCleanly() ? handleTrailingSpaces(bidiRuns, resolver.context()) : 0;
1278
1279             if (bidiRuns.runCount() && lineBreaker.lineWasHyphenated()) {
1280                 bidiRuns.logicallyLastRun()->m_hasHyphen = true;
1281                 consecutiveHyphenatedLines++;
1282             } else
1283                 consecutiveHyphenatedLines = 0;
1284
1285             // Now that the runs have been ordered, we create the line boxes.
1286             // At the same time we figure out where border/padding/margin should be applied for
1287             // inline flow boxes.
1288
1289             LayoutUnit oldLogicalHeight = logicalHeight();
1290             RootInlineBox* lineBox = createLineBoxesFromBidiRuns(bidiRuns, end, layoutState.lineInfo(), verticalPositionCache, trailingSpaceRun);
1291
1292             bidiRuns.deleteRuns();
1293             resolver.markCurrentRunEmpty(); // FIXME: This can probably be replaced by an ASSERT (or just removed).
1294
1295             if (lineBox) {
1296                 lineBox->setLineBreakInfo(end.m_obj, end.m_pos, resolver.status());
1297                 if (layoutState.usesRepaintBounds())
1298                     layoutState.updateRepaintRangeFromBox(lineBox);
1299
1300                 if (paginated) {
1301                     LayoutUnit adjustment = 0;
1302                     adjustLinePositionForPagination(lineBox, adjustment);
1303                     if (adjustment) {
1304                         LayoutUnit oldLineWidth = availableLogicalWidthForLine(oldLogicalHeight, layoutState.lineInfo().isFirstLine());
1305                         lineBox->adjustBlockDirectionPosition(adjustment);
1306                         if (layoutState.usesRepaintBounds())
1307                             layoutState.updateRepaintRangeFromBox(lineBox);
1308
1309                         if (availableLogicalWidthForLine(oldLogicalHeight + adjustment, layoutState.lineInfo().isFirstLine()) != oldLineWidth) {
1310                             // We have to delete this line, remove all floats that got added, and let line layout re-run.
1311                             lineBox->deleteLine(renderArena());
1312                             removeFloatingObjectsBelow(lastFloatFromPreviousLine, oldLogicalHeight);
1313                             setLogicalHeight(oldLogicalHeight + adjustment);
1314                             resolver.setPositionIgnoringNestedIsolates(oldEnd);
1315                             end = oldEnd;
1316                             continue;
1317                         }
1318
1319                         setLogicalHeight(lineBox->lineBottomWithLeading());
1320                     }
1321                 }
1322             }
1323
1324             for (size_t i = 0; i < lineBreaker.positionedObjects().size(); ++i)
1325                 setStaticPositions(this, lineBreaker.positionedObjects()[i]);
1326
1327             layoutState.lineInfo().setFirstLine(false);
1328             newLine(lineBreaker.clear());
1329         }
1330
1331         if (m_floatingObjects && lastRootBox()) {
1332             const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1333             FloatingObjectSetIterator it = floatingObjectSet.begin();
1334             FloatingObjectSetIterator end = floatingObjectSet.end();
1335             if (layoutState.lastFloat()) {
1336                 FloatingObjectSetIterator lastFloatIterator = floatingObjectSet.find(layoutState.lastFloat());
1337                 ASSERT(lastFloatIterator != end);
1338                 ++lastFloatIterator;
1339                 it = lastFloatIterator;
1340             }
1341             for (; it != end; ++it) {
1342                 FloatingObject* f = *it;
1343                 appendFloatingObjectToLastLine(f);
1344                 ASSERT(f->m_renderer == layoutState.floats()[layoutState.floatIndex()].object);
1345                 // If a float's geometry has changed, give up on syncing with clean lines.
1346                 if (layoutState.floats()[layoutState.floatIndex()].rect != f->frameRect())
1347                     checkForEndLineMatch = false;
1348                 layoutState.setFloatIndex(layoutState.floatIndex() + 1);
1349             }
1350             layoutState.setLastFloat(!floatingObjectSet.isEmpty() ? floatingObjectSet.last() : 0);
1351         }
1352
1353         lineMidpointState.reset();
1354         resolver.setPosition(end, numberOfIsolateAncestors(end));
1355     }
1356 }
1357
1358 void RenderBlock::linkToEndLineIfNeeded(LineLayoutState& layoutState)
1359 {
1360     if (layoutState.endLine()) {
1361         if (layoutState.endLineMatched()) {
1362             bool paginated = view()->layoutState() && view()->layoutState()->isPaginated();
1363             // Attach all the remaining lines, and then adjust their y-positions as needed.
1364             LayoutUnit delta = logicalHeight() - layoutState.endLineLogicalTop();
1365             for (RootInlineBox* line = layoutState.endLine(); line; line = line->nextRootBox()) {
1366                 line->attachLine();
1367                 if (paginated) {
1368                     delta -= line->paginationStrut();
1369                     adjustLinePositionForPagination(line, delta);
1370                 }
1371                 if (delta) {
1372                     layoutState.updateRepaintRangeFromBox(line, delta);
1373                     line->adjustBlockDirectionPosition(delta);
1374                 }
1375                 if (Vector<RenderBox*>* cleanLineFloats = line->floatsPtr()) {
1376                     Vector<RenderBox*>::iterator end = cleanLineFloats->end();
1377                     for (Vector<RenderBox*>::iterator f = cleanLineFloats->begin(); f != end; ++f) {
1378                         FloatingObject* floatingObject = insertFloatingObject(*f);
1379                         ASSERT(!floatingObject->m_originatingLine);
1380                         floatingObject->m_originatingLine = line;
1381                         setLogicalHeight(logicalTopForChild(*f) - marginBeforeForChild(*f) + delta);
1382                         positionNewFloats();
1383                     }
1384                 }
1385             }
1386             setLogicalHeight(lastRootBox()->lineBottomWithLeading());
1387         } else {
1388             // Delete all the remaining lines.
1389             deleteLineRange(layoutState, renderArena(), layoutState.endLine());
1390         }
1391     }
1392     
1393     if (m_floatingObjects && (layoutState.checkForFloatsFromLastLine() || positionNewFloats()) && lastRootBox()) {
1394         // In case we have a float on the last line, it might not be positioned up to now.
1395         // This has to be done before adding in the bottom border/padding, or the float will
1396         // include the padding incorrectly. -dwh
1397         if (layoutState.checkForFloatsFromLastLine()) {
1398             LayoutUnit bottomVisualOverflow = lastRootBox()->logicalBottomVisualOverflow();
1399             LayoutUnit bottomLayoutOverflow = lastRootBox()->logicalBottomLayoutOverflow();
1400             TrailingFloatsRootInlineBox* trailingFloatsLineBox = new (renderArena()) TrailingFloatsRootInlineBox(this);
1401             m_lineBoxes.appendLineBox(trailingFloatsLineBox);
1402             trailingFloatsLineBox->setConstructed();
1403             GlyphOverflowAndFallbackFontsMap textBoxDataMap;
1404             VerticalPositionCache verticalPositionCache;
1405             LayoutUnit blockLogicalHeight = logicalHeight();
1406             trailingFloatsLineBox->alignBoxesInBlockDirection(blockLogicalHeight, textBoxDataMap, verticalPositionCache);
1407             trailingFloatsLineBox->setLineTopBottomPositions(blockLogicalHeight, blockLogicalHeight, blockLogicalHeight, blockLogicalHeight);
1408             trailingFloatsLineBox->setPaginatedLineWidth(availableLogicalWidthForContent(blockLogicalHeight));
1409             LayoutRect logicalLayoutOverflow(0, blockLogicalHeight, 1, bottomLayoutOverflow - blockLogicalHeight);
1410             LayoutRect logicalVisualOverflow(0, blockLogicalHeight, 1, bottomVisualOverflow - blockLogicalHeight);
1411             trailingFloatsLineBox->setOverflowFromLogicalRects(logicalLayoutOverflow, logicalVisualOverflow, trailingFloatsLineBox->lineTop(), trailingFloatsLineBox->lineBottom());
1412         }
1413
1414         const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1415         FloatingObjectSetIterator it = floatingObjectSet.begin();
1416         FloatingObjectSetIterator end = floatingObjectSet.end();
1417         if (layoutState.lastFloat()) {
1418             FloatingObjectSetIterator lastFloatIterator = floatingObjectSet.find(layoutState.lastFloat());
1419             ASSERT(lastFloatIterator != end);
1420             ++lastFloatIterator;
1421             it = lastFloatIterator;
1422         }
1423         for (; it != end; ++it)
1424             appendFloatingObjectToLastLine(*it);
1425         layoutState.setLastFloat(!floatingObjectSet.isEmpty() ? floatingObjectSet.last() : 0);
1426     }
1427 }
1428
1429 void RenderBlock::repaintDirtyFloats(Vector<FloatWithRect>& floats)
1430 {
1431     size_t floatCount = floats.size();
1432     // Floats that did not have layout did not repaint when we laid them out. They would have
1433     // painted by now if they had moved, but if they stayed at (0, 0), they still need to be
1434     // painted.
1435     for (size_t i = 0; i < floatCount; ++i) {
1436         if (!floats[i].everHadLayout) {
1437             RenderBox* f = floats[i].object;
1438             if (!f->x() && !f->y() && f->checkForRepaintDuringLayout())
1439                 f->repaint();
1440         }
1441     }
1442 }
1443
1444 void RenderBlock::layoutInlineChildren(bool relayoutChildren, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom)
1445 {
1446     m_overflow.clear();
1447
1448     setLogicalHeight(borderBefore() + paddingBefore());
1449     
1450     // Lay out our hypothetical grid line as though it occurs at the top of the block.
1451     if (view()->layoutState() && view()->layoutState()->lineGrid() == this)
1452         layoutLineGridBox();
1453
1454     // Figure out if we should clear out our line boxes.
1455     // FIXME: Handle resize eventually!
1456     bool isFullLayout = !firstLineBox() || selfNeedsLayout() || relayoutChildren;
1457     LineLayoutState layoutState(isFullLayout, repaintLogicalTop, repaintLogicalBottom);
1458
1459     if (isFullLayout)
1460         lineBoxes()->deleteLineBoxes(renderArena());
1461
1462     // Text truncation only kicks in if your overflow isn't visible and your text-overflow-mode isn't
1463     // clip.
1464     // FIXME: CSS3 says that descendants that are clipped must also know how to truncate.  This is insanely
1465     // difficult to figure out (especially in the middle of doing layout), and is really an esoteric pile of nonsense
1466     // anyway, so we won't worry about following the draft here.
1467     bool hasTextOverflow = style()->textOverflow() && hasOverflowClip();
1468
1469     // Walk all the lines and delete our ellipsis line boxes if they exist.
1470     if (hasTextOverflow)
1471          deleteEllipsisLineBoxes();
1472
1473     if (firstChild()) {
1474         // layout replaced elements
1475         bool hasInlineChild = false;
1476         for (InlineWalker walker(this); !walker.atEnd(); walker.advance()) {
1477             RenderObject* o = walker.current();
1478             if (!hasInlineChild && o->isInline())
1479                 hasInlineChild = true;
1480
1481             if (o->isReplaced() || o->isFloating() || o->isPositioned()) {
1482                 RenderBox* box = toRenderBox(o);
1483
1484                 if (relayoutChildren || box->hasRelativeDimensions())
1485                     o->setChildNeedsLayout(true, MarkOnlyThis);
1486
1487                 // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
1488                 if (relayoutChildren && box->needsPreferredWidthsRecalculation())
1489                     o->setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
1490
1491                 if (o->isPositioned())
1492                     o->containingBlock()->insertPositionedObject(box);
1493                 else if (o->isFloating())
1494                     layoutState.floats().append(FloatWithRect(box));
1495                 else if (layoutState.isFullLayout() || o->needsLayout()) {
1496                     // Replaced elements
1497                     toRenderBox(o)->dirtyLineBoxes(layoutState.isFullLayout());
1498                 }
1499             } else if (o->isText() || (o->isRenderInline() && !walker.atEndOfInline())) {
1500                 if (!o->isText())
1501                     toRenderInline(o)->updateAlwaysCreateLineBoxes(layoutState.isFullLayout());
1502                 if (layoutState.isFullLayout() || o->selfNeedsLayout())
1503                     dirtyLineBoxesForRenderer(o, layoutState.isFullLayout());
1504                 o->setNeedsLayout(false);
1505             }
1506         }
1507
1508         layoutRunsAndFloats(layoutState, hasInlineChild);
1509     }
1510
1511     // Expand the last line to accommodate Ruby and emphasis marks.
1512     int lastLineAnnotationsAdjustment = 0;
1513     if (lastRootBox()) {
1514         LayoutUnit lowestAllowedPosition = max(lastRootBox()->lineBottom(), logicalHeight() + paddingAfter());
1515         if (!style()->isFlippedLinesWritingMode())
1516             lastLineAnnotationsAdjustment = lastRootBox()->computeUnderAnnotationAdjustment(lowestAllowedPosition);
1517         else
1518             lastLineAnnotationsAdjustment = lastRootBox()->computeOverAnnotationAdjustment(lowestAllowedPosition);
1519     }
1520
1521     // Now add in the bottom border/padding.
1522     setLogicalHeight(logicalHeight() + lastLineAnnotationsAdjustment + borderAfter() + paddingAfter() + scrollbarLogicalHeight());
1523
1524     if (!firstLineBox() && hasLineIfEmpty())
1525         setLogicalHeight(logicalHeight() + lineHeight(true, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes));
1526
1527     // See if we have any lines that spill out of our block.  If we do, then we will possibly need to
1528     // truncate text.
1529     if (hasTextOverflow)
1530         checkLinesForTextOverflow();
1531 }
1532
1533 void RenderBlock::checkFloatsInCleanLine(RootInlineBox* line, Vector<FloatWithRect>& floats, size_t& floatIndex, bool& encounteredNewFloat, bool& dirtiedByFloat)
1534 {
1535     Vector<RenderBox*>* cleanLineFloats = line->floatsPtr();
1536     if (!cleanLineFloats)
1537         return;
1538
1539     Vector<RenderBox*>::iterator end = cleanLineFloats->end();
1540     for (Vector<RenderBox*>::iterator it = cleanLineFloats->begin(); it != end; ++it) {
1541         RenderBox* floatingBox = *it;
1542         floatingBox->layoutIfNeeded();
1543         LayoutSize newSize(floatingBox->width() + floatingBox->marginWidth(), floatingBox->height() + floatingBox->marginHeight());
1544         ASSERT(floatIndex < floats.size());
1545         if (floats[floatIndex].object != floatingBox) {
1546             encounteredNewFloat = true;
1547             return;
1548         }
1549
1550         if (floats[floatIndex].rect.size() != newSize) {
1551             LayoutUnit floatTop = isHorizontalWritingMode() ? floats[floatIndex].rect.y() : floats[floatIndex].rect.x();
1552             LayoutUnit floatHeight = isHorizontalWritingMode() ? max(floats[floatIndex].rect.height(), newSize.height())
1553                                                                  : max(floats[floatIndex].rect.width(), newSize.width());
1554             floatHeight = min(floatHeight, MAX_LAYOUT_UNIT - floatTop);
1555             line->markDirty();
1556             markLinesDirtyInBlockRange(line->lineBottomWithLeading(), floatTop + floatHeight, line);
1557             floats[floatIndex].rect.setSize(newSize);
1558             dirtiedByFloat = true;
1559         }
1560         floatIndex++;
1561     }
1562 }
1563
1564 RootInlineBox* RenderBlock::determineStartPosition(LineLayoutState& layoutState, InlineBidiResolver& resolver)
1565 {
1566     RootInlineBox* curr = 0;
1567     RootInlineBox* last = 0;
1568
1569     // FIXME: This entire float-checking block needs to be broken into a new function.
1570     bool dirtiedByFloat = false;
1571     if (!layoutState.isFullLayout()) {
1572         // Paginate all of the clean lines.
1573         bool paginated = view()->layoutState() && view()->layoutState()->isPaginated();
1574         LayoutUnit paginationDelta = 0;
1575         size_t floatIndex = 0;
1576         for (curr = firstRootBox(); curr && !curr->isDirty(); curr = curr->nextRootBox()) {
1577             if (paginated) {
1578                 if (lineWidthForPaginatedLineChanged(curr)) {
1579                     curr->markDirty();
1580                     break;
1581                 }
1582                 paginationDelta -= curr->paginationStrut();
1583                 adjustLinePositionForPagination(curr, paginationDelta);
1584                 if (paginationDelta) {
1585                     if (containsFloats() || !layoutState.floats().isEmpty()) {
1586                         // FIXME: Do better eventually.  For now if we ever shift because of pagination and floats are present just go to a full layout.
1587                         layoutState.markForFullLayout();
1588                         break;
1589                     }
1590
1591                     layoutState.updateRepaintRangeFromBox(curr, paginationDelta);
1592                     curr->adjustBlockDirectionPosition(paginationDelta);
1593                 }
1594             }
1595
1596             // If a new float has been inserted before this line or before its last known float, just do a full layout.
1597             bool encounteredNewFloat = false;
1598             checkFloatsInCleanLine(curr, layoutState.floats(), floatIndex, encounteredNewFloat, dirtiedByFloat);
1599             if (encounteredNewFloat)
1600                 layoutState.markForFullLayout();
1601
1602             if (dirtiedByFloat || layoutState.isFullLayout())
1603                 break;
1604         }
1605         // Check if a new float has been inserted after the last known float.
1606         if (!curr && floatIndex < layoutState.floats().size())
1607             layoutState.markForFullLayout();
1608     }
1609
1610     if (layoutState.isFullLayout()) {
1611         // FIXME: This should just call deleteLineBoxTree, but that causes
1612         // crashes for fast/repaint tests.
1613         RenderArena* arena = renderArena();
1614         curr = firstRootBox();
1615         while (curr) {
1616             // Note: This uses nextRootBox() insted of nextLineBox() like deleteLineBoxTree does.
1617             RootInlineBox* next = curr->nextRootBox();
1618             curr->deleteLine(arena);
1619             curr = next;
1620         }
1621         ASSERT(!firstLineBox() && !lastLineBox());
1622     } else {
1623         if (curr) {
1624             // We have a dirty line.
1625             if (RootInlineBox* prevRootBox = curr->prevRootBox()) {
1626                 // We have a previous line.
1627                 if (!dirtiedByFloat && (!prevRootBox->endsWithBreak() || (prevRootBox->lineBreakObj()->isText() && prevRootBox->lineBreakPos() >= toRenderText(prevRootBox->lineBreakObj())->textLength())))
1628                     // The previous line didn't break cleanly or broke at a newline
1629                     // that has been deleted, so treat it as dirty too.
1630                     curr = prevRootBox;
1631             }
1632         } else {
1633             // No dirty lines were found.
1634             // If the last line didn't break cleanly, treat it as dirty.
1635             if (lastRootBox() && !lastRootBox()->endsWithBreak())
1636                 curr = lastRootBox();
1637         }
1638
1639         // If we have no dirty lines, then last is just the last root box.
1640         last = curr ? curr->prevRootBox() : lastRootBox();
1641     }
1642
1643     unsigned numCleanFloats = 0;
1644     if (!layoutState.floats().isEmpty()) {
1645         LayoutUnit savedLogicalHeight = logicalHeight();
1646         // Restore floats from clean lines.
1647         RootInlineBox* line = firstRootBox();
1648         while (line != curr) {
1649             if (Vector<RenderBox*>* cleanLineFloats = line->floatsPtr()) {
1650                 Vector<RenderBox*>::iterator end = cleanLineFloats->end();
1651                 for (Vector<RenderBox*>::iterator f = cleanLineFloats->begin(); f != end; ++f) {
1652                     FloatingObject* floatingObject = insertFloatingObject(*f);
1653                     ASSERT(!floatingObject->m_originatingLine);
1654                     floatingObject->m_originatingLine = line;
1655                     setLogicalHeight(logicalTopForChild(*f) - marginBeforeForChild(*f));
1656                     positionNewFloats();
1657                     ASSERT(layoutState.floats()[numCleanFloats].object == *f);
1658                     numCleanFloats++;
1659                 }
1660             }
1661             line = line->nextRootBox();
1662         }
1663         setLogicalHeight(savedLogicalHeight);
1664     }
1665     layoutState.setFloatIndex(numCleanFloats);
1666
1667     layoutState.lineInfo().setFirstLine(!last);
1668     layoutState.lineInfo().setPreviousLineBrokeCleanly(!last || last->endsWithBreak());
1669
1670     if (last) {
1671         setLogicalHeight(last->lineBottomWithLeading());
1672         InlineIterator iter = InlineIterator(this, last->lineBreakObj(), last->lineBreakPos());
1673         resolver.setPosition(iter, numberOfIsolateAncestors(iter));
1674         resolver.setStatus(last->lineBreakBidiStatus());
1675     } else {
1676         TextDirection direction = style()->direction();
1677         if (style()->unicodeBidi() == Plaintext)
1678             determineDirectionality(direction, InlineIterator(this, bidiFirstSkippingEmptyInlines(this), 0));
1679         resolver.setStatus(BidiStatus(direction, isOverride(style()->unicodeBidi())));
1680         InlineIterator iter = InlineIterator(this, bidiFirstSkippingEmptyInlines(this, &resolver), 0);
1681         resolver.setPosition(iter, numberOfIsolateAncestors(iter));
1682     }
1683     return curr;
1684 }
1685
1686 void RenderBlock::determineEndPosition(LineLayoutState& layoutState, RootInlineBox* startLine, InlineIterator& cleanLineStart, BidiStatus& cleanLineBidiStatus)
1687 {
1688     ASSERT(!layoutState.endLine());
1689     size_t floatIndex = layoutState.floatIndex();
1690     RootInlineBox* last = 0;
1691     for (RootInlineBox* curr = startLine->nextRootBox(); curr; curr = curr->nextRootBox()) {
1692         if (!curr->isDirty()) {
1693             bool encounteredNewFloat = false;
1694             bool dirtiedByFloat = false;
1695             checkFloatsInCleanLine(curr, layoutState.floats(), floatIndex, encounteredNewFloat, dirtiedByFloat);
1696             if (encounteredNewFloat)
1697                 return;
1698         }
1699         if (curr->isDirty())
1700             last = 0;
1701         else if (!last)
1702             last = curr;
1703     }
1704
1705     if (!last)
1706         return;
1707
1708     // At this point, |last| is the first line in a run of clean lines that ends with the last line
1709     // in the block.
1710
1711     RootInlineBox* prev = last->prevRootBox();
1712     cleanLineStart = InlineIterator(this, prev->lineBreakObj(), prev->lineBreakPos());
1713     cleanLineBidiStatus = prev->lineBreakBidiStatus();
1714     layoutState.setEndLineLogicalTop(prev->lineBottomWithLeading());
1715
1716     for (RootInlineBox* line = last; line; line = line->nextRootBox())
1717         line->extractLine(); // Disconnect all line boxes from their render objects while preserving
1718                              // their connections to one another.
1719
1720     layoutState.setEndLine(last);
1721 }
1722
1723 bool RenderBlock::checkPaginationAndFloatsAtEndLine(LineLayoutState& layoutState)
1724 {
1725     LayoutUnit lineDelta = logicalHeight() - layoutState.endLineLogicalTop();
1726
1727     bool paginated = view()->layoutState() && view()->layoutState()->isPaginated();
1728     if (paginated && inRenderFlowThread()) {
1729         // Check all lines from here to the end, and see if the hypothetical new position for the lines will result
1730         // in a different available line width.
1731         for (RootInlineBox* lineBox = layoutState.endLine(); lineBox; lineBox = lineBox->nextRootBox()) {
1732             if (paginated) {
1733                 // This isn't the real move we're going to do, so don't update the line box's pagination
1734                 // strut yet.
1735                 LayoutUnit oldPaginationStrut = lineBox->paginationStrut();
1736                 lineDelta -= oldPaginationStrut;
1737                 adjustLinePositionForPagination(lineBox, lineDelta);
1738                 lineBox->setPaginationStrut(oldPaginationStrut);
1739             }
1740             if (lineWidthForPaginatedLineChanged(lineBox, lineDelta))
1741                 return false;
1742         }
1743     }
1744     
1745     if (!lineDelta || !m_floatingObjects)
1746         return true;
1747     
1748     // See if any floats end in the range along which we want to shift the lines vertically.
1749     LayoutUnit logicalTop = min(logicalHeight(), layoutState.endLineLogicalTop());
1750
1751     RootInlineBox* lastLine = layoutState.endLine();
1752     while (RootInlineBox* nextLine = lastLine->nextRootBox())
1753         lastLine = nextLine;
1754
1755     LayoutUnit logicalBottom = lastLine->lineBottomWithLeading() + absoluteValue(lineDelta);
1756
1757     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1758     FloatingObjectSetIterator end = floatingObjectSet.end();
1759     for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1760         FloatingObject* f = *it;
1761         if (logicalBottomForFloat(f) >= logicalTop && logicalBottomForFloat(f) < logicalBottom)
1762             return false;
1763     }
1764
1765     return true;
1766 }
1767
1768 bool RenderBlock::matchedEndLine(LineLayoutState& layoutState, const InlineBidiResolver& resolver, const InlineIterator& endLineStart, const BidiStatus& endLineStatus)
1769 {
1770     if (resolver.position() == endLineStart) {
1771         if (resolver.status() != endLineStatus)
1772             return false;
1773         return checkPaginationAndFloatsAtEndLine(layoutState);
1774     }
1775
1776     // The first clean line doesn't match, but we can check a handful of following lines to try
1777     // to match back up.
1778     static int numLines = 8; // The # of lines we're willing to match against.
1779     RootInlineBox* originalEndLine = layoutState.endLine();
1780     RootInlineBox* line = originalEndLine;
1781     for (int i = 0; i < numLines && line; i++, line = line->nextRootBox()) {
1782         if (line->lineBreakObj() == resolver.position().m_obj && line->lineBreakPos() == resolver.position().m_pos) {
1783             // We have a match.
1784             if (line->lineBreakBidiStatus() != resolver.status())
1785                 return false; // ...but the bidi state doesn't match.
1786             
1787             bool matched = false;
1788             RootInlineBox* result = line->nextRootBox();
1789             layoutState.setEndLine(result);
1790             if (result) {
1791                 layoutState.setEndLineLogicalTop(line->lineBottomWithLeading());
1792                 matched = checkPaginationAndFloatsAtEndLine(layoutState);
1793             }
1794
1795             // Now delete the lines that we failed to sync.
1796             deleteLineRange(layoutState, renderArena(), originalEndLine, result);
1797             return matched;
1798         }
1799     }
1800
1801     return false;
1802 }
1803
1804 static inline bool skipNonBreakingSpace(const InlineIterator& it, const LineInfo& lineInfo)
1805 {
1806     if (it.m_obj->style()->nbspMode() != SPACE || it.current() != noBreakSpace)
1807         return false;
1808
1809     // FIXME: This is bad.  It makes nbsp inconsistent with space and won't work correctly
1810     // with m_minWidth/m_maxWidth.
1811     // Do not skip a non-breaking space if it is the first character
1812     // on a line after a clean line break (or on the first line, since previousLineBrokeCleanly starts off
1813     // |true|).
1814     if (lineInfo.isEmpty() && lineInfo.previousLineBrokeCleanly())
1815         return false;
1816
1817     return true;
1818 }
1819
1820 enum WhitespacePosition { LeadingWhitespace, TrailingWhitespace };
1821 static inline bool shouldCollapseWhiteSpace(const RenderStyle* style, const LineInfo& lineInfo, WhitespacePosition whitespacePosition)
1822 {
1823     // CSS2 16.6.1
1824     // If a space (U+0020) at the beginning of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is removed.
1825     // 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.
1826     // 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.
1827     return style->collapseWhiteSpace()
1828         || (whitespacePosition == TrailingWhitespace && style->whiteSpace() == PRE_WRAP && (!lineInfo.isEmpty() || !lineInfo.previousLineBrokeCleanly()));
1829 }
1830
1831 static bool requiresLineBoxForContent(RenderInline* flow, const LineInfo& lineInfo)
1832 {
1833     RenderObject* parent = flow->parent();
1834     if (flow->document()->inNoQuirksMode() 
1835         && (flow->style(lineInfo.isFirstLine())->lineHeight() != parent->style(lineInfo.isFirstLine())->lineHeight()
1836         || flow->style()->verticalAlign() != parent->style()->verticalAlign()
1837         || !parent->style()->font().fontMetrics().hasIdenticalAscentDescentAndLineGap(flow->style()->font().fontMetrics())))
1838         return true;
1839     return false;
1840 }
1841
1842 static bool alwaysRequiresLineBox(RenderInline* flow)
1843 {
1844     // FIXME: Right now, we only allow line boxes for inlines that are truly empty.
1845     // We need to fix this, though, because at the very least, inlines containing only
1846     // ignorable whitespace should should also have line boxes.
1847     return !flow->firstChild() && flow->hasInlineDirectionBordersPaddingOrMargin();
1848 }
1849
1850 static bool requiresLineBox(const InlineIterator& it, const LineInfo& lineInfo = LineInfo(), WhitespacePosition whitespacePosition = LeadingWhitespace)
1851 {
1852     if (it.m_obj->isFloatingOrPositioned())
1853         return false;
1854
1855     if (it.m_obj->isRenderInline() && !alwaysRequiresLineBox(toRenderInline(it.m_obj)) && !requiresLineBoxForContent(toRenderInline(it.m_obj), lineInfo))
1856         return false;
1857
1858     if (!shouldCollapseWhiteSpace(it.m_obj->style(), lineInfo, whitespacePosition) || it.m_obj->isBR())
1859         return true;
1860
1861     UChar current = it.current();
1862     return current != ' ' && current != '\t' && current != softHyphen && (current != '\n' || it.m_obj->preservesNewline())
1863     && !skipNonBreakingSpace(it, lineInfo);
1864 }
1865
1866 bool RenderBlock::generatesLineBoxesForInlineChild(RenderObject* inlineObj)
1867 {
1868     ASSERT(inlineObj->parent() == this);
1869
1870     InlineIterator it(this, inlineObj, 0);
1871     // FIXME: We should pass correct value for WhitespacePosition.
1872     while (!it.atEnd() && !requiresLineBox(it))
1873         it.increment();
1874
1875     return !it.atEnd();
1876 }
1877
1878 // FIXME: The entire concept of the skipTrailingWhitespace function is flawed, since we really need to be building
1879 // line boxes even for containers that may ultimately collapse away. Otherwise we'll never get positioned
1880 // elements quite right. In other words, we need to build this function's work into the normal line
1881 // object iteration process.
1882 // NB. this function will insert any floating elements that would otherwise
1883 // be skipped but it will not position them.
1884 void RenderBlock::LineBreaker::skipTrailingWhitespace(InlineIterator& iterator, const LineInfo& lineInfo)
1885 {
1886     while (!iterator.atEnd() && !requiresLineBox(iterator, lineInfo, TrailingWhitespace)) {
1887         RenderObject* object = iterator.m_obj;
1888         if (object->isPositioned())
1889             setStaticPositions(m_block, toRenderBox(object));
1890         else if (object->isFloating())
1891             m_block->insertFloatingObject(toRenderBox(object));
1892         iterator.increment();
1893     }
1894 }
1895
1896 void RenderBlock::LineBreaker::skipLeadingWhitespace(InlineBidiResolver& resolver, LineInfo& lineInfo,
1897                                                      FloatingObject* lastFloatFromPreviousLine, LineWidth& width)
1898 {
1899     while (!resolver.position().atEnd() && !requiresLineBox(resolver.position(), lineInfo, LeadingWhitespace)) {
1900         RenderObject* object = resolver.position().m_obj;
1901         if (object->isPositioned()) {
1902             setStaticPositions(m_block, toRenderBox(object));
1903             if (object->style()->isOriginalDisplayInlineType()) {
1904                 resolver.runs().addRun(createRun(0, 1, object, resolver));
1905                 lineInfo.incrementRunsFromLeadingWhitespace();
1906             }
1907         } else if (object->isFloating())
1908             m_block->positionNewFloatOnLine(m_block->insertFloatingObject(toRenderBox(object)), lastFloatFromPreviousLine, lineInfo, width);
1909         else if (object->isText() && object->style()->hasTextCombine() && object->isCombineText() && !toRenderCombineText(object)->isCombined()) {
1910             toRenderCombineText(object)->combineText();
1911             if (toRenderCombineText(object)->isCombined())
1912                 continue;
1913         }
1914         resolver.increment();
1915     }
1916     resolver.commitExplicitEmbedding();
1917 }
1918
1919 // This is currently just used for list markers and inline flows that have line boxes. Neither should
1920 // have an effect on whitespace at the start of the line.
1921 static bool shouldSkipWhitespaceAfterStartObject(RenderBlock* block, RenderObject* o, LineMidpointState& lineMidpointState)
1922 {
1923     RenderObject* next = bidiNextSkippingEmptyInlines(block, o);
1924     if (next && !next->isBR() && next->isText() && toRenderText(next)->textLength() > 0) {
1925         RenderText* nextText = toRenderText(next);
1926         UChar nextChar = nextText->characters()[0];
1927         if (nextText->style()->isCollapsibleWhiteSpace(nextChar)) {
1928             addMidpoint(lineMidpointState, InlineIterator(0, o, 0));
1929             return true;
1930         }
1931     }
1932
1933     return false;
1934 }
1935
1936 static inline float textWidth(RenderText* text, unsigned from, unsigned len, const Font& font, float xPos, bool isFixedPitch, bool collapseWhiteSpace)
1937 {
1938     if (isFixedPitch || (!from && len == text->textLength()) || text->style()->hasTextCombine())
1939         return text->width(from, len, font, xPos);
1940
1941     TextRun run = RenderBlock::constructTextRun(text, font, text->characters() + from, len, text->style());
1942     run.setCharactersLength(text->textLength() - from);
1943     ASSERT(run.charactersLength() >= run.length());
1944
1945     run.setCharacterScanForCodePath(!text->canUseSimpleFontCodePath());
1946     run.setTabSize(!collapseWhiteSpace, text->style()->tabSize());
1947     run.setXPos(xPos);
1948     return font.width(run);
1949 }
1950
1951 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)
1952 {
1953     // Map 'hyphenate-limit-{before,after}: auto;' to 2.
1954     if (minimumPrefixLength < 0)
1955         minimumPrefixLength = 2;
1956
1957     if (minimumSuffixLength < 0)
1958         minimumSuffixLength = 2;
1959
1960     if (pos - lastSpace <= minimumSuffixLength)
1961         return;
1962
1963     if (consecutiveHyphenatedLinesLimit >= 0 && consecutiveHyphenatedLines >= static_cast<unsigned>(consecutiveHyphenatedLinesLimit))
1964         return;
1965
1966     int hyphenWidth = measureHyphenWidth(text, font);
1967
1968     float maxPrefixWidth = availableWidth - xPos - hyphenWidth - lastSpaceWordSpacing;
1969     // If the maximum width available for the prefix before the hyphen is small, then it is very unlikely
1970     // that an hyphenation opportunity exists, so do not bother to look for it.
1971     if (maxPrefixWidth <= font.pixelSize() * 5 / 4)
1972         return;
1973
1974     TextRun run = RenderBlock::constructTextRun(text, font, text->characters() + lastSpace, pos - lastSpace, text->style());
1975     run.setCharactersLength(text->textLength() - lastSpace);
1976     ASSERT(run.charactersLength() >= run.length());
1977
1978     run.setTabSize(!collapseWhiteSpace, text->style()->tabSize());
1979     run.setXPos(xPos + lastSpaceWordSpacing);
1980
1981     unsigned prefixLength = font.offsetForPosition(run, maxPrefixWidth, false);
1982     if (prefixLength < static_cast<unsigned>(minimumPrefixLength))
1983         return;
1984
1985     prefixLength = lastHyphenLocation(text->characters() + lastSpace, pos - lastSpace, min(prefixLength, static_cast<unsigned>(pos - lastSpace - minimumSuffixLength)) + 1, localeIdentifier);
1986     if (!prefixLength || prefixLength < static_cast<unsigned>(minimumPrefixLength))
1987         return;
1988
1989     // When lastSapce is a space, which it always is except sometimes at the beginning of a line or after collapsed
1990     // space, it should not count towards hyphenate-limit-before.
1991     if (prefixLength == static_cast<unsigned>(minimumPrefixLength)) {
1992         UChar characterAtLastSpace = text->characters()[lastSpace];
1993         if (characterAtLastSpace == ' ' || characterAtLastSpace == '\n' || characterAtLastSpace == '\t' || characterAtLastSpace == noBreakSpace)
1994             return;
1995     }
1996
1997     ASSERT(pos - lastSpace - prefixLength >= static_cast<unsigned>(minimumSuffixLength));
1998
1999 #if !ASSERT_DISABLED
2000     float prefixWidth = hyphenWidth + textWidth(text, lastSpace, prefixLength, font, xPos, isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing;
2001     ASSERT(xPos + prefixWidth <= availableWidth);
2002 #else
2003     UNUSED_PARAM(isFixedPitch);
2004 #endif
2005
2006     lineBreak.moveTo(text, lastSpace + prefixLength, nextBreakable);
2007     hyphenated = true;
2008 }
2009
2010 class TrailingObjects {
2011 public:
2012     TrailingObjects();
2013     void setTrailingWhitespace(RenderText*);
2014     void clear();
2015     void appendBoxIfNeeded(RenderBox*);
2016
2017     enum CollapseFirstSpaceOrNot { DoNotCollapseFirstSpace, CollapseFirstSpace };
2018
2019     void updateMidpointsForTrailingBoxes(LineMidpointState&, const InlineIterator& lBreak, CollapseFirstSpaceOrNot);
2020
2021 private:
2022     RenderText* m_whitespace;
2023     Vector<RenderBox*, 4> m_boxes;
2024 };
2025
2026 TrailingObjects::TrailingObjects()
2027     : m_whitespace(0)
2028 {
2029 }
2030
2031 inline void TrailingObjects::setTrailingWhitespace(RenderText* whitespace)
2032 {
2033     ASSERT(whitespace);
2034     m_whitespace = whitespace;
2035 }
2036
2037 inline void TrailingObjects::clear()
2038 {
2039     m_whitespace = 0;
2040     m_boxes.clear();
2041 }
2042
2043 inline void TrailingObjects::appendBoxIfNeeded(RenderBox* box)
2044 {
2045     if (m_whitespace)
2046         m_boxes.append(box);
2047 }
2048
2049 void TrailingObjects::updateMidpointsForTrailingBoxes(LineMidpointState& lineMidpointState, const InlineIterator& lBreak, CollapseFirstSpaceOrNot collapseFirstSpace)
2050 {
2051     if (!m_whitespace)
2052         return;
2053
2054     // This object is either going to be part of the last midpoint, or it is going to be the actual endpoint.
2055     // In both cases we just decrease our pos by 1 level to exclude the space, allowing it to - in effect - collapse into the newline.
2056     if (lineMidpointState.numMidpoints % 2) {
2057         // Find the trailing space object's midpoint.
2058         int trailingSpaceMidpoint = lineMidpointState.numMidpoints - 1;
2059         for ( ; trailingSpaceMidpoint > 0 && lineMidpointState.midpoints[trailingSpaceMidpoint].m_obj != m_whitespace; --trailingSpaceMidpoint) { }
2060         ASSERT(trailingSpaceMidpoint >= 0);
2061         if (collapseFirstSpace == CollapseFirstSpace)
2062             lineMidpointState.midpoints[trailingSpaceMidpoint].m_pos--;
2063
2064         // Now make sure every single trailingPositionedBox following the trailingSpaceMidpoint properly stops and starts
2065         // ignoring spaces.
2066         size_t currentMidpoint = trailingSpaceMidpoint + 1;
2067         for (size_t i = 0; i < m_boxes.size(); ++i) {
2068             if (currentMidpoint >= lineMidpointState.numMidpoints) {
2069                 // We don't have a midpoint for this box yet.
2070                 InlineIterator ignoreStart(0, m_boxes[i], 0);
2071                 addMidpoint(lineMidpointState, ignoreStart); // Stop ignoring.
2072                 addMidpoint(lineMidpointState, ignoreStart); // Start ignoring again.
2073             } else {
2074                 ASSERT(lineMidpointState.midpoints[currentMidpoint].m_obj == m_boxes[i]);
2075                 ASSERT(lineMidpointState.midpoints[currentMidpoint + 1].m_obj == m_boxes[i]);
2076             }
2077             currentMidpoint += 2;
2078         }
2079     } else if (!lBreak.m_obj) {
2080         ASSERT(m_whitespace->isText());
2081         ASSERT(collapseFirstSpace == CollapseFirstSpace);
2082         // Add a new end midpoint that stops right at the very end.
2083         unsigned length = m_whitespace->textLength();
2084         unsigned pos = length >= 2 ? length - 2 : UINT_MAX;
2085         InlineIterator endMid(0, m_whitespace, pos);
2086         addMidpoint(lineMidpointState, endMid);
2087         for (size_t i = 0; i < m_boxes.size(); ++i) {
2088             InlineIterator ignoreStart(0, m_boxes[i], 0);
2089             addMidpoint(lineMidpointState, ignoreStart); // Stop ignoring spaces.
2090             addMidpoint(lineMidpointState, ignoreStart); // Start ignoring again.
2091         }
2092     }
2093 }
2094
2095 void RenderBlock::LineBreaker::reset()
2096 {
2097     m_positionedObjects.clear();
2098     m_hyphenated = false;
2099     m_clear = CNONE;
2100 }
2101
2102 InlineIterator RenderBlock::LineBreaker::nextLineBreak(InlineBidiResolver& resolver, LineInfo& lineInfo,
2103     LineBreakIteratorInfo& lineBreakIteratorInfo, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines)
2104 {
2105     reset();
2106
2107     ASSERT(resolver.position().root() == m_block);
2108
2109     bool appliedStartWidth = resolver.position().m_pos > 0;
2110     bool includeEndWidth = true;
2111     LineMidpointState& lineMidpointState = resolver.midpointState();
2112
2113     LineWidth width(m_block, lineInfo.isFirstLine());
2114
2115     skipLeadingWhitespace(resolver, lineInfo, lastFloatFromPreviousLine, width);
2116
2117     if (resolver.position().atEnd())
2118         return resolver.position();
2119
2120     // This variable is used only if whitespace isn't set to PRE, and it tells us whether
2121     // or not we are currently ignoring whitespace.
2122     bool ignoringSpaces = false;
2123     InlineIterator ignoreStart;
2124
2125     // This variable tracks whether the very last character we saw was a space.  We use
2126     // this to detect when we encounter a second space so we know we have to terminate
2127     // a run.
2128     bool currentCharacterIsSpace = false;
2129     bool currentCharacterIsWS = false;
2130     TrailingObjects trailingObjects;
2131
2132     InlineIterator lBreak = resolver.position();
2133
2134     // FIXME: It is error-prone to split the position object out like this.
2135     // Teach this code to work with objects instead of this split tuple.
2136     InlineIterator current = resolver.position();
2137     RenderObject* last = current.m_obj;
2138     bool atStart = true;
2139
2140     bool startingNewParagraph = lineInfo.previousLineBrokeCleanly();
2141     lineInfo.setPreviousLineBrokeCleanly(false);
2142
2143     bool autoWrapWasEverTrueOnLine = false;
2144     bool floatsFitOnLine = true;
2145
2146     // Firefox and Opera will allow a table cell to grow to fit an image inside it under
2147     // very specific circumstances (in order to match common WinIE renderings).
2148     // Not supporting the quirk has caused us to mis-render some real sites. (See Bugzilla 10517.)
2149     RenderStyle* blockStyle = m_block->style();
2150     bool allowImagesToBreak = !m_block->document()->inQuirksMode() || !m_block->isTableCell() || !blockStyle->logicalWidth().isIntrinsicOrAuto();
2151
2152     EWhiteSpace currWS = blockStyle->whiteSpace();
2153     EWhiteSpace lastWS = currWS;
2154     while (current.m_obj) {
2155         RenderStyle* currentStyle = current.m_obj->style();
2156         RenderObject* next = bidiNextSkippingEmptyInlines(m_block, current.m_obj);
2157         if (next && next->parent() && !next->parent()->isDescendantOf(current.m_obj->parent()))
2158             includeEndWidth = true;
2159
2160         currWS = current.m_obj->isReplaced() ? current.m_obj->parent()->style()->whiteSpace() : currentStyle->whiteSpace();
2161         lastWS = last->isReplaced() ? last->parent()->style()->whiteSpace() : last->style()->whiteSpace();
2162
2163         bool autoWrap = RenderStyle::autoWrap(currWS);
2164         autoWrapWasEverTrueOnLine = autoWrapWasEverTrueOnLine || autoWrap;
2165
2166 #if ENABLE(SVG)
2167         bool preserveNewline = current.m_obj->isSVGInlineText() ? false : RenderStyle::preserveNewline(currWS);
2168 #else
2169         bool preserveNewline = RenderStyle::preserveNewline(currWS);
2170 #endif
2171
2172         bool collapseWhiteSpace = RenderStyle::collapseWhiteSpace(currWS);
2173
2174         if (current.m_obj->isBR()) {
2175             if (width.fitsOnLine()) {
2176                 lBreak.moveToStartOf(current.m_obj);
2177                 lBreak.increment();
2178
2179                 // A <br> always breaks a line, so don't let the line be collapsed
2180                 // away. Also, the space at the end of a line with a <br> does not
2181                 // get collapsed away.  It only does this if the previous line broke
2182                 // cleanly.  Otherwise the <br> has no effect on whether the line is
2183                 // empty or not.
2184                 if (startingNewParagraph)
2185                     lineInfo.setEmpty(false, m_block, &width);
2186                 trailingObjects.clear();
2187                 lineInfo.setPreviousLineBrokeCleanly(true);
2188
2189                 if (!lineInfo.isEmpty())
2190                     m_clear = currentStyle->clear();
2191             }
2192             goto end;
2193         }
2194
2195         if (current.m_obj->isPositioned()) {
2196             // If our original display wasn't an inline type, then we can
2197             // go ahead and determine our static inline position now.
2198             RenderBox* box = toRenderBox(current.m_obj);
2199             bool isInlineType = box->style()->isOriginalDisplayInlineType();
2200             if (!isInlineType)
2201                 m_block->setStaticInlinePositionForChild(box, m_block->logicalHeight(), m_block->startOffsetForContent(m_block->logicalHeight()));
2202             else  {
2203                 // If our original display was an INLINE type, then we can go ahead
2204                 // and determine our static y position now.
2205                 box->layer()->setStaticBlockPosition(m_block->logicalHeight());
2206             }
2207
2208             // If we're ignoring spaces, we have to stop and include this object and
2209             // then start ignoring spaces again.
2210             if (isInlineType || current.m_obj->container()->isRenderInline()) {
2211                 if (ignoringSpaces) {
2212                     ignoreStart.m_obj = current.m_obj;
2213                     ignoreStart.m_pos = 0;
2214                     addMidpoint(lineMidpointState, ignoreStart); // Stop ignoring spaces.
2215                     addMidpoint(lineMidpointState, ignoreStart); // Start ignoring again.
2216                 }
2217                 trailingObjects.appendBoxIfNeeded(box);
2218             } else
2219                 m_positionedObjects.append(box);
2220         } else if (current.m_obj->isFloating()) {
2221             RenderBox* floatBox = toRenderBox(current.m_obj);
2222             FloatingObject* f = m_block->insertFloatingObject(floatBox);
2223             // check if it fits in the current line.
2224             // If it does, position it now, otherwise, position
2225             // it after moving to next line (in newLine() func)
2226             if (floatsFitOnLine && width.fitsOnLine(m_block->logicalWidthForFloat(f))) {
2227                 m_block->positionNewFloatOnLine(f, lastFloatFromPreviousLine, lineInfo, width);
2228                 if (lBreak.m_obj == current.m_obj) {
2229                     ASSERT(!lBreak.m_pos);
2230                     lBreak.increment();
2231                 }
2232             } else
2233                 floatsFitOnLine = false;
2234         } else if (current.m_obj->isRenderInline()) {
2235             // Right now, we should only encounter empty inlines here.
2236             ASSERT(!current.m_obj->firstChild());
2237
2238             RenderInline* flowBox = toRenderInline(current.m_obj);
2239
2240             // Now that some inline flows have line boxes, if we are already ignoring spaces, we need
2241             // to make sure that we stop to include this object and then start ignoring spaces again.
2242             // If this object is at the start of the line, we need to behave like list markers and
2243             // start ignoring spaces.
2244             bool requiresLineBox = alwaysRequiresLineBox(flowBox);
2245             if (requiresLineBox || requiresLineBoxForContent(flowBox, lineInfo)) {
2246                 // An empty inline that only has line-height, vertical-align or font-metrics will only get a
2247                 // line box to affect the height of the line if the rest of the line is not empty.
2248                 if (requiresLineBox)
2249                     lineInfo.setEmpty(false, m_block, &width);
2250                 if (ignoringSpaces) {
2251                     trailingObjects.clear();
2252                     addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, 0)); // Stop ignoring spaces.
2253                     addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, 0)); // Start ignoring again.
2254                 } else if (blockStyle->collapseWhiteSpace() && resolver.position().m_obj == current.m_obj
2255                     && shouldSkipWhitespaceAfterStartObject(m_block, current.m_obj, lineMidpointState)) {
2256                     // Like with list markers, we start ignoring spaces to make sure that any
2257                     // additional spaces we see will be discarded.
2258                     currentCharacterIsSpace = true;
2259                     currentCharacterIsWS = true;
2260                     ignoringSpaces = true;
2261                 }
2262             }
2263
2264             width.addUncommittedWidth(borderPaddingMarginStart(flowBox) + borderPaddingMarginEnd(flowBox));
2265         } else if (current.m_obj->isReplaced()) {
2266             RenderBox* replacedBox = toRenderBox(current.m_obj);
2267             replacedBox->layoutIfNeeded();
2268
2269             // Break on replaced elements if either has normal white-space.
2270             if ((autoWrap || RenderStyle::autoWrap(lastWS)) && (!current.m_obj->isImage() || allowImagesToBreak)) {
2271                 width.commit();
2272                 lBreak.moveToStartOf(current.m_obj);
2273             }
2274
2275             if (ignoringSpaces)
2276                 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, 0));
2277
2278             lineInfo.setEmpty(false, m_block, &width);
2279             ignoringSpaces = false;
2280             currentCharacterIsSpace = false;
2281             currentCharacterIsWS = false;
2282             trailingObjects.clear();
2283
2284             // Optimize for a common case. If we can't find whitespace after the list
2285             // item, then this is all moot.
2286             LayoutUnit replacedLogicalWidth = m_block->logicalWidthForChild(replacedBox) + m_block->marginStartForChild(replacedBox) + m_block->marginEndForChild(replacedBox) + inlineLogicalWidth(current.m_obj);
2287             if (current.m_obj->isListMarker()) {
2288                 if (blockStyle->collapseWhiteSpace() && shouldSkipWhitespaceAfterStartObject(m_block, current.m_obj, lineMidpointState)) {
2289                     // Like with inline flows, we start ignoring spaces to make sure that any
2290                     // additional spaces we see will be discarded.
2291                     currentCharacterIsSpace = true;
2292                     currentCharacterIsWS = true;
2293                     ignoringSpaces = true;
2294                 }
2295                 if (toRenderListMarker(current.m_obj)->isInside())
2296                     width.addUncommittedWidth(replacedLogicalWidth);
2297             } else
2298                 width.addUncommittedWidth(replacedLogicalWidth);
2299             if (current.m_obj->isRubyRun())
2300                 width.applyOverhang(toRenderRubyRun(current.m_obj), last, next);
2301         } else if (current.m_obj->isText()) {
2302             if (!current.m_pos)
2303                 appliedStartWidth = false;
2304
2305             RenderText* t = toRenderText(current.m_obj);
2306
2307 #if ENABLE(SVG)
2308             bool isSVGText = t->isSVGInlineText();
2309 #endif
2310
2311             RenderStyle* style = t->style(lineInfo.isFirstLine());
2312             if (style->hasTextCombine() && current.m_obj->isCombineText() && !toRenderCombineText(current.m_obj)->isCombined())
2313                 toRenderCombineText(current.m_obj)->combineText();
2314
2315             const Font& f = style->font();
2316             bool isFixedPitch = f.isFixedPitch();
2317             bool canHyphenate = style->hyphens() == HyphensAuto && WebCore::canHyphenate(style->locale());
2318
2319             int lastSpace = current.m_pos;
2320             float wordSpacing = currentStyle->wordSpacing();
2321             float lastSpaceWordSpacing = 0;
2322
2323             // Non-zero only when kerning is enabled, in which case we measure words with their trailing
2324             // space, then subtract its width.
2325             float wordTrailingSpaceWidth = f.typesettingFeatures() & Kerning ? f.width(constructTextRun(t, f, &space, 1, style)) + wordSpacing : 0;
2326
2327             float wrapW = width.uncommittedWidth() + inlineLogicalWidth(current.m_obj, !appliedStartWidth, true);
2328             float charWidth = 0;
2329             bool breakNBSP = autoWrap && currentStyle->nbspMode() == SPACE;
2330             // Auto-wrapping text should wrap in the middle of a word only if it could not wrap before the word,
2331             // which is only possible if the word is the first thing on the line, that is, if |w| is zero.
2332             bool breakWords = currentStyle->breakWords() && ((autoWrap && !width.committedWidth()) || currWS == PRE);
2333             bool midWordBreak = false;
2334             bool breakAll = currentStyle->wordBreak() == BreakAllWordBreak && autoWrap;
2335             float hyphenWidth = 0;
2336
2337             if (t->isWordBreak()) {
2338                 width.commit();
2339                 lBreak.moveToStartOf(current.m_obj);
2340                 ASSERT(current.m_pos == t->textLength());
2341             }
2342
2343             for (; current.m_pos < t->textLength(); current.fastIncrementInTextNode()) {
2344                 bool previousCharacterIsSpace = currentCharacterIsSpace;
2345                 bool previousCharacterIsWS = currentCharacterIsWS;
2346                 UChar c = current.current();
2347                 currentCharacterIsSpace = c == ' ' || c == '\t' || (!preserveNewline && (c == '\n'));
2348
2349                 if (!collapseWhiteSpace || !currentCharacterIsSpace)
2350                     lineInfo.setEmpty(false, m_block, &width);
2351
2352                 if (c == softHyphen && autoWrap && !hyphenWidth && style->hyphens() != HyphensNone) {
2353                     hyphenWidth = measureHyphenWidth(t, f);
2354                     width.addUncommittedWidth(hyphenWidth);
2355                 }
2356
2357                 bool applyWordSpacing = false;
2358
2359                 currentCharacterIsWS = currentCharacterIsSpace || (breakNBSP && c == noBreakSpace);
2360
2361                 if ((breakAll || breakWords) && !midWordBreak) {
2362                     wrapW += charWidth;
2363                     bool midWordBreakIsBeforeSurrogatePair = U16_IS_LEAD(c) && current.m_pos + 1 < t->textLength() && U16_IS_TRAIL(t->characters()[current.m_pos + 1]);
2364                     charWidth = textWidth(t, current.m_pos, midWordBreakIsBeforeSurrogatePair ? 2 : 1, f, width.committedWidth() + wrapW, isFixedPitch, collapseWhiteSpace);
2365                     midWordBreak = width.committedWidth() + wrapW + charWidth > width.availableWidth();
2366                 }
2367
2368                 if ((lineBreakIteratorInfo.first != t) || (lineBreakIteratorInfo.second.string() != t->characters())) {
2369                     lineBreakIteratorInfo.first = t;
2370                     lineBreakIteratorInfo.second.reset(t->characters(), t->textLength(), style->locale());
2371                 }
2372
2373                 bool betweenWords = c == '\n' || (currWS != PRE && !atStart && isBreakable(lineBreakIteratorInfo.second, current.m_pos, current.m_nextBreakablePosition, breakNBSP)
2374                     && (style->hyphens() != HyphensNone || (current.previousInSameNode() != softHyphen)));
2375
2376                 if (betweenWords || midWordBreak) {
2377                     bool stoppedIgnoringSpaces = false;
2378                     if (ignoringSpaces) {
2379                         if (!currentCharacterIsSpace) {
2380                             // Stop ignoring spaces and begin at this
2381                             // new point.
2382                             ignoringSpaces = false;
2383                             lastSpaceWordSpacing = 0;
2384                             lastSpace = current.m_pos; // e.g., "Foo    goo", don't add in any of the ignored spaces.
2385                             addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos));
2386                             stoppedIgnoringSpaces = true;
2387                         } else {
2388                             // Just keep ignoring these spaces.
2389                             continue;
2390                         }
2391                     }
2392
2393                     float additionalTmpW;
2394                     if (wordTrailingSpaceWidth && currentCharacterIsSpace)
2395                         additionalTmpW = textWidth(t, lastSpace, current.m_pos + 1 - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) - wordTrailingSpaceWidth + lastSpaceWordSpacing;
2396                     else
2397                         additionalTmpW = textWidth(t, lastSpace, current.m_pos - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing;
2398                     width.addUncommittedWidth(additionalTmpW);
2399                     if (!appliedStartWidth) {
2400                         width.addUncommittedWidth(inlineLogicalWidth(current.m_obj, true, false));
2401                         appliedStartWidth = true;
2402                     }
2403
2404                     applyWordSpacing =  wordSpacing && currentCharacterIsSpace && !previousCharacterIsSpace;
2405
2406                     if (!width.committedWidth() && autoWrap && !width.fitsOnLine())
2407                         width.fitBelowFloats();
2408
2409                     if (autoWrap || breakWords) {
2410                         // If we break only after white-space, consider the current character
2411                         // as candidate width for this line.
2412                         bool lineWasTooWide = false;
2413                         if (width.fitsOnLine() && currentCharacterIsWS && currentStyle->breakOnlyAfterWhiteSpace() && !midWordBreak) {
2414                             float charWidth = textWidth(t, current.m_pos, 1, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) + (applyWordSpacing ? wordSpacing : 0);
2415                             // Check if line is too big even without the extra space
2416                             // at the end of the line. If it is not, do nothing.
2417                             // If the line needs the extra whitespace to be too long,
2418                             // then move the line break to the space and skip all
2419                             // additional whitespace.
2420                             if (!width.fitsOnLine(charWidth)) {
2421                                 lineWasTooWide = true;
2422                                 lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2423                                 skipTrailingWhitespace(lBreak, lineInfo);
2424                             }
2425                         }
2426                         if (lineWasTooWide || !width.fitsOnLine()) {
2427                             if (canHyphenate && !width.fitsOnLine()) {
2428                                 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);
2429                                 if (m_hyphenated)
2430                                     goto end;
2431                             }
2432                             if (lBreak.atTextParagraphSeparator()) {
2433                                 if (!stoppedIgnoringSpaces && current.m_pos > 0) {
2434                                     // We need to stop right before the newline and then start up again.
2435                                     addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos - 1)); // Stop
2436                                     addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos)); // Start
2437                                 }
2438                                 lBreak.increment();
2439                                 lineInfo.setPreviousLineBrokeCleanly(true);
2440                             }
2441                             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)
2442                                 m_hyphenated = true;
2443                             goto end; // Didn't fit. Jump to the end.
2444                         } else {
2445                             if (!betweenWords || (midWordBreak && !autoWrap))
2446                                 width.addUncommittedWidth(-additionalTmpW);
2447                             if (hyphenWidth) {
2448                                 // Subtract the width of the soft hyphen out since we fit on a line.
2449                                 width.addUncommittedWidth(-hyphenWidth);
2450                                 hyphenWidth = 0;
2451                             }
2452                         }
2453                     }
2454
2455                     if (c == '\n' && preserveNewline) {
2456                         if (!stoppedIgnoringSpaces && current.m_pos > 0) {
2457                             // We need to stop right before the newline and then start up again.
2458                             addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos - 1)); // Stop
2459                             addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos)); // Start
2460                         }
2461                         lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2462                         lBreak.increment();
2463                         lineInfo.setPreviousLineBrokeCleanly(true);
2464                         return lBreak;
2465                     }
2466
2467                     if (autoWrap && betweenWords) {
2468                         width.commit();
2469                         wrapW = 0;
2470                         lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2471                         // Auto-wrapping text should not wrap in the middle of a word once it has had an
2472                         // opportunity to break after a word.
2473                         breakWords = false;
2474                     }
2475
2476                     if (midWordBreak && !U16_IS_TRAIL(c) && !(category(c) & (Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining))) {
2477                         // Remember this as a breakable position in case
2478                         // adding the end width forces a break.
2479                         lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2480                         midWordBreak &= (breakWords || breakAll);
2481                     }
2482
2483                     if (betweenWords) {
2484                         lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
2485                         lastSpace = current.m_pos;
2486                     }
2487
2488                     if (!ignoringSpaces && currentStyle->collapseWhiteSpace()) {
2489                         // If we encounter a newline, or if we encounter a
2490                         // second space, we need to go ahead and break up this
2491                         // run and enter a mode where we start collapsing spaces.
2492                         if (currentCharacterIsSpace && previousCharacterIsSpace) {
2493                             ignoringSpaces = true;
2494
2495                             // We just entered a mode where we are ignoring
2496                             // spaces. Create a midpoint to terminate the run
2497                             // before the second space.
2498                             addMidpoint(lineMidpointState, ignoreStart);
2499                             trailingObjects.updateMidpointsForTrailingBoxes(lineMidpointState, InlineIterator(), TrailingObjects::DoNotCollapseFirstSpace);
2500                         }
2501                     }
2502                 } else if (ignoringSpaces) {
2503                     // Stop ignoring spaces and begin at this
2504                     // new point.
2505                     ignoringSpaces = false;
2506                     lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
2507                     lastSpace = current.m_pos; // e.g., "Foo    goo", don't add in any of the ignored spaces.
2508                     addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos));
2509                 }
2510
2511 #if ENABLE(SVG)
2512                 if (isSVGText && current.m_pos > 0) {
2513                     // Force creation of new InlineBoxes for each absolute positioned character (those that start new text chunks).
2514                     if (toRenderSVGInlineText(t)->characterStartsNewTextChunk(current.m_pos)) {
2515                         addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos - 1));
2516                         addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos));
2517                     }
2518                 }
2519 #endif
2520
2521                 if (currentCharacterIsSpace && !previousCharacterIsSpace) {
2522                     ignoreStart.m_obj = current.m_obj;
2523                     ignoreStart.m_pos = current.m_pos;
2524                 }
2525
2526                 if (!currentCharacterIsWS && previousCharacterIsWS) {
2527                     if (autoWrap && currentStyle->breakOnlyAfterWhiteSpace())
2528                         lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2529                 }
2530
2531                 if (collapseWhiteSpace && currentCharacterIsSpace && !ignoringSpaces)
2532                     trailingObjects.setTrailingWhitespace(toRenderText(current.m_obj));
2533                 else if (!currentStyle->collapseWhiteSpace() || !currentCharacterIsSpace)
2534                     trailingObjects.clear();
2535
2536                 atStart = false;
2537             }
2538
2539             // IMPORTANT: current.m_pos is > length here!
2540             float additionalTmpW = ignoringSpaces ? 0 : textWidth(t, lastSpace, current.m_pos - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing;
2541             width.addUncommittedWidth(additionalTmpW + inlineLogicalWidth(current.m_obj, !appliedStartWidth, includeEndWidth));
2542             includeEndWidth = false;
2543
2544             if (!width.fitsOnLine()) {
2545                 if (canHyphenate)
2546                     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);
2547
2548                 if (!m_hyphenated && lBreak.previousInSameNode() == softHyphen && style->hyphens() != HyphensNone)
2549                     m_hyphenated = true;
2550
2551                 if (m_hyphenated)
2552                     goto end;
2553             }
2554         } else
2555             ASSERT_NOT_REACHED();
2556
2557         bool checkForBreak = autoWrap;
2558         if (width.committedWidth() && !width.fitsOnLine() && lBreak.m_obj && currWS == NOWRAP)
2559             checkForBreak = true;
2560         else if (next && current.m_obj->isText() && next->isText() && !next->isBR() && (autoWrap || (next->style()->autoWrap()))) {
2561             if (currentCharacterIsSpace)
2562                 checkForBreak = true;
2563             else {
2564                 RenderText* nextText = toRenderText(next);
2565                 if (nextText->textLength()) {
2566                     UChar c = nextText->characters()[0];
2567                     checkForBreak = (c == ' ' || c == '\t' || (c == '\n' && !next->preservesNewline()));
2568                     // If the next item on the line is text, and if we did not end with
2569                     // a space, then the next text run continues our word (and so it needs to
2570                     // keep adding to |tmpW|. Just update and continue.
2571                 } else if (nextText->isWordBreak())
2572                     checkForBreak = true;
2573
2574                 if (!width.fitsOnLine() && !width.committedWidth())
2575                     width.fitBelowFloats();
2576
2577                 bool canPlaceOnLine = width.fitsOnLine() || !autoWrapWasEverTrueOnLine;
2578                 if (canPlaceOnLine && checkForBreak) {
2579                     width.commit();
2580                     lBreak.moveToStartOf(next);
2581                 }
2582             }
2583         }
2584
2585         if (checkForBreak && !width.fitsOnLine()) {
2586             // if we have floats, try to get below them.
2587             if (currentCharacterIsSpace && !ignoringSpaces && currentStyle->collapseWhiteSpace())
2588                 trailingObjects.clear();
2589
2590             if (width.committedWidth())
2591                 goto end;
2592
2593             width.fitBelowFloats();
2594
2595             // |width| may have been adjusted because we got shoved down past a float (thus
2596             // giving us more room), so we need to retest, and only jump to
2597             // the end label if we still don't fit on the line. -dwh
2598             if (!width.fitsOnLine())
2599                 goto end;
2600         }
2601
2602         if (!current.m_obj->isFloatingOrPositioned()) {
2603             last = current.m_obj;
2604             if (last->isReplaced() && autoWrap && (!last->isImage() || allowImagesToBreak) && (!last->isListMarker() || toRenderListMarker(last)->isInside())) {
2605                 width.commit();
2606                 lBreak.moveToStartOf(next);
2607             }
2608         }
2609
2610         // Clear out our character space bool, since inline <pre>s don't collapse whitespace
2611         // with adjacent inline normal/nowrap spans.
2612         if (!collapseWhiteSpace)
2613             currentCharacterIsSpace = false;
2614
2615         current.moveToStartOf(next);
2616         atStart = false;
2617     }
2618
2619     if (width.fitsOnLine() || lastWS == NOWRAP)
2620         lBreak.clear();
2621
2622  end:
2623     if (lBreak == resolver.position() && (!lBreak.m_obj || !lBreak.m_obj->isBR())) {
2624         // we just add as much as possible
2625         if (blockStyle->whiteSpace() == PRE) {
2626             // FIXME: Don't really understand this case.
2627             if (current.m_pos) {
2628                 // FIXME: This should call moveTo which would clear m_nextBreakablePosition
2629                 // this code as-is is likely wrong.
2630                 lBreak.m_obj = current.m_obj;
2631                 lBreak.m_pos = current.m_pos - 1;
2632             } else
2633                 lBreak.moveTo(last, last->isText() ? last->length() : 0);
2634         } else if (lBreak.m_obj) {
2635             // Don't ever break in the middle of a word if we can help it.
2636             // There's no room at all. We just have to be on this line,
2637             // even though we'll spill out.
2638             lBreak.moveTo(current.m_obj, current.m_pos);
2639         }
2640     }
2641
2642     // make sure we consume at least one char/object.
2643     if (lBreak == resolver.position())
2644         lBreak.increment();
2645
2646     // Sanity check our midpoints.
2647     checkMidpoints(lineMidpointState, lBreak);
2648
2649     trailingObjects.updateMidpointsForTrailingBoxes(lineMidpointState, lBreak, TrailingObjects::CollapseFirstSpace);
2650
2651     // We might have made lBreak an iterator that points past the end
2652     // of the object. Do this adjustment to make it point to the start
2653     // of the next object instead to avoid confusing the rest of the
2654     // code.
2655     if (lBreak.m_pos > 0) {
2656         lBreak.m_pos--;
2657         lBreak.increment();
2658     }
2659
2660     return lBreak;
2661 }
2662
2663 void RenderBlock::addOverflowFromInlineChildren()
2664 {
2665     LayoutUnit endPadding = hasOverflowClip() ? paddingEnd() : ZERO_LAYOUT_UNIT;
2666     // FIXME: Need to find another way to do this, since scrollbars could show when we don't want them to.
2667     if (hasOverflowClip() && !endPadding && node() && node()->isRootEditableElement() && style()->isLeftToRightDirection())
2668         endPadding = 1;
2669     for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
2670         addLayoutOverflow(curr->paddedLayoutOverflowRect(endPadding));
2671         if (!hasOverflowClip())
2672             addVisualOverflow(curr->visualOverflowRect(curr->lineTop(), curr->lineBottom()));
2673     }
2674 }
2675
2676 void RenderBlock::deleteEllipsisLineBoxes()
2677 {
2678     for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox())
2679         curr->clearTruncation();
2680 }
2681
2682 void RenderBlock::checkLinesForTextOverflow()
2683 {
2684     // Determine the width of the ellipsis using the current font.
2685     // FIXME: CSS3 says this is configurable, also need to use 0x002E (FULL STOP) if horizontal ellipsis is "not renderable"
2686     const Font& font = style()->font();
2687     DEFINE_STATIC_LOCAL(AtomicString, ellipsisStr, (&horizontalEllipsis, 1));
2688     const Font& firstLineFont = firstLineStyle()->font();
2689     int firstLineEllipsisWidth = firstLineFont.width(constructTextRun(this, firstLineFont, &horizontalEllipsis, 1, firstLineStyle()));
2690     int ellipsisWidth = (font == firstLineFont) ? firstLineEllipsisWidth : font.width(constructTextRun(this, font, &horizontalEllipsis, 1, style()));
2691
2692     // For LTR text truncation, we want to get the right edge of our padding box, and then we want to see
2693     // if the right edge of a line box exceeds that.  For RTL, we use the left edge of the padding box and
2694     // check the left edge of the line box to see if it is less
2695     // Include the scrollbar for overflow blocks, which means we want to use "contentWidth()"
2696     bool ltr = style()->isLeftToRightDirection();
2697     for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
2698         LayoutUnit blockRightEdge = logicalRightOffsetForLine(curr->y(), curr == firstRootBox());
2699         LayoutUnit blockLeftEdge = logicalLeftOffsetForLine(curr->y(), curr == firstRootBox());
2700         LayoutUnit lineBoxEdge = ltr ? curr->x() + curr->logicalWidth() : curr->x();
2701         if ((ltr && lineBoxEdge > blockRightEdge) || (!ltr && lineBoxEdge < blockLeftEdge)) {
2702             // This line spills out of our box in the appropriate direction.  Now we need to see if the line
2703             // can be truncated.  In order for truncation to be possible, the line must have sufficient space to
2704             // accommodate our truncation string, and no replaced elements (images, tables) can overlap the ellipsis
2705             // space.
2706             LayoutUnit width = curr == firstRootBox() ? firstLineEllipsisWidth : ellipsisWidth;
2707             LayoutUnit blockEdge = ltr ? blockRightEdge : blockLeftEdge;
2708             if (curr->lineCanAccommodateEllipsis(ltr, blockEdge, lineBoxEdge, width))
2709                 curr->placeEllipsis(ellipsisStr, ltr, blockLeftEdge, blockRightEdge, width);
2710         }
2711     }
2712 }
2713
2714 bool RenderBlock::positionNewFloatOnLine(FloatingObject* newFloat, FloatingObject* lastFloatFromPreviousLine, LineInfo& lineInfo, LineWidth& width)
2715 {
2716     if (!positionNewFloats())
2717         return false;
2718
2719     width.shrinkAvailableWidthForNewFloatIfNeeded(newFloat);
2720
2721     // We only connect floats to lines for pagination purposes if the floats occur at the start of
2722     // the line and the previous line had a hard break (so this line is either the first in the block
2723     // or follows a <br>).
2724     if (!newFloat->m_paginationStrut || !lineInfo.previousLineBrokeCleanly() || !lineInfo.isEmpty())
2725         return true;
2726
2727     const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2728     ASSERT(floatingObjectSet.last() == newFloat);
2729
2730     LayoutUnit floatLogicalTop = logicalTopForFloat(newFloat);
2731     int paginationStrut = newFloat->m_paginationStrut;
2732
2733     if (floatLogicalTop - paginationStrut != logicalHeight() + lineInfo.floatPaginationStrut())
2734         return true;
2735
2736     FloatingObjectSetIterator it = floatingObjectSet.end();
2737     --it; // Last float is newFloat, skip that one.
2738     FloatingObjectSetIterator begin = floatingObjectSet.begin();
2739     while (it != begin) {
2740         --it;
2741         FloatingObject* f = *it;
2742         if (f == lastFloatFromPreviousLine)
2743             break;
2744         if (logicalTopForFloat(f) == logicalHeight() + lineInfo.floatPaginationStrut()) {
2745             f->m_paginationStrut += paginationStrut;
2746             RenderBox* o = f->m_renderer;
2747             setLogicalTopForChild(o, logicalTopForChild(o) + marginBeforeForChild(o) + paginationStrut);
2748             if (o->isRenderBlock())
2749                 toRenderBlock(o)->setChildNeedsLayout(true, MarkOnlyThis);
2750             o->layoutIfNeeded();
2751             // Save the old logical top before calling removePlacedObject which will set
2752             // isPlaced to false. Otherwise it will trigger an assert in logicalTopForFloat.
2753             LayoutUnit oldLogicalTop = logicalTopForFloat(f);
2754             m_floatingObjects->removePlacedObject(f);
2755             setLogicalTopForFloat(f, oldLogicalTop + paginationStrut);
2756             m_floatingObjects->addPlacedObject(f);
2757         }
2758     }
2759
2760     // Just update the line info's pagination strut without altering our logical height yet. If the line ends up containing
2761     // no content, then we don't want to improperly grow the height of the block.
2762     lineInfo.setFloatPaginationStrut(lineInfo.floatPaginationStrut() + paginationStrut);
2763     return true;
2764 }
2765
2766 LayoutUnit RenderBlock::startAlignedOffsetForLine(RenderBox* child, LayoutUnit position, bool firstLine)
2767 {
2768     ETextAlign textAlign = style()->textAlign();
2769
2770     if (textAlign == TASTART) // FIXME: Handle TAEND here
2771         return startOffsetForLine(position, firstLine);
2772
2773     // updateLogicalWidthForAlignment() handles the direction of the block so no need to consider it here
2774     float logicalLeft;
2775     float availableLogicalWidth;
2776     logicalLeft = logicalLeftOffsetForLine(logicalHeight(), false);
2777     availableLogicalWidth = logicalRightOffsetForLine(logicalHeight(), false) - logicalLeft;
2778     float totalLogicalWidth = logicalWidthForChild(child);
2779     updateLogicalWidthForAlignment(textAlign, 0l, logicalLeft, totalLogicalWidth, availableLogicalWidth, 0);
2780
2781     if (!style()->isLeftToRightDirection())
2782         return logicalWidth() - (logicalLeft + totalLogicalWidth);
2783     return logicalLeft;
2784 }
2785
2786
2787 void RenderBlock::layoutLineGridBox()
2788 {
2789     if (style()->lineGrid() == RenderStyle::initialLineGrid()) {
2790         setLineGridBox(0);
2791         return;
2792     }
2793     
2794     setLineGridBox(0);
2795
2796     RootInlineBox* lineGridBox = new (renderArena()) RootInlineBox(this);
2797     lineGridBox->setHasTextChildren(); // Needed to make the line ascent/descent actually be honored in quirks mode.
2798     lineGridBox->setConstructed();
2799     GlyphOverflowAndFallbackFontsMap textBoxDataMap;
2800     VerticalPositionCache verticalPositionCache;
2801     lineGridBox->alignBoxesInBlockDirection(logicalHeight(), textBoxDataMap, verticalPositionCache);
2802     
2803     setLineGridBox(lineGridBox);
2804     
2805     // FIXME: If any of the characteristics of the box change compared to the old one, then we need to do a deep dirtying
2806     // (similar to what happens when the page height changes). Ideally, though, we only do this if someone is actually snapping
2807     // to this grid.
2808 }
2809
2810 }