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