https://bugs.webkit.org/show_bug.cgi?id=47021
[WebKit-https.git] / WebCore / rendering / RenderBlockLineLayout.cpp
1 /*
2  * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
3  * Copyright (C) 2003, 2004, 2006, 2007, 2008, 2009, 2010 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 "CharacterNames.h"
27 #include "Hyphenation.h"
28 #include "InlineIterator.h"
29 #include "InlineTextBox.h"
30 #include "Logging.h"
31 #include "RenderArena.h"
32 #include "RenderInline.h"
33 #include "RenderLayer.h"
34 #include "RenderListMarker.h"
35 #include "RenderView.h"
36 #include "Settings.h"
37 #include "TrailingFloatsRootInlineBox.h"
38 #include "break_lines.h"
39 #include <wtf/AlwaysInline.h>
40 #include <wtf/RefCountedLeakCounter.h>
41 #include <wtf/StdLibExtras.h>
42 #include <wtf/Vector.h>
43
44 #if ENABLE(SVG)
45 #include "RenderSVGInlineText.h"
46 #include "SVGRootInlineBox.h"
47 #endif
48
49 using namespace std;
50 using namespace WTF;
51 using namespace Unicode;
52
53 namespace WebCore {
54
55 // We don't let our line box tree for a single line get any deeper than this.
56 const unsigned cMaxLineDepth = 200;
57
58 static int getBorderPaddingMargin(RenderBoxModelObject* child, bool endOfInline)
59 {
60     bool leftSide = (child->style()->isLeftToRightDirection()) ? !endOfInline : endOfInline;
61     if (leftSide)
62         return child->marginLeft() + child->paddingLeft() + child->borderLeft();
63     return child->marginRight() + child->paddingRight() + child->borderRight();
64 }
65
66 static int inlineWidth(RenderObject* child, bool start = true, bool end = true)
67 {
68     unsigned lineDepth = 1;
69     int extraWidth = 0;
70     RenderObject* parent = child->parent();
71     while (parent->isInline() && !parent->isInlineBlockOrInlineTable() && lineDepth++ < cMaxLineDepth) {
72         if (start && !child->previousSibling())
73             extraWidth += getBorderPaddingMargin(toRenderBoxModelObject(parent), false);
74         if (end && !child->nextSibling())
75             extraWidth += getBorderPaddingMargin(toRenderBoxModelObject(parent), true);
76         child = parent;
77         parent = child->parent();
78     }
79     return extraWidth;
80 }
81
82 static void checkMidpoints(LineMidpointState& lineMidpointState, InlineIterator& lBreak)
83 {
84     // Check to see if our last midpoint is a start point beyond the line break.  If so,
85     // shave it off the list, and shave off a trailing space if the previous end point doesn't
86     // preserve whitespace.
87     if (lBreak.obj && lineMidpointState.numMidpoints && !(lineMidpointState.numMidpoints % 2)) {
88         InlineIterator* midpoints = lineMidpointState.midpoints.data();
89         InlineIterator& endpoint = midpoints[lineMidpointState.numMidpoints - 2];
90         const InlineIterator& startpoint = midpoints[lineMidpointState.numMidpoints - 1];
91         InlineIterator currpoint = endpoint;
92         while (!currpoint.atEnd() && currpoint != startpoint && currpoint != lBreak)
93             currpoint.increment();
94         if (currpoint == lBreak) {
95             // We hit the line break before the start point.  Shave off the start point.
96             lineMidpointState.numMidpoints--;
97             if (endpoint.obj->style()->collapseWhiteSpace())
98                 endpoint.pos--;
99         }
100     }    
101 }
102
103 static void addMidpoint(LineMidpointState& lineMidpointState, const InlineIterator& midpoint)
104 {
105     if (lineMidpointState.midpoints.size() <= lineMidpointState.numMidpoints)
106         lineMidpointState.midpoints.grow(lineMidpointState.numMidpoints + 10);
107
108     InlineIterator* midpoints = lineMidpointState.midpoints.data();
109     midpoints[lineMidpointState.numMidpoints++] = midpoint;
110 }
111
112 void RenderBlock::appendRunsForObject(int start, int end, RenderObject* obj, InlineBidiResolver& resolver)
113 {
114     if (start > end || obj->isFloating() ||
115         (obj->isPositioned() && !obj->style()->hasStaticX() && !obj->style()->hasStaticY() && !obj->container()->isRenderInline()))
116         return;
117
118     LineMidpointState& lineMidpointState = resolver.midpointState();
119     bool haveNextMidpoint = (lineMidpointState.currentMidpoint < lineMidpointState.numMidpoints);
120     InlineIterator nextMidpoint;
121     if (haveNextMidpoint)
122         nextMidpoint = lineMidpointState.midpoints[lineMidpointState.currentMidpoint];
123     if (lineMidpointState.betweenMidpoints) {
124         if (!(haveNextMidpoint && nextMidpoint.obj == obj))
125             return;
126         // This is a new start point. Stop ignoring objects and 
127         // adjust our start.
128         lineMidpointState.betweenMidpoints = false;
129         start = nextMidpoint.pos;
130         lineMidpointState.currentMidpoint++;
131         if (start < end)
132             return appendRunsForObject(start, end, obj, resolver);
133     } else {
134         if (!haveNextMidpoint || (obj != nextMidpoint.obj)) {
135             resolver.addRun(new (obj->renderArena()) BidiRun(start, end, obj, resolver.context(), resolver.dir()));
136             return;
137         }
138
139         // An end midpoint has been encountered within our object.  We
140         // need to go ahead and append a run with our endpoint.
141         if (static_cast<int>(nextMidpoint.pos + 1) <= end) {
142             lineMidpointState.betweenMidpoints = true;
143             lineMidpointState.currentMidpoint++;
144             if (nextMidpoint.pos != UINT_MAX) { // UINT_MAX means stop at the object and don't include any of it.
145                 if (static_cast<int>(nextMidpoint.pos + 1) > start)
146                     resolver.addRun(new (obj->renderArena())
147                         BidiRun(start, nextMidpoint.pos + 1, obj, resolver.context(), resolver.dir()));
148                 return appendRunsForObject(nextMidpoint.pos + 1, end, obj, resolver);
149             }
150         } else
151            resolver.addRun(new (obj->renderArena()) BidiRun(start, end, obj, resolver.context(), resolver.dir()));
152     }
153 }
154
155 static inline InlineBox* createInlineBoxForRenderer(RenderObject* obj, bool isRootLineBox, bool isOnlyRun = false)
156 {
157     if (isRootLineBox)
158         return toRenderBlock(obj)->createAndAppendRootInlineBox();
159     
160     if (obj->isText()) {
161         InlineTextBox* textBox = toRenderText(obj)->createInlineTextBox();
162         // We only treat a box as text for a <br> if we are on a line by ourself or in strict mode
163         // (Note the use of strict mode.  In "almost strict" mode, we don't treat the box for <br> as text.)
164         if (obj->isBR())
165             textBox->setIsText(isOnlyRun || obj->document()->inNoQuirksMode());
166         return textBox;
167     }
168     
169     if (obj->isBox())
170         return toRenderBox(obj)->createInlineBox();
171     
172     return toRenderInline(obj)->createAndAppendInlineFlowBox();
173 }
174
175 static inline void dirtyLineBoxesForRenderer(RenderObject* o, bool fullLayout)
176 {
177     if (o->isText()) {
178         if (o->preferredLogicalWidthsDirty() && o->isCounter())
179             toRenderText(o)->computePreferredLogicalWidths(0); // FIXME: Counters depend on this hack. No clue why. Should be investigated and removed.
180         toRenderText(o)->dirtyLineBoxes(fullLayout);
181     } else
182         toRenderInline(o)->dirtyLineBoxes(fullLayout);
183 }
184
185 InlineFlowBox* RenderBlock::createLineBoxes(RenderObject* obj, bool firstLine)
186 {
187     // See if we have an unconstructed line box for this object that is also
188     // the last item on the line.
189     unsigned lineDepth = 1;
190     InlineFlowBox* childBox = 0;
191     InlineFlowBox* parentBox = 0;
192     InlineFlowBox* result = 0;
193     do {
194         ASSERT(obj->isRenderInline() || obj == this);
195         
196         // Get the last box we made for this render object.
197         parentBox = obj->isRenderInline() ? toRenderInline(obj)->lastLineBox() : toRenderBlock(obj)->lastLineBox();
198
199         // If this box is constructed then it is from a previous line, and we need
200         // to make a new box for our line.  If this box is unconstructed but it has
201         // something following it on the line, then we know we have to make a new box
202         // as well.  In this situation our inline has actually been split in two on
203         // the same line (this can happen with very fancy language mixtures).
204         bool constructedNewBox = false;
205         if (!parentBox || parentBox->isConstructed() || parentBox->nextOnLine()) {
206             // We need to make a new box for this render object.  Once
207             // made, we need to place it at the end of the current line.
208             InlineBox* newBox = createInlineBoxForRenderer(obj, obj == this);
209             ASSERT(newBox->isInlineFlowBox());
210             parentBox = static_cast<InlineFlowBox*>(newBox);
211             parentBox->setFirstLineStyleBit(firstLine);
212             constructedNewBox = true;
213         }
214
215         if (!result)
216             result = parentBox;
217
218         // If we have hit the block itself, then |box| represents the root
219         // inline box for the line, and it doesn't have to be appended to any parent
220         // inline.
221         if (childBox)
222             parentBox->addToLine(childBox);
223
224         if (!constructedNewBox || obj == this)
225             break;
226
227         childBox = parentBox;        
228
229         // If we've exceeded our line depth, then jump straight to the root and skip all the remaining
230         // intermediate inline flows.
231         obj = (++lineDepth >= cMaxLineDepth) ? this : obj->parent();
232
233     } while (true);
234
235     return result;
236 }
237
238 RootInlineBox* RenderBlock::constructLine(unsigned runCount, BidiRun* firstRun, BidiRun* lastRun, bool firstLine, bool lastLine, RenderObject* endObject)
239 {
240     ASSERT(firstRun);
241
242     InlineFlowBox* parentBox = 0;
243     for (BidiRun* r = firstRun; r; r = r->next()) {
244         // Create a box for our object.
245         bool isOnlyRun = (runCount == 1);
246         if (runCount == 2 && !r->m_object->isListMarker())
247             isOnlyRun = (!style()->isLeftToRightDirection() ? lastRun : firstRun)->m_object->isListMarker();
248
249         InlineBox* box = createInlineBoxForRenderer(r->m_object, false, isOnlyRun);
250         r->m_box = box;
251
252         ASSERT(box);
253         if (!box)
254             continue;
255
256         // If we have no parent box yet, or if the run is not simply a sibling,
257         // then we need to construct inline boxes as necessary to properly enclose the
258         // run's inline box.
259         if (!parentBox || parentBox->renderer() != r->m_object->parent())
260             // Create new inline boxes all the way back to the appropriate insertion point.
261             parentBox = createLineBoxes(r->m_object->parent(), firstLine);
262
263         // Append the inline box to this line.
264         parentBox->addToLine(box);
265
266         bool visuallyOrdered = r->m_object->style()->visuallyOrdered();
267         box->setBidiLevel(visuallyOrdered ? 0 : r->level());
268
269         if (box->isInlineTextBox()) {
270             InlineTextBox* text = static_cast<InlineTextBox*>(box);
271             text->setStart(r->m_start);
272             text->setLen(r->m_stop - r->m_start);
273             text->m_dirOverride = r->dirOverride(visuallyOrdered);
274             if (r->m_hasHyphen)
275                 text->setHasHyphen(true);
276         }
277     }
278
279     // We should have a root inline box.  It should be unconstructed and
280     // be the last continuation of our line list.
281     ASSERT(lastLineBox() && !lastLineBox()->isConstructed());
282
283     // Set bits on our inline flow boxes that indicate which sides should
284     // paint borders/margins/padding.  This knowledge will ultimately be used when
285     // we determine the horizontal positions and widths of all the inline boxes on
286     // the line.
287     lastLineBox()->determineSpacingForFlowBoxes(lastLine, endObject);
288
289     // Now mark the line boxes as being constructed.
290     lastLineBox()->setConstructed();
291
292     // Return the last line.
293     return lastRootBox();
294 }
295
296 void RenderBlock::computeInlineDirectionPositionsForLine(RootInlineBox* lineBox, bool firstLine, BidiRun* firstRun, BidiRun* trailingSpaceRun, bool reachedEnd, GlyphOverflowAndFallbackFontsMap& textBoxDataMap)
297 {
298     // First determine our total width.
299     int availableWidth = availableLogicalWidthForLine(height(), firstLine);
300     int totWidth = lineBox->getFlowSpacingLogicalWidth();
301     bool needsWordSpacing = false;
302     unsigned numSpaces = 0;
303     ETextAlign textAlign = style()->textAlign();
304
305     for (BidiRun* r = firstRun; r; r = r->next()) {
306         if (!r->m_box || r->m_object->isPositioned() || r->m_box->isLineBreak())
307             continue; // Positioned objects are only participating to figure out their
308                       // correct static x position.  They have no effect on the width.
309                       // Similarly, line break boxes have no effect on the width.
310         if (r->m_object->isText()) {
311             RenderText* rt = toRenderText(r->m_object);
312
313             if (textAlign == JUSTIFY && r != trailingSpaceRun) {
314                 const UChar* characters = rt->characters();
315                 for (int i = r->m_start; i < r->m_stop; i++) {
316                     UChar c = characters[i];
317                     if (c == ' ' || c == '\n' || c == '\t')
318                         numSpaces++;
319                 }
320             }
321
322             if (int length = rt->textLength()) {
323                 if (!r->m_start && needsWordSpacing && isSpaceOrNewline(rt->characters()[r->m_start]))
324                     totWidth += rt->style(firstLine)->font().wordSpacing();
325                 needsWordSpacing = !isSpaceOrNewline(rt->characters()[r->m_stop - 1]) && r->m_stop == length;          
326             }
327             HashSet<const SimpleFontData*> fallbackFonts;
328             GlyphOverflow glyphOverflow;
329             int hyphenWidth = 0;
330             if (static_cast<InlineTextBox*>(r->m_box)->hasHyphen()) {
331                 const AtomicString& hyphenString = rt->style()->hyphenString();
332                 hyphenWidth = rt->style(firstLine)->font().width(TextRun(hyphenString.characters(), hyphenString.length()));
333             }
334             r->m_box->setLogicalWidth(rt->width(r->m_start, r->m_stop - r->m_start, totWidth, firstLine, &fallbackFonts, &glyphOverflow) + hyphenWidth);
335             if (!fallbackFonts.isEmpty()) {
336                 ASSERT(r->m_box->isText());
337                 GlyphOverflowAndFallbackFontsMap::iterator it = textBoxDataMap.add(static_cast<InlineTextBox*>(r->m_box), make_pair(Vector<const SimpleFontData*>(), GlyphOverflow())).first;
338                 ASSERT(it->second.first.isEmpty());
339                 copyToVector(fallbackFonts, it->second.first);
340             }
341             if ((glyphOverflow.top || glyphOverflow.bottom || glyphOverflow.left || glyphOverflow.right)) {
342                 ASSERT(r->m_box->isText());
343                 GlyphOverflowAndFallbackFontsMap::iterator it = textBoxDataMap.add(static_cast<InlineTextBox*>(r->m_box), make_pair(Vector<const SimpleFontData*>(), GlyphOverflow())).first;
344                 it->second.second = glyphOverflow;
345             }
346         } else if (!r->m_object->isRenderInline()) {
347             RenderBox* renderBox = toRenderBox(r->m_object);
348             renderBox->computeLogicalWidth();
349             r->m_box->setLogicalWidth(renderBox->width());
350             totWidth += renderBox->marginLeft() + renderBox->marginRight();
351         }
352
353         totWidth += r->m_box->logicalWidth();
354     }
355
356     // Armed with the total width of the line (without justification),
357     // we now examine our text-align property in order to determine where to position the
358     // objects horizontally.  The total width of the line can be increased if we end up
359     // justifying text.
360     int x = logicalLeftOffsetForLine(height(), firstLine);
361     switch (textAlign) {
362         case LEFT:
363         case WEBKIT_LEFT:
364             // The direction of the block should determine what happens with wide lines.  In
365             // particular with RTL blocks, wide lines should still spill out to the left.
366             if (style()->isLeftToRightDirection()) {
367                 if (totWidth > availableWidth && trailingSpaceRun)
368                     trailingSpaceRun->m_box->setLogicalWidth(max(0, trailingSpaceRun->m_box->logicalWidth() - totWidth + availableWidth));
369             } else {
370                 if (trailingSpaceRun)
371                     trailingSpaceRun->m_box->setLogicalWidth(0);
372                 else if (totWidth > availableWidth)
373                     x -= (totWidth - availableWidth);
374             }
375             break;
376         case JUSTIFY:
377             if (numSpaces && !reachedEnd && !lineBox->endsWithBreak()) {
378                 if (trailingSpaceRun) {
379                     totWidth -= trailingSpaceRun->m_box->logicalWidth();
380                     trailingSpaceRun->m_box->setLogicalWidth(0);
381                 }
382                 break;
383             }
384             // fall through
385         case TAAUTO:
386             numSpaces = 0;
387             // for right to left fall through to right aligned
388             if (style()->isLeftToRightDirection()) {
389                 if (totWidth > availableWidth && trailingSpaceRun)
390                     trailingSpaceRun->m_box->setLogicalWidth(max(0, trailingSpaceRun->m_box->logicalWidth() - totWidth + availableWidth));
391                 break;
392             }
393         case RIGHT:
394         case WEBKIT_RIGHT:
395             // Wide lines spill out of the block based off direction.
396             // So even if text-align is right, if direction is LTR, wide lines should overflow out of the right
397             // side of the block.
398             if (style()->isLeftToRightDirection()) {
399                 if (trailingSpaceRun) {
400                     totWidth -= trailingSpaceRun->m_box->logicalWidth();
401                     trailingSpaceRun->m_box->setLogicalWidth(0);
402                 }
403                 if (totWidth < availableWidth)
404                     x += availableWidth - totWidth;
405             } else {
406                 if (totWidth > availableWidth && trailingSpaceRun) {
407                     trailingSpaceRun->m_box->setLogicalWidth(max(0, trailingSpaceRun->m_box->logicalWidth() - totWidth + availableWidth));
408                     totWidth -= trailingSpaceRun->m_box->logicalWidth();
409                 } else
410                     x += availableWidth - totWidth;
411             }
412             break;
413         case CENTER:
414         case WEBKIT_CENTER:
415             int trailingSpaceWidth = 0;
416             if (trailingSpaceRun) {
417                 totWidth -= trailingSpaceRun->m_box->logicalWidth();
418                 trailingSpaceWidth = min(trailingSpaceRun->m_box->logicalWidth(), (availableWidth - totWidth + 1) / 2);
419                 trailingSpaceRun->m_box->setLogicalWidth(max(0, trailingSpaceWidth));
420             }
421             if (style()->isLeftToRightDirection())
422                 x += max((availableWidth - totWidth) / 2, 0);
423             else
424                 x += totWidth > availableWidth ? (availableWidth - totWidth) : (availableWidth - totWidth) / 2 - trailingSpaceWidth;
425             break;
426     }
427
428     if (numSpaces) {
429         for (BidiRun* r = firstRun; r; r = r->next()) {
430             if (!r->m_box || r == trailingSpaceRun)
431                 continue;
432
433             int spaceAdd = 0;
434             if (r->m_object->isText()) {
435                 unsigned spaces = 0;
436                 const UChar* characters = toRenderText(r->m_object)->characters();
437                 for (int i = r->m_start; i < r->m_stop; i++) {
438                     UChar c = characters[i];
439                     if (c == ' ' || c == '\n' || c == '\t')
440                         spaces++;
441                 }
442
443                 ASSERT(spaces <= numSpaces);
444
445                 // Only justify text if whitespace is collapsed.
446                 if (r->m_object->style()->collapseWhiteSpace()) {
447                     spaceAdd = (availableWidth - totWidth) * spaces / numSpaces;
448                     static_cast<InlineTextBox*>(r->m_box)->setSpaceAdd(spaceAdd);
449                     totWidth += spaceAdd;
450                 }
451                 numSpaces -= spaces;
452                 if (!numSpaces)
453                     break;
454             }
455         }
456     }
457
458     // The widths of all runs are now known.  We can now place every inline box (and
459     // compute accurate widths for the inline flow boxes).
460     needsWordSpacing = false;
461     lineBox->placeBoxesInInlineDirection(x, needsWordSpacing, textBoxDataMap);
462 }
463
464 void RenderBlock::computeBlockDirectionPositionsForLine(RootInlineBox* lineBox, BidiRun* firstRun, GlyphOverflowAndFallbackFontsMap& textBoxDataMap)
465 {
466     setLogicalHeight(lineBox->alignBoxesInBlockDirection(height(), textBoxDataMap));
467     lineBox->setBlockHeight(height());
468
469     // Now make sure we place replaced render objects correctly.
470     for (BidiRun* r = firstRun; r; r = r->next()) {
471         ASSERT(r->m_box);
472         if (!r->m_box)
473             continue; // Skip runs with no line boxes.
474
475         // Align positioned boxes with the top of the line box.  This is
476         // a reasonable approximation of an appropriate y position.
477         if (r->m_object->isPositioned())
478             r->m_box->setY(height());
479
480         // Position is used to properly position both replaced elements and
481         // to update the static normal flow x/y of positioned elements.
482         if (r->m_object->isText())
483             toRenderText(r->m_object)->positionLineBox(r->m_box);
484         else if (r->m_object->isBox())
485             toRenderBox(r->m_object)->positionLineBox(r->m_box);
486     }
487     // Positioned objects and zero-length text nodes destroy their boxes in
488     // position(), which unnecessarily dirties the line.
489     lineBox->markDirty(false);
490 }
491
492 static inline bool isCollapsibleSpace(UChar character, RenderText* renderer)
493 {
494     if (character == ' ' || character == '\t' || character == softHyphen)
495         return true;
496     if (character == '\n')
497         return !renderer->style()->preserveNewline();
498     if (character == noBreakSpace)
499         return renderer->style()->nbspMode() == SPACE;
500     return false;
501 }
502
503 void RenderBlock::layoutInlineChildren(bool relayoutChildren, int& repaintTop, int& repaintBottom)
504 {
505     bool useRepaintBounds = false;
506     
507     m_overflow.clear();
508         
509     setLogicalHeight(borderTop() + paddingTop());
510     int toAdd = borderBottom() + paddingBottom() + horizontalScrollbarHeight();
511
512     // Figure out if we should clear out our line boxes.
513     // FIXME: Handle resize eventually!
514     bool fullLayout = !firstLineBox() || selfNeedsLayout() || relayoutChildren;
515     if (fullLayout)
516         lineBoxes()->deleteLineBoxes(renderArena());
517
518     // Text truncation only kicks in if your overflow isn't visible and your text-overflow-mode isn't
519     // clip.
520     // FIXME: CSS3 says that descendants that are clipped must also know how to truncate.  This is insanely
521     // difficult to figure out (especially in the middle of doing layout), and is really an esoteric pile of nonsense
522     // anyway, so we won't worry about following the draft here.
523     bool hasTextOverflow = style()->textOverflow() && hasOverflowClip();
524
525     // Walk all the lines and delete our ellipsis line boxes if they exist.
526     if (hasTextOverflow)
527          deleteEllipsisLineBoxes();
528
529     if (firstChild()) {
530         // layout replaced elements
531         bool endOfInline = false;
532         RenderObject* o = bidiFirst(this, 0, false);
533         Vector<FloatWithRect> floats;
534         bool hasInlineChild = false;
535         while (o) {
536             if (!hasInlineChild && o->isInline())
537                 hasInlineChild = true;
538
539             if (o->isReplaced() || o->isFloating() || o->isPositioned()) {
540                 RenderBox* box = toRenderBox(o);
541                 
542                 if (relayoutChildren || o->style()->width().isPercent() || o->style()->height().isPercent())
543                     o->setChildNeedsLayout(true, false);
544                     
545                 // If relayoutChildren is set and we have percentage padding, we also need to invalidate the child's pref widths.
546                 if (relayoutChildren && (o->style()->paddingLeft().isPercent() || o->style()->paddingRight().isPercent()))
547                     o->setPreferredLogicalWidthsDirty(true, false);
548             
549                 if (o->isPositioned())
550                     o->containingBlock()->insertPositionedObject(box);
551                 else if (o->isFloating())
552                     floats.append(FloatWithRect(box));
553                 else if (fullLayout || o->needsLayout()) {
554                     // Replaced elements
555                     toRenderBox(o)->dirtyLineBoxes(fullLayout);
556                     o->layoutIfNeeded();
557                 }
558             } else if (o->isText() || (o->isRenderInline() && !endOfInline)) {
559                 if (fullLayout || o->selfNeedsLayout())
560                     dirtyLineBoxesForRenderer(o, fullLayout);
561                 o->setNeedsLayout(false);
562                 if (!o->isText())
563                     toRenderInline(o)->invalidateVerticalPosition(); // FIXME: Should do better here and not always invalidate everything.
564             }
565             o = bidiNext(this, o, 0, false, &endOfInline);
566         }
567
568         // We want to skip ahead to the first dirty line
569         InlineBidiResolver resolver;
570         unsigned floatIndex;
571         bool firstLine = true;
572         bool previousLineBrokeCleanly = true;
573         RootInlineBox* startLine = determineStartPosition(firstLine, fullLayout, previousLineBrokeCleanly, resolver, floats, floatIndex,
574                                                           useRepaintBounds, repaintTop, repaintBottom);
575
576         if (fullLayout && hasInlineChild && !selfNeedsLayout()) {
577             setNeedsLayout(true, false);  // Mark ourselves as needing a full layout. This way we'll repaint like
578                                           // we're supposed to.
579             RenderView* v = view();
580             if (v && !v->doingFullRepaint() && hasLayer()) {
581                 // Because we waited until we were already inside layout to discover
582                 // that the block really needed a full layout, we missed our chance to repaint the layer
583                 // before layout started.  Luckily the layer has cached the repaint rect for its original
584                 // position and size, and so we can use that to make a repaint happen now.
585                 repaintUsingContainer(containerForRepaint(), layer()->repaintRect());
586             }
587         }
588
589         FloatingObject* lastFloat = m_floatingObjects ? m_floatingObjects->last() : 0;
590
591         LineMidpointState& lineMidpointState = resolver.midpointState();
592
593         // We also find the first clean line and extract these lines.  We will add them back
594         // if we determine that we're able to synchronize after handling all our dirty lines.
595         InlineIterator cleanLineStart;
596         BidiStatus cleanLineBidiStatus;
597         int endLineYPos = 0;
598         RootInlineBox* endLine = (fullLayout || !startLine) ? 
599                                  0 : determineEndPosition(startLine, cleanLineStart, cleanLineBidiStatus, endLineYPos);
600
601         if (startLine) {
602             if (!useRepaintBounds) {
603                 useRepaintBounds = true;
604                 repaintTop = height();
605                 repaintBottom = height();
606             }
607             RenderArena* arena = renderArena();
608             RootInlineBox* box = startLine;
609             while (box) {
610                 repaintTop = min(repaintTop, box->topVisibleOverflow());
611                 repaintBottom = max(repaintBottom, box->bottomVisibleOverflow());
612                 RootInlineBox* next = box->nextRootBox();
613                 box->deleteLine(arena);
614                 box = next;
615             }
616         }
617
618         InlineIterator end = resolver.position();
619
620         if (!fullLayout && lastRootBox() && lastRootBox()->endsWithBreak()) {
621             // If the last line before the start line ends with a line break that clear floats,
622             // adjust the height accordingly.
623             // A line break can be either the first or the last object on a line, depending on its direction.
624             if (InlineBox* lastLeafChild = lastRootBox()->lastLeafChild()) {
625                 RenderObject* lastObject = lastLeafChild->renderer();
626                 if (!lastObject->isBR())
627                     lastObject = lastRootBox()->firstLeafChild()->renderer();
628                 if (lastObject->isBR()) {
629                     EClear clear = lastObject->style()->clear();
630                     if (clear != CNONE)
631                         newLine(clear);
632                 }
633             }
634         }
635
636         bool endLineMatched = false;
637         bool checkForEndLineMatch = endLine;
638         bool checkForFloatsFromLastLine = false;
639
640         bool isLineEmpty = true;
641         bool paginated = view()->layoutState() && view()->layoutState()->isPaginated();
642
643         while (!end.atEnd()) {
644             // FIXME: Is this check necessary before the first iteration or can it be moved to the end?
645             if (checkForEndLineMatch && (endLineMatched = matchedEndLine(resolver, cleanLineStart, cleanLineBidiStatus, endLine, endLineYPos, repaintBottom, repaintTop)))
646                 break;
647
648             lineMidpointState.reset();
649             
650             isLineEmpty = true;
651             
652             EClear clear = CNONE;
653             bool hyphenated;
654             
655             InlineIterator oldEnd = end;
656             FloatingObject* lastFloatFromPreviousLine = m_floatingObjects ? m_floatingObjects->last() : 0;
657             end = findNextLineBreak(resolver, firstLine, isLineEmpty, previousLineBrokeCleanly, hyphenated, &clear, lastFloatFromPreviousLine);
658             if (resolver.position().atEnd()) {
659                 resolver.deleteRuns();
660                 checkForFloatsFromLastLine = true;
661                 break;
662             }
663             ASSERT(end != resolver.position());
664
665             if (!isLineEmpty) {
666                 resolver.createBidiRunsForLine(end, style()->visuallyOrdered(), previousLineBrokeCleanly);
667                 ASSERT(resolver.position() == end);
668
669                 BidiRun* trailingSpaceRun = 0;
670                 if (!previousLineBrokeCleanly && resolver.runCount() && resolver.logicallyLastRun()->m_object->style()->breakOnlyAfterWhiteSpace()
671                         && resolver.logicallyLastRun()->m_object->style()->autoWrap()) {
672                     trailingSpaceRun = resolver.logicallyLastRun();
673                     RenderObject* lastObject = trailingSpaceRun->m_object;
674                     if (lastObject->isText()) {
675                         RenderText* lastText = toRenderText(lastObject);
676                         const UChar* characters = lastText->characters();
677                         int firstSpace = trailingSpaceRun->stop();
678                         while (firstSpace > trailingSpaceRun->start()) {
679                             UChar current = characters[firstSpace - 1];
680                             if (!isCollapsibleSpace(current, lastText))
681                                 break;
682                             firstSpace--;
683                         }
684                         if (firstSpace == trailingSpaceRun->stop())
685                             trailingSpaceRun = 0;
686                         else {
687                             TextDirection direction = style()->direction();
688                             bool shouldReorder = trailingSpaceRun != (direction == LTR ? resolver.lastRun() : resolver.firstRun());
689                             if (firstSpace != trailingSpaceRun->start()) {
690                                 BidiContext* baseContext = resolver.context();
691                                 while (BidiContext* parent = baseContext->parent())
692                                     baseContext = parent;
693
694                                 BidiRun* newTrailingRun = new (renderArena()) BidiRun(firstSpace, trailingSpaceRun->m_stop, trailingSpaceRun->m_object, baseContext, OtherNeutral);
695                                 trailingSpaceRun->m_stop = firstSpace;
696                                 if (direction == LTR)
697                                     resolver.addRun(newTrailingRun);
698                                 else
699                                     resolver.prependRun(newTrailingRun);
700                                 trailingSpaceRun = newTrailingRun;
701                                 shouldReorder = false;
702                             }
703                             if (shouldReorder) {
704                                 if (direction == LTR) {
705                                     resolver.moveRunToEnd(trailingSpaceRun);
706                                     trailingSpaceRun->m_level = 0;
707                                 } else {
708                                     resolver.moveRunToBeginning(trailingSpaceRun);
709                                     trailingSpaceRun->m_level = 1;
710                                 }
711                             }
712                         }
713                     } else
714                         trailingSpaceRun = 0;
715                 }
716
717                 // Now that the runs have been ordered, we create the line boxes.
718                 // At the same time we figure out where border/padding/margin should be applied for
719                 // inline flow boxes.
720
721                 RootInlineBox* lineBox = 0;
722                 int oldHeight = height();
723                 if (resolver.runCount()) {
724                     if (hyphenated)
725                         resolver.logicallyLastRun()->m_hasHyphen = true;
726                     lineBox = constructLine(resolver.runCount(), resolver.firstRun(), resolver.lastRun(), firstLine, !end.obj, end.obj && !end.pos ? end.obj : 0);
727                     if (lineBox) {
728                         lineBox->setEndsWithBreak(previousLineBrokeCleanly);
729
730 #if ENABLE(SVG)
731                         bool isSVGRootInlineBox = lineBox->isSVGRootInlineBox();
732 #else
733                         bool isSVGRootInlineBox = false;
734 #endif
735
736                         GlyphOverflowAndFallbackFontsMap textBoxDataMap;
737
738                         // Now we position all of our text runs horizontally.
739                         if (!isSVGRootInlineBox)
740                             computeInlineDirectionPositionsForLine(lineBox, firstLine, resolver.firstRun(), trailingSpaceRun, end.atEnd(), textBoxDataMap);
741
742                         // Now position our text runs vertically.
743                         computeBlockDirectionPositionsForLine(lineBox, resolver.firstRun(), textBoxDataMap);
744
745 #if ENABLE(SVG)
746                         // SVG text layout code computes vertical & horizontal positions on its own.
747                         // Note that we still need to execute computeVerticalPositionsForLine() as
748                         // it calls InlineTextBox::positionLineBox(), which tracks whether the box
749                         // contains reversed text or not. If we wouldn't do that editing and thus
750                         // text selection in RTL boxes would not work as expected.
751                         if (isSVGRootInlineBox) {
752                             ASSERT(isSVGText());
753                             static_cast<SVGRootInlineBox*>(lineBox)->computePerCharacterLayoutInformation();
754                         }
755 #endif
756
757 #if PLATFORM(MAC)
758                         // Highlight acts as an overflow inflation.
759                         if (style()->highlight() != nullAtom)
760                             lineBox->addHighlightOverflow();
761 #endif
762                     }
763                 }
764
765                 resolver.deleteRuns();
766
767                 if (lineBox) {
768                     lineBox->setLineBreakInfo(end.obj, end.pos, resolver.status());
769                     if (useRepaintBounds) {
770                         repaintTop = min(repaintTop, lineBox->topVisibleOverflow());
771                         repaintBottom = max(repaintBottom, lineBox->bottomVisibleOverflow());
772                     }
773                     
774                     if (paginated) {
775                         int adjustment = 0;
776                         adjustLinePositionForPagination(lineBox, adjustment);
777                         if (adjustment) {
778                             int oldLineWidth = availableLogicalWidthForLine(oldHeight, firstLine);
779                             lineBox->adjustPosition(0, adjustment);
780                             if (useRepaintBounds) // This can only be a positive adjustment, so no need to update repaintTop.
781                                 repaintBottom = max(repaintBottom, lineBox->bottomVisibleOverflow());
782                                 
783                             if (availableLogicalWidthForLine(oldHeight + adjustment, firstLine) != oldLineWidth) {
784                                 // We have to delete this line, remove all floats that got added, and let line layout re-run.
785                                 lineBox->deleteLine(renderArena());
786                                 removeFloatingObjectsBelow(lastFloatFromPreviousLine, oldHeight);
787                                 setLogicalHeight(oldHeight + adjustment);
788                                 resolver.setPosition(oldEnd);
789                                 end = oldEnd;
790                                 continue;
791                             }
792
793                             setLogicalHeight(lineBox->blockHeight());
794                         }
795                     }
796                 }
797
798                 firstLine = false;
799                 newLine(clear);
800             }
801
802             if (m_floatingObjects && lastRootBox()) {
803                 if (lastFloat) {
804                     for (FloatingObject* f = m_floatingObjects->last(); f != lastFloat; f = m_floatingObjects->prev()) {
805                     }
806                     m_floatingObjects->next();
807                 } else
808                     m_floatingObjects->first();
809                 for (FloatingObject* f = m_floatingObjects->current(); f; f = m_floatingObjects->next()) {
810                     lastRootBox()->floats().append(f->m_renderer);
811                     ASSERT(f->m_renderer == floats[floatIndex].object);
812                     // If a float's geometry has changed, give up on syncing with clean lines.
813                     if (floats[floatIndex].rect != f->frameRect())
814                         checkForEndLineMatch = false;
815                     floatIndex++;
816                 }
817                 lastFloat = m_floatingObjects->last();
818             }
819
820             lineMidpointState.reset();
821             resolver.setPosition(end);
822         }
823
824         if (endLine) {
825             if (endLineMatched) {
826                 // Attach all the remaining lines, and then adjust their y-positions as needed.
827                 int delta = height() - endLineYPos;
828                 for (RootInlineBox* line = endLine; line; line = line->nextRootBox()) {
829                     line->attachLine();
830                     if (paginated) {
831                         delta -= line->paginationStrut();
832                         adjustLinePositionForPagination(line, delta);
833                     }
834                     if (delta) {
835                         repaintTop = min(repaintTop, line->topVisibleOverflow() + min(delta, 0));
836                         repaintBottom = max(repaintBottom, line->bottomVisibleOverflow() + max(delta, 0));
837                         line->adjustPosition(0, delta);
838                     }
839                     if (Vector<RenderBox*>* cleanLineFloats = line->floatsPtr()) {
840                         Vector<RenderBox*>::iterator end = cleanLineFloats->end();
841                         for (Vector<RenderBox*>::iterator f = cleanLineFloats->begin(); f != end; ++f) {
842                             int floatTop = (*f)->y() - (*f)->marginTop();
843                             insertFloatingObject(*f);
844                             setLogicalHeight(floatTop + delta);
845                             positionNewFloats();
846                         }
847                     }
848                 }
849                 setLogicalHeight(lastRootBox()->blockHeight());
850             } else {
851                 // Delete all the remaining lines.
852                 RootInlineBox* line = endLine;
853                 RenderArena* arena = renderArena();
854                 while (line) {
855                     repaintTop = min(repaintTop, line->topVisibleOverflow());
856                     repaintBottom = max(repaintBottom, line->bottomVisibleOverflow());
857                     RootInlineBox* next = line->nextRootBox();
858                     line->deleteLine(arena);
859                     line = next;
860                 }
861             }
862         }
863         if (m_floatingObjects && (checkForFloatsFromLastLine || positionNewFloats()) && lastRootBox()) {
864             // In case we have a float on the last line, it might not be positioned up to now.
865             // This has to be done before adding in the bottom border/padding, or the float will
866             // include the padding incorrectly. -dwh
867             if (checkForFloatsFromLastLine) {
868                 int bottomVisualOverflow = lastRootBox()->bottomVisualOverflow();
869                 int bottomLayoutOverflow = lastRootBox()->bottomLayoutOverflow();
870                 TrailingFloatsRootInlineBox* trailingFloatsLineBox = new (renderArena()) TrailingFloatsRootInlineBox(this);
871                 m_lineBoxes.appendLineBox(trailingFloatsLineBox);
872                 trailingFloatsLineBox->setConstructed();
873                 GlyphOverflowAndFallbackFontsMap textBoxDataMap;
874                 trailingFloatsLineBox->alignBoxesInBlockDirection(height(), textBoxDataMap);
875                 trailingFloatsLineBox->setBlockDirectionOverflowPositions(height(), bottomLayoutOverflow, height(), bottomVisualOverflow, 0);
876                 trailingFloatsLineBox->setBlockHeight(height());
877             }
878             if (lastFloat) {
879                 for (FloatingObject* f = m_floatingObjects->last(); f != lastFloat; f = m_floatingObjects->prev()) {
880                 }
881                 m_floatingObjects->next();
882             } else
883                 m_floatingObjects->first();
884             for (FloatingObject* f = m_floatingObjects->current(); f; f = m_floatingObjects->next())
885                 lastRootBox()->floats().append(f->m_renderer);
886             lastFloat = m_floatingObjects->last();
887         }
888         size_t floatCount = floats.size();
889         // Floats that did not have layout did not repaint when we laid them out. They would have
890         // painted by now if they had moved, but if they stayed at (0, 0), they still need to be
891         // painted.
892         for (size_t i = 0; i < floatCount; ++i) {
893             if (!floats[i].everHadLayout) {
894                 RenderBox* f = floats[i].object;
895                 if (!f->x() && !f->y() && f->checkForRepaintDuringLayout())
896                     f->repaint();
897             }
898         }
899     }
900
901     // Now add in the bottom border/padding.
902     setLogicalHeight(logicalHeight() + toAdd);
903
904     if (!firstLineBox() && hasLineIfEmpty())
905         setLogicalHeight(logicalHeight() + lineHeight(true, true));
906
907     // See if we have any lines that spill out of our block.  If we do, then we will possibly need to
908     // truncate text.
909     if (hasTextOverflow)
910         checkLinesForTextOverflow();
911 }
912
913 RootInlineBox* RenderBlock::determineStartPosition(bool& firstLine, bool& fullLayout, bool& previousLineBrokeCleanly, 
914                                                    InlineBidiResolver& resolver, Vector<FloatWithRect>& floats, unsigned& numCleanFloats,
915                                                    bool& useRepaintBounds, int& repaintTop, int& repaintBottom)
916 {
917     RootInlineBox* curr = 0;
918     RootInlineBox* last = 0;
919
920     bool dirtiedByFloat = false;
921     if (!fullLayout) {
922         // Paginate all of the clean lines.
923         bool paginated = view()->layoutState() && view()->layoutState()->isPaginated();
924         int paginationDelta = 0;
925         size_t floatIndex = 0;
926         for (curr = firstRootBox(); curr && !curr->isDirty(); curr = curr->nextRootBox()) {
927             if (paginated) {
928                 paginationDelta -= curr->paginationStrut();
929                 adjustLinePositionForPagination(curr, paginationDelta);
930                 if (paginationDelta) {
931                     if (containsFloats() || !floats.isEmpty()) {
932                         // FIXME: Do better eventually.  For now if we ever shift because of pagination and floats are present just go to a full layout.
933                         fullLayout = true; 
934                         break;
935                     }
936                     
937                     if (!useRepaintBounds)
938                         useRepaintBounds = true;
939                         
940                     repaintTop = min(repaintTop, curr->topVisibleOverflow() + min(paginationDelta, 0));
941                     repaintBottom = max(repaintBottom, curr->bottomVisibleOverflow() + max(paginationDelta, 0));
942                     curr->adjustPosition(0, paginationDelta);
943                 }                
944             }
945             
946             if (Vector<RenderBox*>* cleanLineFloats = curr->floatsPtr()) {
947                 Vector<RenderBox*>::iterator end = cleanLineFloats->end();
948                 for (Vector<RenderBox*>::iterator o = cleanLineFloats->begin(); o != end; ++o) {
949                     RenderBox* f = *o;
950                     f->layoutIfNeeded();
951                     IntSize newSize(f->width() + f->marginLeft() + f->marginRight(), f->height() + f->marginTop() + f->marginBottom());
952                     ASSERT(floatIndex < floats.size());
953                     if (floats[floatIndex].object != f) {
954                         // A new float has been inserted before this line or before its last known float.
955                         // Just do a full layout.
956                         fullLayout = true;
957                         break;
958                     }
959                     if (floats[floatIndex].rect.size() != newSize) {
960                         int floatTop = floats[floatIndex].rect.y();
961                         curr->markDirty();
962                         markLinesDirtyInVerticalRange(curr->blockHeight(), floatTop + max(floats[floatIndex].rect.height(), newSize.height()), curr);
963                         floats[floatIndex].rect.setSize(newSize);
964                         dirtiedByFloat = true;
965                     }
966                     floatIndex++;
967                 }
968             }
969             if (dirtiedByFloat || fullLayout)
970                 break;
971         }
972         // Check if a new float has been inserted after the last known float.
973         if (!curr && floatIndex < floats.size())
974             fullLayout = true;
975     }
976
977     if (fullLayout) {
978         // Nuke all our lines.
979         if (firstRootBox()) {
980             RenderArena* arena = renderArena();
981             curr = firstRootBox(); 
982             while (curr) {
983                 RootInlineBox* next = curr->nextRootBox();
984                 curr->deleteLine(arena);
985                 curr = next;
986             }
987             ASSERT(!firstLineBox() && !lastLineBox());
988         }
989     } else {
990         if (curr) {
991             // We have a dirty line.
992             if (RootInlineBox* prevRootBox = curr->prevRootBox()) {
993                 // We have a previous line.
994                 if (!dirtiedByFloat && (!prevRootBox->endsWithBreak() || (prevRootBox->lineBreakObj()->isText() && prevRootBox->lineBreakPos() >= toRenderText(prevRootBox->lineBreakObj())->textLength())))
995                     // The previous line didn't break cleanly or broke at a newline
996                     // that has been deleted, so treat it as dirty too.
997                     curr = prevRootBox;
998             }
999         } else {
1000             // No dirty lines were found.
1001             // If the last line didn't break cleanly, treat it as dirty.
1002             if (lastRootBox() && !lastRootBox()->endsWithBreak())
1003                 curr = lastRootBox();
1004         }
1005
1006         // If we have no dirty lines, then last is just the last root box.
1007         last = curr ? curr->prevRootBox() : lastRootBox();
1008     }
1009
1010     numCleanFloats = 0;
1011     if (!floats.isEmpty()) {
1012         int savedHeight = height();
1013         // Restore floats from clean lines.
1014         RootInlineBox* line = firstRootBox();
1015         while (line != curr) {
1016             if (Vector<RenderBox*>* cleanLineFloats = line->floatsPtr()) {
1017                 Vector<RenderBox*>::iterator end = cleanLineFloats->end();
1018                 for (Vector<RenderBox*>::iterator f = cleanLineFloats->begin(); f != end; ++f) {
1019                     insertFloatingObject(*f);
1020                     setLogicalHeight((*f)->y() - (*f)->marginTop());
1021                     positionNewFloats();
1022                     ASSERT(floats[numCleanFloats].object == *f);
1023                     numCleanFloats++;
1024                 }
1025             }
1026             line = line->nextRootBox();
1027         }
1028         setLogicalHeight(savedHeight);
1029     }
1030
1031     firstLine = !last;
1032     previousLineBrokeCleanly = !last || last->endsWithBreak();
1033
1034     RenderObject* startObj;
1035     int pos = 0;
1036     if (last) {
1037         setLogicalHeight(last->blockHeight());
1038         startObj = last->lineBreakObj();
1039         pos = last->lineBreakPos();
1040         resolver.setStatus(last->lineBreakBidiStatus());
1041     } else {
1042         bool ltr = style()->isLeftToRightDirection()
1043     #if ENABLE(SVG)   
1044             || (style()->unicodeBidi() == UBNormal && isSVGText())
1045     #endif
1046             ;
1047
1048         Direction direction = ltr ? LeftToRight : RightToLeft;
1049         resolver.setLastStrongDir(direction);
1050         resolver.setLastDir(direction);
1051         resolver.setEorDir(direction);
1052         resolver.setContext(BidiContext::create(ltr ? 0 : 1, direction, style()->unicodeBidi() == Override));
1053
1054         startObj = bidiFirst(this, &resolver);
1055     }
1056
1057     resolver.setPosition(InlineIterator(this, startObj, pos));
1058
1059     return curr;
1060 }
1061
1062 RootInlineBox* RenderBlock::determineEndPosition(RootInlineBox* startLine, InlineIterator& cleanLineStart, BidiStatus& cleanLineBidiStatus, int& yPos)
1063 {
1064     RootInlineBox* last = 0;
1065     if (!startLine)
1066         last = 0;
1067     else {
1068         for (RootInlineBox* curr = startLine->nextRootBox(); curr; curr = curr->nextRootBox()) {
1069             if (curr->isDirty())
1070                 last = 0;
1071             else if (!last)
1072                 last = curr;
1073         }
1074     }
1075
1076     if (!last)
1077         return 0;
1078
1079     RootInlineBox* prev = last->prevRootBox();
1080     cleanLineStart = InlineIterator(this, prev->lineBreakObj(), prev->lineBreakPos());
1081     cleanLineBidiStatus = prev->lineBreakBidiStatus();
1082     yPos = prev->blockHeight();
1083
1084     for (RootInlineBox* line = last; line; line = line->nextRootBox())
1085         line->extractLine(); // Disconnect all line boxes from their render objects while preserving
1086                              // their connections to one another.
1087
1088     return last;
1089 }
1090
1091 bool RenderBlock::matchedEndLine(const InlineBidiResolver& resolver, const InlineIterator& endLineStart, const BidiStatus& endLineStatus, RootInlineBox*& endLine, int& endYPos, int& repaintBottom, int& repaintTop)
1092 {
1093     if (resolver.position() == endLineStart) {
1094         if (resolver.status() != endLineStatus)
1095             return false;
1096
1097         int delta = height() - endYPos;
1098         if (!delta || !m_floatingObjects)
1099             return true;
1100
1101         // See if any floats end in the range along which we want to shift the lines vertically.
1102         int top = min(height(), endYPos);
1103
1104         RootInlineBox* lastLine = endLine;
1105         while (RootInlineBox* nextLine = lastLine->nextRootBox())
1106             lastLine = nextLine;
1107
1108         int bottom = lastLine->blockHeight() + abs(delta);
1109
1110         for (FloatingObject* f = m_floatingObjects->first(); f; f = m_floatingObjects->next()) {
1111             if (f->bottom() >= top && f->bottom() < bottom)
1112                 return false;
1113         }
1114
1115         return true;
1116     }
1117
1118     // The first clean line doesn't match, but we can check a handful of following lines to try
1119     // to match back up.
1120     static int numLines = 8; // The # of lines we're willing to match against.
1121     RootInlineBox* line = endLine;
1122     for (int i = 0; i < numLines && line; i++, line = line->nextRootBox()) {
1123         if (line->lineBreakObj() == resolver.position().obj && line->lineBreakPos() == resolver.position().pos) {
1124             // We have a match.
1125             if (line->lineBreakBidiStatus() != resolver.status())
1126                 return false; // ...but the bidi state doesn't match.
1127             RootInlineBox* result = line->nextRootBox();
1128
1129             // Set our yPos to be the block height of endLine.
1130             if (result)
1131                 endYPos = line->blockHeight();
1132
1133             int delta = height() - endYPos;
1134             if (delta && m_floatingObjects) {
1135                 // See if any floats end in the range along which we want to shift the lines vertically.
1136                 int top = min(height(), endYPos);
1137
1138                 RootInlineBox* lastLine = endLine;
1139                 while (RootInlineBox* nextLine = lastLine->nextRootBox())
1140                     lastLine = nextLine;
1141
1142                 int bottom = lastLine->blockHeight() + abs(delta);
1143
1144                 for (FloatingObject* f = m_floatingObjects->first(); f; f = m_floatingObjects->next()) {
1145                     if (f->bottom() >= top && f->bottom() < bottom)
1146                         return false;
1147                 }
1148             }
1149
1150             // Now delete the lines that we failed to sync.
1151             RootInlineBox* boxToDelete = endLine;
1152             RenderArena* arena = renderArena();
1153             while (boxToDelete && boxToDelete != result) {
1154                 repaintTop = min(repaintTop, boxToDelete->topVisibleOverflow());
1155                 repaintBottom = max(repaintBottom, boxToDelete->bottomVisibleOverflow());
1156                 RootInlineBox* next = boxToDelete->nextRootBox();
1157                 boxToDelete->deleteLine(arena);
1158                 boxToDelete = next;
1159             }
1160
1161             endLine = result;
1162             return result;
1163         }
1164     }
1165
1166     return false;
1167 }
1168
1169 static inline bool skipNonBreakingSpace(const InlineIterator& it, bool isLineEmpty, bool previousLineBrokeCleanly)
1170 {
1171     if (it.obj->style()->nbspMode() != SPACE || it.current() != noBreakSpace)
1172         return false;
1173
1174     // FIXME: This is bad.  It makes nbsp inconsistent with space and won't work correctly
1175     // with m_minWidth/m_maxWidth.
1176     // Do not skip a non-breaking space if it is the first character
1177     // on a line after a clean line break (or on the first line, since previousLineBrokeCleanly starts off
1178     // |true|).
1179     if (isLineEmpty && previousLineBrokeCleanly)
1180         return false;
1181
1182     return true;
1183 }
1184
1185 static inline bool shouldCollapseWhiteSpace(const RenderStyle* style, bool isLineEmpty, bool previousLineBrokeCleanly)
1186 {
1187     return style->collapseWhiteSpace() || (style->whiteSpace() == PRE_WRAP && (!isLineEmpty || !previousLineBrokeCleanly));
1188 }
1189
1190 static inline bool shouldPreserveNewline(RenderObject* object)
1191 {
1192 #if ENABLE(SVG)
1193     if (object->isSVGInlineText())
1194         return false;
1195 #endif
1196
1197     return object->style()->preserveNewline();
1198 }
1199
1200 static bool inlineFlowRequiresLineBox(RenderInline* flow)
1201 {
1202     // FIXME: Right now, we only allow line boxes for inlines that are truly empty.
1203     // We need to fix this, though, because at the very least, inlines containing only
1204     // ignorable whitespace should should also have line boxes. 
1205     return !flow->firstChild() && flow->hasHorizontalBordersPaddingOrMargin();
1206 }
1207
1208 bool RenderBlock::requiresLineBox(const InlineIterator& it, bool isLineEmpty, bool previousLineBrokeCleanly)
1209 {
1210     if (it.obj->isFloatingOrPositioned())
1211         return false;
1212
1213     if (it.obj->isRenderInline() && !inlineFlowRequiresLineBox(toRenderInline(it.obj)))
1214         return false;
1215
1216     if (!shouldCollapseWhiteSpace(it.obj->style(), isLineEmpty, previousLineBrokeCleanly) || it.obj->isBR())
1217         return true;
1218
1219     UChar current = it.current();
1220     return current != ' ' && current != '\t' && current != softHyphen && (current != '\n' || shouldPreserveNewline(it.obj)) 
1221             && !skipNonBreakingSpace(it, isLineEmpty, previousLineBrokeCleanly);
1222 }
1223
1224 bool RenderBlock::generatesLineBoxesForInlineChild(RenderObject* inlineObj, bool isLineEmpty, bool previousLineBrokeCleanly)
1225 {
1226     ASSERT(inlineObj->parent() == this);
1227
1228     InlineIterator it(this, inlineObj, 0);
1229     while (!it.atEnd() && !requiresLineBox(it, isLineEmpty, previousLineBrokeCleanly))
1230         it.increment();
1231
1232     return !it.atEnd();
1233 }
1234
1235 // FIXME: The entire concept of the skipTrailingWhitespace function is flawed, since we really need to be building
1236 // line boxes even for containers that may ultimately collapse away.  Otherwise we'll never get positioned
1237 // elements quite right.  In other words, we need to build this function's work into the normal line
1238 // object iteration process.
1239 // NB. this function will insert any floating elements that would otherwise
1240 // be skipped but it will not position them.
1241 void RenderBlock::skipTrailingWhitespace(InlineIterator& iterator, bool isLineEmpty, bool previousLineBrokeCleanly)
1242 {
1243     while (!iterator.atEnd() && !requiresLineBox(iterator, isLineEmpty, previousLineBrokeCleanly)) {
1244         RenderObject* object = iterator.obj;
1245         if (object->isFloating()) {
1246             insertFloatingObject(toRenderBox(object));
1247         } else if (object->isPositioned()) {
1248             // FIXME: The math here is actually not really right.  It's a best-guess approximation that
1249             // will work for the common cases
1250             RenderObject* c = object->container();
1251             if (c->isRenderInline()) {
1252                 // A relative positioned inline encloses us.  In this case, we also have to determine our
1253                 // position as though we were an inline.  Set |staticX| and |staticY| on the relative positioned
1254                 // inline so that we can obtain the value later.
1255                 toRenderInline(c)->layer()->setStaticX(style()->isLeftToRightDirection() ? logicalLeftOffsetForLine(height(), false) : logicalRightOffsetForLine(height(), false));
1256                 toRenderInline(c)->layer()->setStaticY(height());
1257             }
1258     
1259             RenderBox* box = toRenderBox(object);
1260             if (box->style()->hasStaticX()) {
1261                 if (box->style()->isOriginalDisplayInlineType())
1262                     box->layer()->setStaticX(style()->isLeftToRightDirection() ? logicalLeftOffsetForLine(height(), false) : width() - logicalRightOffsetForLine(height(), false));
1263                 else
1264                     box->layer()->setStaticX(style()->isLeftToRightDirection() ? borderLeft() + paddingLeft() : borderRight() + paddingRight());
1265             }
1266     
1267             if (box->style()->hasStaticY())
1268                 box->layer()->setStaticY(height());
1269         }
1270         iterator.increment();
1271     }
1272 }
1273
1274 int RenderBlock::skipLeadingWhitespace(InlineBidiResolver& resolver, bool firstLine, bool isLineEmpty, bool previousLineBrokeCleanly,
1275                                        FloatingObject* lastFloatFromPreviousLine)
1276 {
1277     int availableWidth = availableLogicalWidthForLine(height(), firstLine);
1278     while (!resolver.position().atEnd() && !requiresLineBox(resolver.position(), isLineEmpty, previousLineBrokeCleanly)) {
1279         RenderObject* object = resolver.position().obj;
1280         if (object->isFloating()) {
1281             positionNewFloatOnLine(insertFloatingObject(toRenderBox(object)), lastFloatFromPreviousLine);
1282             availableWidth = availableLogicalWidthForLine(height(), firstLine);
1283         } else if (object->isPositioned()) {
1284             // FIXME: The math here is actually not really right.  It's a best-guess approximation that
1285             // will work for the common cases
1286             RenderObject* c = object->container();
1287             if (c->isRenderInline()) {
1288                 // A relative positioned inline encloses us.  In this case, we also have to determine our
1289                 // position as though we were an inline.  Set |staticX| and |staticY| on the relative positioned
1290                 // inline so that we can obtain the value later.
1291                 toRenderInline(c)->layer()->setStaticX(style()->isLeftToRightDirection() ? logicalLeftOffsetForLine(height(), firstLine) : logicalRightOffsetForLine(height(), firstLine));
1292                 toRenderInline(c)->layer()->setStaticY(height());
1293             }
1294     
1295             RenderBox* box = toRenderBox(object);
1296             if (box->style()->hasStaticX()) {
1297                 if (box->style()->isOriginalDisplayInlineType())
1298                     box->layer()->setStaticX(style()->isLeftToRightDirection() ? logicalLeftOffsetForLine(height(), firstLine) : width() - logicalRightOffsetForLine(height(), firstLine));
1299                 else
1300                     box->layer()->setStaticX(style()->isLeftToRightDirection() ? borderLeft() + paddingLeft() : borderRight() + paddingRight());
1301             }
1302     
1303             if (box->style()->hasStaticY())
1304                 box->layer()->setStaticY(height());
1305         }
1306         resolver.increment();
1307     }
1308     resolver.commitExplicitEmbedding();
1309     return availableWidth;
1310 }
1311
1312 // This is currently just used for list markers and inline flows that have line boxes. Neither should 
1313 // have an effect on whitespace at the start of the line. 
1314 static bool shouldSkipWhitespaceAfterStartObject(RenderBlock* block, RenderObject* o, LineMidpointState& lineMidpointState)
1315 {
1316     RenderObject* next = bidiNext(block, o);
1317     if (next && !next->isBR() && next->isText() && toRenderText(next)->textLength() > 0) {
1318         RenderText* nextText = toRenderText(next);
1319         UChar nextChar = nextText->characters()[0];
1320         if (nextText->style()->isCollapsibleWhiteSpace(nextChar)) {
1321             addMidpoint(lineMidpointState, InlineIterator(0, o, 0));
1322             return true;
1323         }
1324     }
1325
1326     return false;
1327 }
1328
1329 void RenderBlock::fitBelowFloats(int widthToFit, bool firstLine, int& availableWidth)
1330 {
1331     ASSERT(widthToFit > availableWidth);
1332
1333     int floatLogicalBottom;
1334     int lastFloatLogicalBottom = height();
1335     int newLineWidth = availableWidth;
1336     while (true) {
1337         floatLogicalBottom = nextFloatLogicalBottomBelow(lastFloatLogicalBottom);
1338         if (!floatLogicalBottom)
1339             break;
1340
1341         newLineWidth = availableLogicalWidthForLine(floatLogicalBottom, firstLine);
1342         lastFloatLogicalBottom = floatLogicalBottom;
1343         if (newLineWidth >= widthToFit)
1344             break;
1345     }
1346
1347     if (newLineWidth > availableWidth) {
1348         setLogicalHeight(lastFloatLogicalBottom);
1349         availableWidth = newLineWidth;
1350     }
1351 }
1352
1353 static inline unsigned textWidth(RenderText* text, unsigned from, unsigned len, const Font& font, int xPos, bool isFixedPitch, bool collapseWhiteSpace)
1354 {
1355     if (isFixedPitch || (!from && len == text->textLength()))
1356         return text->width(from, len, font, xPos);
1357     return font.width(TextRun(text->characters() + from, len, !collapseWhiteSpace, xPos));
1358 }
1359
1360 static void tryHyphenating(RenderText* text, const Font& font, const AtomicString& localeIdentifier, int lastSpace, int pos, int xPos, int availableWidth, bool isFixedPitch, bool collapseWhiteSpace, int lastSpaceWordSpacing, InlineIterator& lineBreak, int nextBreakable, bool& hyphenated)
1361 {
1362     const AtomicString& hyphenString = text->style()->hyphenString();
1363     int hyphenWidth = font.width(TextRun(hyphenString.characters(), hyphenString.length()));
1364
1365     int maxPrefixWidth = availableWidth - xPos - hyphenWidth - lastSpaceWordSpacing;
1366     // If the maximum width available for the prefix before the hyphen is small, then it is very unlikely
1367     // that an hyphenation opportunity exists, so do not bother to look for it.
1368     if (maxPrefixWidth <= font.pixelSize() * 5 / 4)
1369         return;
1370
1371     unsigned prefixLength = font.offsetForPosition(TextRun(text->characters() + lastSpace, pos - lastSpace, !collapseWhiteSpace, xPos + lastSpaceWordSpacing), maxPrefixWidth, false);
1372     if (!prefixLength)
1373         return;
1374
1375     prefixLength = lastHyphenLocation(text->characters() + lastSpace, pos - lastSpace, prefixLength + 1, localeIdentifier);
1376     if (!prefixLength)
1377         return;
1378
1379 #if !ASSERT_DISABLED
1380     int prefixWidth = hyphenWidth + textWidth(text, lastSpace, prefixLength, font, xPos, isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing;
1381     ASSERT(xPos + prefixWidth <= availableWidth);
1382 #else
1383     UNUSED_PARAM(isFixedPitch);
1384 #endif
1385
1386     lineBreak.obj = text;
1387     lineBreak.pos = lastSpace + prefixLength;
1388     lineBreak.nextBreakablePosition = nextBreakable;
1389     hyphenated = true;
1390 }
1391
1392 InlineIterator RenderBlock::findNextLineBreak(InlineBidiResolver& resolver, bool firstLine,  bool& isLineEmpty, bool& previousLineBrokeCleanly, 
1393                                               bool& hyphenated, EClear* clear, FloatingObject* lastFloatFromPreviousLine)
1394 {
1395     ASSERT(resolver.position().block == this);
1396
1397     bool appliedStartWidth = resolver.position().pos > 0;
1398     LineMidpointState& lineMidpointState = resolver.midpointState();
1399     
1400     int width = skipLeadingWhitespace(resolver, firstLine, isLineEmpty, previousLineBrokeCleanly, lastFloatFromPreviousLine);
1401
1402     int w = 0;
1403     int tmpW = 0;
1404
1405     if (resolver.position().atEnd())
1406         return resolver.position();
1407
1408     // This variable is used only if whitespace isn't set to PRE, and it tells us whether
1409     // or not we are currently ignoring whitespace.
1410     bool ignoringSpaces = false;
1411     InlineIterator ignoreStart;
1412     
1413     // This variable tracks whether the very last character we saw was a space.  We use
1414     // this to detect when we encounter a second space so we know we have to terminate
1415     // a run.
1416     bool currentCharacterIsSpace = false;
1417     bool currentCharacterIsWS = false;
1418     RenderObject* trailingSpaceObject = 0;
1419
1420     InlineIterator lBreak = resolver.position();
1421
1422     RenderObject *o = resolver.position().obj;
1423     RenderObject *last = o;
1424     unsigned pos = resolver.position().pos;
1425     int nextBreakable = resolver.position().nextBreakablePosition;
1426     bool atStart = true;
1427
1428     bool prevLineBrokeCleanly = previousLineBrokeCleanly;
1429     previousLineBrokeCleanly = false;
1430
1431     hyphenated = false;
1432
1433     bool autoWrapWasEverTrueOnLine = false;
1434     bool floatsFitOnLine = true;
1435     
1436     // Firefox and Opera will allow a table cell to grow to fit an image inside it under
1437     // very specific circumstances (in order to match common WinIE renderings). 
1438     // Not supporting the quirk has caused us to mis-render some real sites. (See Bugzilla 10517.) 
1439     bool allowImagesToBreak = !document()->inQuirksMode() || !isTableCell() || !style()->width().isIntrinsicOrAuto();
1440
1441     EWhiteSpace currWS = style()->whiteSpace();
1442     EWhiteSpace lastWS = currWS;
1443     while (o) {
1444         currWS = o->isReplaced() ? o->parent()->style()->whiteSpace() : o->style()->whiteSpace();
1445         lastWS = last->isReplaced() ? last->parent()->style()->whiteSpace() : last->style()->whiteSpace();
1446         
1447         bool autoWrap = RenderStyle::autoWrap(currWS);
1448         autoWrapWasEverTrueOnLine = autoWrapWasEverTrueOnLine || autoWrap;
1449
1450 #if ENABLE(SVG)
1451         bool preserveNewline = o->isSVGInlineText() ? false : RenderStyle::preserveNewline(currWS);
1452 #else
1453         bool preserveNewline = RenderStyle::preserveNewline(currWS);
1454 #endif
1455
1456         bool collapseWhiteSpace = RenderStyle::collapseWhiteSpace(currWS);
1457             
1458         if (o->isBR()) {
1459             if (w + tmpW <= width) {
1460                 lBreak.obj = o;
1461                 lBreak.pos = 0;
1462                 lBreak.nextBreakablePosition = -1;
1463                 lBreak.increment();
1464
1465                 // A <br> always breaks a line, so don't let the line be collapsed
1466                 // away. Also, the space at the end of a line with a <br> does not
1467                 // get collapsed away.  It only does this if the previous line broke
1468                 // cleanly.  Otherwise the <br> has no effect on whether the line is
1469                 // empty or not.
1470                 if (prevLineBrokeCleanly)
1471                     isLineEmpty = false;
1472                 trailingSpaceObject = 0;
1473                 previousLineBrokeCleanly = true;
1474
1475                 if (!isLineEmpty && clear)
1476                     *clear = o->style()->clear();
1477             }
1478             goto end;
1479         }
1480
1481         if (o->isFloatingOrPositioned()) {
1482             // add to special objects...
1483             if (o->isFloating()) {
1484                 RenderBox* floatBox = toRenderBox(o);
1485                 FloatingObject* f = insertFloatingObject(floatBox);
1486                 // check if it fits in the current line.
1487                 // If it does, position it now, otherwise, position
1488                 // it after moving to next line (in newLine() func)
1489                 if (floatsFitOnLine && floatBox->width() + floatBox->marginLeft() + floatBox->marginRight() + w + tmpW <= width) {
1490                     positionNewFloatOnLine(f, lastFloatFromPreviousLine);
1491                     width = availableLogicalWidthForLine(height(), firstLine);
1492                 } else
1493                     floatsFitOnLine = false;
1494             } else if (o->isPositioned()) {
1495                 // If our original display wasn't an inline type, then we can
1496                 // go ahead and determine our static x position now.
1497                 RenderBox* box = toRenderBox(o);
1498                 bool isInlineType = box->style()->isOriginalDisplayInlineType();
1499                 bool needToSetStaticX = box->style()->hasStaticX();
1500                 if (box->style()->hasStaticX() && !isInlineType) {
1501                     box->layer()->setStaticX(o->parent()->style()->isLeftToRightDirection() ?
1502                                   borderLeft() + paddingLeft() :
1503                                   borderRight() + paddingRight());
1504                     needToSetStaticX = false;
1505                 }
1506
1507                 // If our original display was an INLINE type, then we can go ahead
1508                 // and determine our static y position now.
1509                 bool needToSetStaticY = box->style()->hasStaticY();
1510                 if (box->style()->hasStaticY() && isInlineType) {
1511                     box->layer()->setStaticY(height());
1512                     needToSetStaticY = false;
1513                 }
1514                 
1515                 bool needToCreateLineBox = needToSetStaticX || needToSetStaticY;
1516                 RenderObject* c = o->container();
1517                 if (c->isRenderInline() && (!needToSetStaticX || !needToSetStaticY))
1518                     needToCreateLineBox = true;
1519
1520                 // If we're ignoring spaces, we have to stop and include this object and
1521                 // then start ignoring spaces again.
1522                 if (needToCreateLineBox) {
1523                     trailingSpaceObject = 0;
1524                     ignoreStart.obj = o;
1525                     ignoreStart.pos = 0;
1526                     if (ignoringSpaces) {
1527                         addMidpoint(lineMidpointState, ignoreStart); // Stop ignoring spaces.
1528                         addMidpoint(lineMidpointState, ignoreStart); // Start ignoring again.
1529                     }
1530                     
1531                 }
1532             }
1533         } else if (o->isRenderInline()) {
1534             // Right now, we should only encounter empty inlines here.
1535             ASSERT(!o->firstChild());
1536     
1537             RenderInline* flowBox = toRenderInline(o);
1538             
1539             // Now that some inline flows have line boxes, if we are already ignoring spaces, we need 
1540             // to make sure that we stop to include this object and then start ignoring spaces again. 
1541             // If this object is at the start of the line, we need to behave like list markers and 
1542             // start ignoring spaces.
1543             if (inlineFlowRequiresLineBox(flowBox)) {
1544                 isLineEmpty = false;
1545                 if (ignoringSpaces) {
1546                     trailingSpaceObject = 0;
1547                     addMidpoint(lineMidpointState, InlineIterator(0, o, 0)); // Stop ignoring spaces.
1548                     addMidpoint(lineMidpointState, InlineIterator(0, o, 0)); // Start ignoring again.
1549                 } else if (style()->collapseWhiteSpace() && resolver.position().obj == o
1550                     && shouldSkipWhitespaceAfterStartObject(this, o, lineMidpointState)) {
1551                     // Like with list markers, we start ignoring spaces to make sure that any 
1552                     // additional spaces we see will be discarded.
1553                     currentCharacterIsSpace = true;
1554                     currentCharacterIsWS = true;
1555                     ignoringSpaces = true;
1556                 }
1557             }
1558
1559             tmpW += flowBox->marginLeft() + flowBox->borderLeft() + flowBox->paddingLeft() +
1560                     flowBox->marginRight() + flowBox->borderRight() + flowBox->paddingRight();
1561         } else if (o->isReplaced()) {
1562             RenderBox* replacedBox = toRenderBox(o);
1563
1564             // Break on replaced elements if either has normal white-space.
1565             if ((autoWrap || RenderStyle::autoWrap(lastWS)) && (!o->isImage() || allowImagesToBreak)) {
1566                 w += tmpW;
1567                 tmpW = 0;
1568                 lBreak.obj = o;
1569                 lBreak.pos = 0;
1570                 lBreak.nextBreakablePosition = -1;
1571             }
1572
1573             if (ignoringSpaces)
1574                 addMidpoint(lineMidpointState, InlineIterator(0, o, 0));
1575
1576             isLineEmpty = false;
1577             ignoringSpaces = false;
1578             currentCharacterIsSpace = false;
1579             currentCharacterIsWS = false;
1580             trailingSpaceObject = 0;
1581
1582             // Optimize for a common case. If we can't find whitespace after the list
1583             // item, then this is all moot. -dwh
1584             if (o->isListMarker()) {
1585                 if (style()->collapseWhiteSpace() && shouldSkipWhitespaceAfterStartObject(this, o, lineMidpointState)) {
1586                     // Like with inline flows, we start ignoring spaces to make sure that any 
1587                     // additional spaces we see will be discarded.
1588                     currentCharacterIsSpace = true;
1589                     currentCharacterIsWS = true;
1590                     ignoringSpaces = true;
1591                 }
1592                 if (toRenderListMarker(o)->isInside())
1593                     tmpW += replacedBox->width() + replacedBox->marginLeft() + replacedBox->marginRight() + inlineWidth(o);
1594             } else
1595                 tmpW += replacedBox->width() + replacedBox->marginLeft() + replacedBox->marginRight() + inlineWidth(o);
1596         } else if (o->isText()) {
1597             if (!pos)
1598                 appliedStartWidth = false;
1599
1600             RenderText* t = toRenderText(o);
1601
1602 #if ENABLE(SVG)
1603             bool isSVGText = t->isSVGInlineText();
1604 #endif
1605
1606             int strlen = t->textLength();
1607             int len = strlen - pos;
1608             const UChar* str = t->characters();
1609
1610             RenderStyle* style = t->style(firstLine);
1611             const Font& f = style->font();
1612             bool isFixedPitch = f.isFixedPitch();
1613             bool canHyphenate = style->hyphens() == HyphensAuto && WebCore::canHyphenate(style->hyphenationLocale());
1614
1615             int lastSpace = pos;
1616             int wordSpacing = o->style()->wordSpacing();
1617             int lastSpaceWordSpacing = 0;
1618
1619             // Non-zero only when kerning is enabled, in which case we measure words with their trailing
1620             // space, then subtract its width.
1621             int wordTrailingSpaceWidth = f.typesettingFeatures() & Kerning ? f.width(TextRun(&space, 1)) + wordSpacing : 0;
1622
1623             int wrapW = tmpW + inlineWidth(o, !appliedStartWidth, true);
1624             int charWidth = 0;
1625             bool breakNBSP = autoWrap && o->style()->nbspMode() == SPACE;
1626             // Auto-wrapping text should wrap in the middle of a word only if it could not wrap before the word,
1627             // which is only possible if the word is the first thing on the line, that is, if |w| is zero.
1628             bool breakWords = o->style()->breakWords() && ((autoWrap && !w) || currWS == PRE);
1629             bool midWordBreak = false;
1630             bool breakAll = o->style()->wordBreak() == BreakAllWordBreak && autoWrap;
1631             int hyphenWidth = 0;
1632
1633             if (t->isWordBreak()) {
1634                 w += tmpW;
1635                 tmpW = 0;
1636                 lBreak.obj = o;
1637                 lBreak.pos = 0;
1638                 lBreak.nextBreakablePosition = -1;
1639                 ASSERT(!len);
1640             }
1641
1642             while (len) {
1643                 bool previousCharacterIsSpace = currentCharacterIsSpace;
1644                 bool previousCharacterIsWS = currentCharacterIsWS;
1645                 UChar c = str[pos];
1646                 currentCharacterIsSpace = c == ' ' || c == '\t' || (!preserveNewline && (c == '\n'));
1647
1648                 if (!collapseWhiteSpace || !currentCharacterIsSpace)
1649                     isLineEmpty = false;
1650
1651                 if (c == softHyphen && autoWrap && !hyphenWidth && style->hyphens() != HyphensNone) {
1652                     const AtomicString& hyphenString = style->hyphenString();
1653                     hyphenWidth = f.width(TextRun(hyphenString.characters(), hyphenString.length()));
1654                     tmpW += hyphenWidth;
1655                 }
1656
1657 #if ENABLE(SVG)
1658                 if (isSVGText) {
1659                     RenderSVGInlineText* svgInlineText = static_cast<RenderSVGInlineText*>(t);
1660                     if (pos > 0) {
1661                         if (svgInlineText->characterStartsNewTextChunk(pos)) {
1662                             addMidpoint(lineMidpointState, InlineIterator(0, o, pos - 1));
1663                             addMidpoint(lineMidpointState, InlineIterator(0, o, pos));
1664                         }
1665                     }
1666                 }
1667 #endif
1668
1669                 bool applyWordSpacing = false;
1670                 
1671                 currentCharacterIsWS = currentCharacterIsSpace || (breakNBSP && c == noBreakSpace);
1672
1673                 if ((breakAll || breakWords) && !midWordBreak) {
1674                     wrapW += charWidth;
1675                     charWidth = textWidth(t, pos, 1, f, w + wrapW, isFixedPitch, collapseWhiteSpace);
1676                     midWordBreak = w + wrapW + charWidth > width;
1677                 }
1678
1679                 bool betweenWords = c == '\n' || (currWS != PRE && !atStart && isBreakable(str, pos, strlen, nextBreakable, breakNBSP) && (style->hyphens() != HyphensNone || (pos && str[pos - 1] != softHyphen)));
1680
1681                 if (betweenWords || midWordBreak) {
1682                     bool stoppedIgnoringSpaces = false;
1683                     if (ignoringSpaces) {
1684                         if (!currentCharacterIsSpace) {
1685                             // Stop ignoring spaces and begin at this
1686                             // new point.
1687                             ignoringSpaces = false;
1688                             lastSpaceWordSpacing = 0;
1689                             lastSpace = pos; // e.g., "Foo    goo", don't add in any of the ignored spaces.
1690                             addMidpoint(lineMidpointState, InlineIterator(0, o, pos));
1691                             stoppedIgnoringSpaces = true;
1692                         } else {
1693                             // Just keep ignoring these spaces.
1694                             pos++;
1695                             len--;
1696                             continue;
1697                         }
1698                     }
1699
1700                     int additionalTmpW;
1701                     if (wordTrailingSpaceWidth && currentCharacterIsSpace)
1702                         additionalTmpW = textWidth(t, lastSpace, pos + 1 - lastSpace, f, w + tmpW, isFixedPitch, collapseWhiteSpace) - wordTrailingSpaceWidth + lastSpaceWordSpacing;
1703                     else
1704                         additionalTmpW = textWidth(t, lastSpace, pos - lastSpace, f, w + tmpW, isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing;
1705                     tmpW += additionalTmpW;
1706                     if (!appliedStartWidth) {
1707                         tmpW += inlineWidth(o, true, false);
1708                         appliedStartWidth = true;
1709                     }
1710                     
1711                     applyWordSpacing =  wordSpacing && currentCharacterIsSpace && !previousCharacterIsSpace;
1712
1713                     if (!w && autoWrap && tmpW > width)
1714                         fitBelowFloats(tmpW, firstLine, width);
1715
1716                     if (autoWrap || breakWords) {
1717                         // If we break only after white-space, consider the current character
1718                         // as candidate width for this line.
1719                         bool lineWasTooWide = false;
1720                         if (w + tmpW <= width && currentCharacterIsWS && o->style()->breakOnlyAfterWhiteSpace() && !midWordBreak) {
1721                             int charWidth = textWidth(t, pos, 1, f, w + tmpW, isFixedPitch, collapseWhiteSpace) + (applyWordSpacing ? wordSpacing : 0);
1722                             // Check if line is too big even without the extra space
1723                             // at the end of the line. If it is not, do nothing. 
1724                             // If the line needs the extra whitespace to be too long, 
1725                             // then move the line break to the space and skip all 
1726                             // additional whitespace.
1727                             if (w + tmpW + charWidth > width) {
1728                                 lineWasTooWide = true;
1729                                 lBreak.obj = o;
1730                                 lBreak.pos = pos;
1731                                 lBreak.nextBreakablePosition = nextBreakable;
1732                                 skipTrailingWhitespace(lBreak, isLineEmpty, previousLineBrokeCleanly);
1733                             }
1734                         }
1735                         if (lineWasTooWide || w + tmpW > width) {
1736                             if (canHyphenate && w + tmpW > width) {
1737                                 tryHyphenating(t, f, style->hyphenationLocale(), lastSpace, pos, w + tmpW - additionalTmpW, width, isFixedPitch, collapseWhiteSpace, lastSpaceWordSpacing, lBreak, nextBreakable, hyphenated);
1738                                 if (hyphenated)
1739                                     goto end;
1740                             }
1741                             if (lBreak.obj && shouldPreserveNewline(lBreak.obj) && lBreak.obj->isText() && toRenderText(lBreak.obj)->textLength() && !toRenderText(lBreak.obj)->isWordBreak() && toRenderText(lBreak.obj)->characters()[lBreak.pos] == '\n') {
1742                                 if (!stoppedIgnoringSpaces && pos > 0) {
1743                                     // We need to stop right before the newline and then start up again.
1744                                     addMidpoint(lineMidpointState, InlineIterator(0, o, pos - 1)); // Stop
1745                                     addMidpoint(lineMidpointState, InlineIterator(0, o, pos)); // Start
1746                                 }
1747                                 lBreak.increment();
1748                                 previousLineBrokeCleanly = true;
1749                             }
1750                             if (lBreak.obj && lBreak.pos && lBreak.obj->isText() && toRenderText(lBreak.obj)->textLength() && toRenderText(lBreak.obj)->characters()[lBreak.pos - 1] == softHyphen && style->hyphens() != HyphensNone)
1751                                 hyphenated = true;
1752                             goto end; // Didn't fit. Jump to the end.
1753                         } else {
1754                             if (!betweenWords || (midWordBreak && !autoWrap))
1755                                 tmpW -= additionalTmpW;
1756                             if (hyphenWidth) {
1757                                 // Subtract the width of the soft hyphen out since we fit on a line.
1758                                 tmpW -= hyphenWidth;
1759                                 hyphenWidth = 0;
1760                             }
1761                         }
1762                     }
1763
1764                     if (c == '\n' && preserveNewline) {
1765                         if (!stoppedIgnoringSpaces && pos > 0) {
1766                             // We need to stop right before the newline and then start up again.
1767                             addMidpoint(lineMidpointState, InlineIterator(0, o, pos - 1)); // Stop
1768                             addMidpoint(lineMidpointState, InlineIterator(0, o, pos)); // Start
1769                         }
1770                         lBreak.obj = o;
1771                         lBreak.pos = pos;
1772                         lBreak.nextBreakablePosition = nextBreakable;
1773                         lBreak.increment();
1774                         previousLineBrokeCleanly = true;
1775                         return lBreak;
1776                     }
1777
1778                     if (autoWrap && betweenWords) {
1779                         w += tmpW;
1780                         wrapW = 0;
1781                         tmpW = 0;
1782                         lBreak.obj = o;
1783                         lBreak.pos = pos;
1784                         lBreak.nextBreakablePosition = nextBreakable;
1785                         // Auto-wrapping text should not wrap in the middle of a word once it has had an
1786                         // opportunity to break after a word.
1787                         breakWords = false;
1788                     }
1789                     
1790                     if (midWordBreak) {
1791                         // Remember this as a breakable position in case
1792                         // adding the end width forces a break.
1793                         lBreak.obj = o;
1794                         lBreak.pos = pos;
1795                         lBreak.nextBreakablePosition = nextBreakable;
1796                         midWordBreak &= (breakWords || breakAll);
1797                     }
1798
1799                     if (betweenWords) {
1800                         lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
1801                         lastSpace = pos;
1802                     }
1803                     
1804                     if (!ignoringSpaces && o->style()->collapseWhiteSpace()) {
1805                         // If we encounter a newline, or if we encounter a
1806                         // second space, we need to go ahead and break up this
1807                         // run and enter a mode where we start collapsing spaces.
1808                         if (currentCharacterIsSpace && previousCharacterIsSpace) {
1809                             ignoringSpaces = true;
1810                             
1811                             // We just entered a mode where we are ignoring
1812                             // spaces. Create a midpoint to terminate the run
1813                             // before the second space. 
1814                             addMidpoint(lineMidpointState, ignoreStart);
1815                         }
1816                     }
1817                 } else if (ignoringSpaces) {
1818                     // Stop ignoring spaces and begin at this
1819                     // new point.
1820                     ignoringSpaces = false;
1821                     lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
1822                     lastSpace = pos; // e.g., "Foo    goo", don't add in any of the ignored spaces.
1823                     addMidpoint(lineMidpointState, InlineIterator(0, o, pos));
1824                 }
1825
1826                 if (currentCharacterIsSpace && !previousCharacterIsSpace) {
1827                     ignoreStart.obj = o;
1828                     ignoreStart.pos = pos;
1829                 }
1830
1831                 if (!currentCharacterIsWS && previousCharacterIsWS) {
1832                     if (autoWrap && o->style()->breakOnlyAfterWhiteSpace()) {
1833                         lBreak.obj = o;
1834                         lBreak.pos = pos;
1835                         lBreak.nextBreakablePosition = nextBreakable;
1836                     }
1837                 }
1838                 
1839                 if (collapseWhiteSpace && currentCharacterIsSpace && !ignoringSpaces)
1840                     trailingSpaceObject = o;
1841                 else if (!o->style()->collapseWhiteSpace() || !currentCharacterIsSpace)
1842                     trailingSpaceObject = 0;
1843                     
1844                 pos++;
1845                 len--;
1846                 atStart = false;
1847             }
1848
1849             // IMPORTANT: pos is > length here!
1850             int additionalTmpW = ignoringSpaces ? 0 : textWidth(t, lastSpace, pos - lastSpace, f, w + tmpW, isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing;
1851             tmpW += additionalTmpW;
1852             tmpW += inlineWidth(o, !appliedStartWidth, true);
1853
1854             if (canHyphenate && w + tmpW > width) {
1855                 tryHyphenating(t, f, style->hyphenationLocale(), lastSpace, pos, w + tmpW - additionalTmpW, width, isFixedPitch, collapseWhiteSpace, lastSpaceWordSpacing, lBreak, nextBreakable, hyphenated);
1856                 if (hyphenated)
1857                     goto end;
1858             }
1859         } else
1860             ASSERT_NOT_REACHED();
1861
1862         RenderObject* next = bidiNext(this, o);
1863         bool checkForBreak = autoWrap;
1864         if (w && w + tmpW > width && lBreak.obj && currWS == NOWRAP)
1865             checkForBreak = true;
1866         else if (next && o->isText() && next->isText() && !next->isBR()) {
1867             if (autoWrap || (next->style()->autoWrap())) {
1868                 if (currentCharacterIsSpace)
1869                     checkForBreak = true;
1870                 else {
1871                     checkForBreak = false;
1872                     RenderText* nextText = toRenderText(next);
1873                     if (nextText->textLength()) {
1874                         UChar c = nextText->characters()[0];
1875                         if (c == ' ' || c == '\t' || (c == '\n' && !shouldPreserveNewline(next)))
1876                             // If the next item on the line is text, and if we did not end with
1877                             // a space, then the next text run continues our word (and so it needs to
1878                             // keep adding to |tmpW|.  Just update and continue.
1879                             checkForBreak = true;
1880                     } else if (nextText->isWordBreak())
1881                         checkForBreak = true;
1882                     bool willFitOnLine = w + tmpW <= width;
1883                     if (!willFitOnLine && !w) {
1884                         fitBelowFloats(tmpW, firstLine, width);
1885                         willFitOnLine = tmpW <= width;
1886                     }
1887                     bool canPlaceOnLine = willFitOnLine || !autoWrapWasEverTrueOnLine;
1888                     if (canPlaceOnLine && checkForBreak) {
1889                         w += tmpW;
1890                         tmpW = 0;
1891                         lBreak.obj = next;
1892                         lBreak.pos = 0;
1893                         lBreak.nextBreakablePosition = -1;
1894                     }
1895                 }
1896             }
1897         }
1898
1899         if (checkForBreak && (w + tmpW > width)) {
1900             // if we have floats, try to get below them.
1901             if (currentCharacterIsSpace && !ignoringSpaces && o->style()->collapseWhiteSpace())
1902                 trailingSpaceObject = 0;
1903
1904             if (w)
1905                 goto end;
1906
1907             fitBelowFloats(tmpW, firstLine, width);
1908
1909             // |width| may have been adjusted because we got shoved down past a float (thus
1910             // giving us more room), so we need to retest, and only jump to
1911             // the end label if we still don't fit on the line. -dwh
1912             if (w + tmpW > width)
1913                 goto end;
1914         }
1915
1916         if (!o->isFloatingOrPositioned()) {
1917             last = o;
1918             if (last->isReplaced() && autoWrap && (!last->isImage() || allowImagesToBreak) && (!last->isListMarker() || toRenderListMarker(last)->isInside())) {
1919                 w += tmpW;
1920                 tmpW = 0;
1921                 lBreak.obj = next;
1922                 lBreak.pos = 0;
1923                 lBreak.nextBreakablePosition = -1;
1924             }
1925         }
1926
1927         o = next;
1928         nextBreakable = -1;
1929
1930         // Clear out our character space bool, since inline <pre>s don't collapse whitespace
1931         // with adjacent inline normal/nowrap spans.
1932         if (!collapseWhiteSpace)
1933             currentCharacterIsSpace = false;
1934         
1935         pos = 0;
1936         atStart = false;
1937     }
1938
1939     
1940     if (w + tmpW <= width || lastWS == NOWRAP) {
1941         lBreak.obj = 0;
1942         lBreak.pos = 0;
1943         lBreak.nextBreakablePosition = -1;
1944     }
1945
1946  end:
1947     if (lBreak == resolver.position() && (!lBreak.obj || !lBreak.obj->isBR())) {
1948         // we just add as much as possible
1949         if (style()->whiteSpace() == PRE) {
1950             // FIXME: Don't really understand this case.
1951             if (pos != 0) {
1952                 lBreak.obj = o;
1953                 lBreak.pos = pos - 1;
1954             } else {
1955                 lBreak.obj = last;
1956                 lBreak.pos = last->isText() ? last->length() : 0;
1957                 lBreak.nextBreakablePosition = -1;
1958             }
1959         } else if (lBreak.obj) {
1960             // Don't ever break in the middle of a word if we can help it.
1961             // There's no room at all. We just have to be on this line,
1962             // even though we'll spill out.
1963             lBreak.obj = o;
1964             lBreak.pos = pos;
1965             lBreak.nextBreakablePosition = -1;
1966         }
1967     }
1968
1969     // make sure we consume at least one char/object.
1970     if (lBreak == resolver.position())
1971         lBreak.increment();
1972
1973     // Sanity check our midpoints.
1974     checkMidpoints(lineMidpointState, lBreak);
1975         
1976     if (trailingSpaceObject) {
1977         // This object is either going to be part of the last midpoint, or it is going
1978         // to be the actual endpoint.  In both cases we just decrease our pos by 1 level to
1979         // exclude the space, allowing it to - in effect - collapse into the newline.
1980         if (lineMidpointState.numMidpoints % 2) {
1981             InlineIterator* midpoints = lineMidpointState.midpoints.data();
1982             midpoints[lineMidpointState.numMidpoints - 1].pos--;
1983         }
1984         //else if (lBreak.pos > 0)
1985         //    lBreak.pos--;
1986         else if (lBreak.obj == 0 && trailingSpaceObject->isText()) {
1987             // Add a new end midpoint that stops right at the very end.
1988             RenderText* text = toRenderText(trailingSpaceObject);
1989             unsigned length = text->textLength();
1990             unsigned pos = length >= 2 ? length - 2 : UINT_MAX;
1991             InlineIterator endMid(0, trailingSpaceObject, pos);
1992             addMidpoint(lineMidpointState, endMid);
1993         }
1994     }
1995
1996     // We might have made lBreak an iterator that points past the end
1997     // of the object. Do this adjustment to make it point to the start
1998     // of the next object instead to avoid confusing the rest of the
1999     // code.
2000     if (lBreak.pos > 0) {
2001         lBreak.pos--;
2002         lBreak.increment();
2003     }
2004
2005     return lBreak;
2006 }
2007
2008 void RenderBlock::addOverflowFromInlineChildren()
2009 {
2010     for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
2011         addLayoutOverflow(curr->layoutOverflowRect());
2012         if (!hasOverflowClip())
2013             addVisualOverflow(curr->visualOverflowRect());
2014     }
2015 }
2016
2017 void RenderBlock::deleteEllipsisLineBoxes()
2018 {
2019     for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox())
2020         curr->clearTruncation();
2021 }
2022
2023 void RenderBlock::checkLinesForTextOverflow()
2024 {
2025     // Determine the width of the ellipsis using the current font.
2026     // FIXME: CSS3 says this is configurable, also need to use 0x002E (FULL STOP) if horizontal ellipsis is "not renderable"
2027     TextRun ellipsisRun(&horizontalEllipsis, 1);
2028     DEFINE_STATIC_LOCAL(AtomicString, ellipsisStr, (&horizontalEllipsis, 1));
2029     const Font& firstLineFont = firstLineStyle()->font();
2030     const Font& font = style()->font();
2031     int firstLineEllipsisWidth = firstLineFont.width(ellipsisRun);
2032     int ellipsisWidth = (font == firstLineFont) ? firstLineEllipsisWidth : font.width(ellipsisRun);
2033
2034     // For LTR text truncation, we want to get the right edge of our padding box, and then we want to see
2035     // if the right edge of a line box exceeds that.  For RTL, we use the left edge of the padding box and
2036     // check the left edge of the line box to see if it is less
2037     // Include the scrollbar for overflow blocks, which means we want to use "contentWidth()"
2038     bool ltr = style()->isLeftToRightDirection();
2039     for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
2040         int blockRightEdge = logicalRightOffsetForLine(curr->y(), curr == firstRootBox());
2041         int blockLeftEdge = logicalLeftOffsetForLine(curr->y(), curr == firstRootBox());
2042         int lineBoxEdge = ltr ? curr->x() + curr->logicalWidth() : curr->x();
2043         if ((ltr && lineBoxEdge > blockRightEdge) || (!ltr && lineBoxEdge < blockLeftEdge)) {
2044             // This line spills out of our box in the appropriate direction.  Now we need to see if the line
2045             // can be truncated.  In order for truncation to be possible, the line must have sufficient space to
2046             // accommodate our truncation string, and no replaced elements (images, tables) can overlap the ellipsis
2047             // space.
2048             int width = curr == firstRootBox() ? firstLineEllipsisWidth : ellipsisWidth;
2049             int blockEdge = ltr ? blockRightEdge : blockLeftEdge;
2050             if (curr->canAccommodateEllipsis(ltr, blockEdge, lineBoxEdge, width))
2051                 curr->placeEllipsis(ellipsisStr, ltr, blockLeftEdge, blockRightEdge, width);
2052         }
2053     }
2054 }
2055
2056 }