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