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())) 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 // if overflow isn't visible, block elements may get clipped 899 // due to the limited content width. disable overflow clipping. 900 setHasOverflowClip(false); 901 902 IntRect overflow = layoutOverflowRect(); 903 if (overflow.width() > maxWidth) { 904 overflow.setWidth(maxWidth); 905 clearLayoutOverflow(); 906 addLayoutOverflow(overflow); 907 } 908 } 909 } 910 } 911 #endif 912 // We want to skip ahead to the first dirty line 913 InlineBidiResolver resolver; 914 unsigned floatIndex; 915 bool firstLine = true; 916 bool previousLineBrokeCleanly = true; 917 RootInlineBox* startLine = determineStartPosition(firstLine, fullLayout, previousLineBrokeCleanly, resolver, floats, floatIndex, 918 useRepaintBounds, repaintLogicalTop, repaintLogicalBottom); 919 920 if (fullLayout && hasInlineChild && !selfNeedsLayout()) { 921 setNeedsLayout(true, false); // Mark ourselves as needing a full layout. This way we'll repaint like 922 // we're supposed to. 923 RenderView* v = view(); 924 if (v && !v->doingFullRepaint() && hasLayer()) { 925 // Because we waited until we were already inside layout to discover 926 // that the block really needed a full layout, we missed our chance to repaint the layer 927 // before layout started. Luckily the layer has cached the repaint rect for its original 928 // position and size, and so we can use that to make a repaint happen now. 929 repaintUsingContainer(containerForRepaint(), layer()->repaintRect()); 930 } 931 } 932 933 FloatingObject* lastFloat = (m_floatingObjects && !m_floatingObjects->set().isEmpty()) ? m_floatingObjects->set().last() : 0; 934 935 LineMidpointState& lineMidpointState = resolver.midpointState(); 936 937 // We also find the first clean line and extract these lines. We will add them back 938 // if we determine that we're able to synchronize after handling all our dirty lines. 939 InlineIterator cleanLineStart; 940 BidiStatus cleanLineBidiStatus; 941 int endLineLogicalTop = 0; 942 RootInlineBox* endLine = (fullLayout || !startLine) ? 943 0 : determineEndPosition(startLine, floats, floatIndex, cleanLineStart, cleanLineBidiStatus, endLineLogicalTop); 944 945 if (startLine) { 946 if (!useRepaintBounds) { 947 useRepaintBounds = true; 948 repaintLogicalTop = logicalHeight(); 949 repaintLogicalBottom = logicalHeight(); 950 } 951 RenderArena* arena = renderArena(); 952 RootInlineBox* box = startLine; 953 while (box) { 954 repaintLogicalTop = min(repaintLogicalTop, box->logicalTopVisualOverflow()); 955 repaintLogicalBottom = max(repaintLogicalBottom, box->logicalBottomVisualOverflow()); 956 RootInlineBox* next = box->nextRootBox(); 957 box->deleteLine(arena); 958 box = next; 959 } 960 } 961 962 InlineIterator end = resolver.position(); 963 964 if (!fullLayout && lastRootBox() && lastRootBox()->endsWithBreak()) { 965 // If the last line before the start line ends with a line break that clear floats, 966 // adjust the height accordingly. 967 // A line break can be either the first or the last object on a line, depending on its direction. 968 if (InlineBox* lastLeafChild = lastRootBox()->lastLeafChild()) { 969 RenderObject* lastObject = lastLeafChild->renderer(); 970 if (!lastObject->isBR()) 971 lastObject = lastRootBox()->firstLeafChild()->renderer(); 972 if (lastObject->isBR()) { 973 EClear clear = lastObject->style()->clear(); 974 if (clear != CNONE) 975 newLine(clear); 976 } 977 } 978 } 979 980 bool endLineMatched = false; 981 bool checkForEndLineMatch = endLine; 982 bool checkForFloatsFromLastLine = false; 983 984 bool isLineEmpty = true; 985 bool paginated = view()->layoutState() && view()->layoutState()->isPaginated(); 986 987 LineBreakIteratorInfo lineBreakIteratorInfo; 988 VerticalPositionCache verticalPositionCache; 989 990 while (!end.atEnd()) { 991 // FIXME: Is this check necessary before the first iteration or can it be moved to the end? 992 if (checkForEndLineMatch && (endLineMatched = matchedEndLine(resolver, cleanLineStart, cleanLineBidiStatus, endLine, endLineLogicalTop, repaintLogicalBottom, repaintLogicalTop))) 993 break; 994 995 lineMidpointState.reset(); 996 997 isLineEmpty = true; 998 999 EClear clear = CNONE; 1000 bool hyphenated; 1001 Vector<RenderBox*> positionedObjects; 1002 1003 InlineIterator oldEnd = end; 1004 FloatingObject* lastFloatFromPreviousLine = (m_floatingObjects && !m_floatingObjects->set().isEmpty()) ? m_floatingObjects->set().last() : 0; 1005 end = findNextLineBreak(resolver, firstLine, isLineEmpty, lineBreakIteratorInfo, previousLineBrokeCleanly, hyphenated, &clear, lastFloatFromPreviousLine, positionedObjects); 1006 if (resolver.position().atEnd()) { 1007 // FIXME: We shouldn't be creating any runs in findNextLineBreak to begin with! 1008 // Once BidiRunList is separated from BidiResolver this will not be needed. 1009 resolver.runs().deleteRuns(); 1010 resolver.markCurrentRunEmpty(); // FIXME: This can probably be replaced by an ASSERT (or just removed). 1011 checkForFloatsFromLastLine = true; 1012 break; 1013 } 1014 ASSERT(end != resolver.position()); 1015 1016 if (isLineEmpty) { 1017 if (lastRootBox()) 1018 lastRootBox()->setLineBreakInfo(end.m_obj, end.m_pos, resolver.status()); 1019 } else { 1020 VisualDirectionOverride override = (style()->visuallyOrdered() ? (style()->direction() == LTR ? VisualLeftToRightOverride : VisualRightToLeftOverride) : NoVisualOverride); 1021 // FIXME: This ownership is reversed. We should own the BidiRunList and pass it to createBidiRunsForLine. 1022 BidiRunList<BidiRun>& bidiRuns = resolver.runs(); 1023 resolver.createBidiRunsForLine(end, override, previousLineBrokeCleanly); 1024 ASSERT(resolver.position() == end); 1025 1026 BidiRun* trailingSpaceRun = !previousLineBrokeCleanly ? handleTrailingSpaces(bidiRuns, resolver.context()) : 0; 1027 1028 // Now that the runs have been ordered, we create the line boxes. 1029 // At the same time we figure out where border/padding/margin should be applied for 1030 // inline flow boxes. 1031 1032 RootInlineBox* lineBox = 0; 1033 int oldLogicalHeight = logicalHeight(); 1034 if (bidiRuns.runCount()) { 1035 if (hyphenated) 1036 bidiRuns.logicallyLastRun()->m_hasHyphen = true; 1037 lineBox = constructLine(bidiRuns, firstLine, !end.m_obj); 1038 if (lineBox) { 1039 lineBox->setEndsWithBreak(previousLineBrokeCleanly); 1040 1041 #if ENABLE(SVG) 1042 bool isSVGRootInlineBox = lineBox->isSVGRootInlineBox(); 1043 #else 1044 bool isSVGRootInlineBox = false; 1045 #endif 1046 1047 GlyphOverflowAndFallbackFontsMap textBoxDataMap; 1048 1049 // Now we position all of our text runs horizontally. 1050 if (!isSVGRootInlineBox) 1051 computeInlineDirectionPositionsForLine(lineBox, firstLine, bidiRuns.firstRun(), trailingSpaceRun, end.atEnd(), textBoxDataMap, verticalPositionCache); 1052 1053 // Now position our text runs vertically. 1054 computeBlockDirectionPositionsForLine(lineBox, bidiRuns.firstRun(), textBoxDataMap, verticalPositionCache); 1055 1056 #if ENABLE(SVG) 1057 // SVG text layout code computes vertical & horizontal positions on its own. 1058 // Note that we still need to execute computeVerticalPositionsForLine() as 1059 // it calls InlineTextBox::positionLineBox(), which tracks whether the box 1060 // contains reversed text or not. If we wouldn't do that editing and thus 1061 // text selection in RTL boxes would not work as expected. 1062 if (isSVGRootInlineBox) { 1063 ASSERT(isSVGText()); 1064 static_cast<SVGRootInlineBox*>(lineBox)->computePerCharacterLayoutInformation(); 1065 } 1066 #endif 1067 1068 // Compute our overflow now. 1069 lineBox->computeOverflow(lineBox->lineTop(), lineBox->lineBottom(), textBoxDataMap); 1070 1071 #if PLATFORM(MAC) 1072 // Highlight acts as an overflow inflation. 1073 if (style()->highlight() != nullAtom) 1074 lineBox->addHighlightOverflow(); 1075 #endif 1076 } 1077 } 1078 1079 bidiRuns.deleteRuns(); 1080 resolver.markCurrentRunEmpty(); // FIXME: This can probably be replaced by an ASSERT (or just removed). 1081 1082 if (lineBox) { 1083 lineBox->setLineBreakInfo(end.m_obj, end.m_pos, resolver.status()); 1084 if (useRepaintBounds) { 1085 repaintLogicalTop = min(repaintLogicalTop, lineBox->logicalTopVisualOverflow()); 1086 repaintLogicalBottom = max(repaintLogicalBottom, lineBox->logicalBottomVisualOverflow()); 1087 } 1088 1089 if (paginated) { 1090 int adjustment = 0; 1091 adjustLinePositionForPagination(lineBox, adjustment); 1092 if (adjustment) { 1093 int oldLineWidth = availableLogicalWidthForLine(oldLogicalHeight, firstLine); 1094 lineBox->adjustBlockDirectionPosition(adjustment); 1095 if (useRepaintBounds) // This can only be a positive adjustment, so no need to update repaintTop. 1096 repaintLogicalBottom = max(repaintLogicalBottom, lineBox->logicalBottomVisualOverflow()); 1097 1098 if (availableLogicalWidthForLine(oldLogicalHeight + adjustment, firstLine) != oldLineWidth) { 1099 // We have to delete this line, remove all floats that got added, and let line layout re-run. 1100 lineBox->deleteLine(renderArena()); 1101 removeFloatingObjectsBelow(lastFloatFromPreviousLine, oldLogicalHeight); 1102 setLogicalHeight(oldLogicalHeight + adjustment); 1103 resolver.setPosition(oldEnd); 1104 end = oldEnd; 1105 continue; 1106 } 1107 1108 setLogicalHeight(lineBox->blockLogicalHeight()); 1109 } 1110 } 1111 } 1112 1113 for (size_t i = 0; i < positionedObjects.size(); ++i) 1114 setStaticPositions(this, positionedObjects[i]); 1115 1116 firstLine = false; 1117 newLine(clear); 1118 } 1119 1120 if (m_floatingObjects && lastRootBox()) { 1121 FloatingObjectSet& floatingObjectSet = m_floatingObjects->set(); 1122 FloatingObjectSetIterator it = floatingObjectSet.begin(); 1123 FloatingObjectSetIterator end = floatingObjectSet.end(); 1124 if (lastFloat) { 1125 FloatingObjectSetIterator lastFloatIterator = floatingObjectSet.find(lastFloat); 1126 ASSERT(lastFloatIterator != end); 1127 ++lastFloatIterator; 1128 it = lastFloatIterator; 1129 } 1130 for (; it != end; ++it) { 1131 FloatingObject* f = *it; 1132 appendFloatingObjectToLastLine(f); 1133 ASSERT(f->m_renderer == floats[floatIndex].object); 1134 // If a float's geometry has changed, give up on syncing with clean lines. 1135 if (floats[floatIndex].rect != f->frameRect()) 1136 checkForEndLineMatch = false; 1137 floatIndex++; 1138 } 1139 lastFloat = !floatingObjectSet.isEmpty() ? floatingObjectSet.last() : 0; 1140 } 1141 1142 lineMidpointState.reset(); 1143 resolver.setPosition(end); 1144 } 1145 1146 if (endLine) { 1147 if (endLineMatched) { 1148 // Attach all the remaining lines, and then adjust their y-positions as needed. 1149 int delta = logicalHeight() - endLineLogicalTop; 1150 for (RootInlineBox* line = endLine; line; line = line->nextRootBox()) { 1151 line->attachLine(); 1152 if (paginated) { 1153 delta -= line->paginationStrut(); 1154 adjustLinePositionForPagination(line, delta); 1155 } 1156 if (delta) { 1157 repaintLogicalTop = min(repaintLogicalTop, line->logicalTopVisualOverflow() + min(delta, 0)); 1158 repaintLogicalBottom = max(repaintLogicalBottom, line->logicalBottomVisualOverflow() + max(delta, 0)); 1159 line->adjustBlockDirectionPosition(delta); 1160 } 1161 if (Vector<RenderBox*>* cleanLineFloats = line->floatsPtr()) { 1162 Vector<RenderBox*>::iterator end = cleanLineFloats->end(); 1163 for (Vector<RenderBox*>::iterator f = cleanLineFloats->begin(); f != end; ++f) { 1164 FloatingObject* floatingObject = insertFloatingObject(*f); 1165 ASSERT(!floatingObject->m_originatingLine); 1166 floatingObject->m_originatingLine = line; 1167 setLogicalHeight(logicalTopForChild(*f) - marginBeforeForChild(*f) + delta); 1168 positionNewFloats(); 1169 } 1170 } 1171 } 1172 setLogicalHeight(lastRootBox()->blockLogicalHeight()); 1173 } else { 1174 // Delete all the remaining lines. 1175 RootInlineBox* line = endLine; 1176 RenderArena* arena = renderArena(); 1177 while (line) { 1178 repaintLogicalTop = min(repaintLogicalTop, line->logicalTopVisualOverflow()); 1179 repaintLogicalBottom = max(repaintLogicalBottom, line->logicalBottomVisualOverflow()); 1180 RootInlineBox* next = line->nextRootBox(); 1181 line->deleteLine(arena); 1182 line = next; 1183 } 1184 } 1185 } 1186 if (m_floatingObjects && (checkForFloatsFromLastLine || positionNewFloats()) && lastRootBox()) { 1187 // In case we have a float on the last line, it might not be positioned up to now. 1188 // This has to be done before adding in the bottom border/padding, or the float will 1189 // include the padding incorrectly. -dwh 1190 if (checkForFloatsFromLastLine) { 1191 int bottomVisualOverflow = lastRootBox()->logicalBottomVisualOverflow(); 1192 int bottomLayoutOverflow = lastRootBox()->logicalBottomLayoutOverflow(); 1193 TrailingFloatsRootInlineBox* trailingFloatsLineBox = new (renderArena()) TrailingFloatsRootInlineBox(this); 1194 m_lineBoxes.appendLineBox(trailingFloatsLineBox); 1195 trailingFloatsLineBox->setConstructed(); 1196 GlyphOverflowAndFallbackFontsMap textBoxDataMap; 1197 VerticalPositionCache verticalPositionCache; 1198 trailingFloatsLineBox->alignBoxesInBlockDirection(logicalHeight(), textBoxDataMap, verticalPositionCache); 1199 int blockLogicalHeight = logicalHeight(); 1200 IntRect logicalLayoutOverflow(0, blockLogicalHeight, 1, bottomLayoutOverflow - blockLogicalHeight); 1201 IntRect logicalVisualOverflow(0, blockLogicalHeight, 1, bottomVisualOverflow - blockLogicalHeight); 1202 trailingFloatsLineBox->setOverflowFromLogicalRects(logicalLayoutOverflow, logicalVisualOverflow, trailingFloatsLineBox->lineTop(), trailingFloatsLineBox->lineBottom()); 1203 trailingFloatsLineBox->setBlockLogicalHeight(logicalHeight()); 1204 } 1205 1206 FloatingObjectSet& floatingObjectSet = m_floatingObjects->set(); 1207 FloatingObjectSetIterator it = floatingObjectSet.begin(); 1208 FloatingObjectSetIterator end = floatingObjectSet.end(); 1209 if (lastFloat) { 1210 FloatingObjectSetIterator lastFloatIterator = floatingObjectSet.find(lastFloat); 1211 ASSERT(lastFloatIterator != end); 1212 ++lastFloatIterator; 1213 it = lastFloatIterator; 1214 } 1215 for (; it != end; ++it) 1216 appendFloatingObjectToLastLine(*it); 1217 lastFloat = !floatingObjectSet.isEmpty() ? floatingObjectSet.last() : 0; 1218 } 1219 size_t floatCount = floats.size(); 1220 // Floats that did not have layout did not repaint when we laid them out. They would have 1221 // painted by now if they had moved, but if they stayed at (0, 0), they still need to be 1222 // painted. 1223 for (size_t i = 0; i < floatCount; ++i) { 1224 if (!floats[i].everHadLayout) { 1225 RenderBox* f = floats[i].object; 1226 if (!f->x() && !f->y() && f->checkForRepaintDuringLayout()) 1227 f->repaint(); 1228 } 1229 } 1230 } 1231 1232 // Expand the last line to accommodate Ruby and emphasis marks. 1233 int lastLineAnnotationsAdjustment = 0; 1234 if (lastRootBox()) { 1235 int lowestAllowedPosition = max(lastRootBox()->lineBottom(), logicalHeight() + paddingAfter()); 1236 if (!style()->isFlippedLinesWritingMode()) 1237 lastLineAnnotationsAdjustment = lastRootBox()->computeUnderAnnotationAdjustment(lowestAllowedPosition); 1238 else 1239 lastLineAnnotationsAdjustment = lastRootBox()->computeOverAnnotationAdjustment(lowestAllowedPosition); 1240 } 1241 1242 // Now add in the bottom border/padding. 1243 setLogicalHeight(logicalHeight() + lastLineAnnotationsAdjustment + borderAfter() + paddingAfter() + scrollbarLogicalHeight()); 1244 1245 if (!firstLineBox() && hasLineIfEmpty()) 1246 setLogicalHeight(logicalHeight() + lineHeight(true, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes)); 1247 1248 // See if we have any lines that spill out of our block. If we do, then we will possibly need to 1249 // truncate text. 1250 if (hasTextOverflow) 1251 checkLinesForTextOverflow(); 1252 } 1253 1254 void RenderBlock::checkFloatsInCleanLine(RootInlineBox* line, Vector<FloatWithRect>& floats, size_t& floatIndex, bool& encounteredNewFloat, bool& dirtiedByFloat) 1255 { 1256 Vector<RenderBox*>* cleanLineFloats = line->floatsPtr(); 1257 if (!cleanLineFloats) 1258 return; 1259 1260 Vector<RenderBox*>::iterator end = cleanLineFloats->end(); 1261 for (Vector<RenderBox*>::iterator it = cleanLineFloats->begin(); it != end; ++it) { 1262 RenderBox* floatingBox = *it; 1263 floatingBox->layoutIfNeeded(); 1264 IntSize newSize(floatingBox->width() + floatingBox->marginLeft() + floatingBox->marginRight(), floatingBox->height() + floatingBox->marginTop() + floatingBox->marginBottom()); 1265 ASSERT(floatIndex < floats.size()); 1266 if (floats[floatIndex].object != floatingBox) { 1267 encounteredNewFloat = true; 1268 return; 1269 } 1270 if (floats[floatIndex].rect.size() != newSize) { 1271 int floatTop = isHorizontalWritingMode() ? floats[floatIndex].rect.y() : floats[floatIndex].rect.x(); 1272 int floatHeight = isHorizontalWritingMode() ? max(floats[floatIndex].rect.height(), newSize.height()) 1273 : max(floats[floatIndex].rect.width(), newSize.width()); 1274 floatHeight = min(floatHeight, numeric_limits<int>::max() - floatTop); 1275 line->markDirty(); 1276 markLinesDirtyInBlockRange(line->blockLogicalHeight(), floatTop + floatHeight, line); 1277 floats[floatIndex].rect.setSize(newSize); 1278 dirtiedByFloat = true; 1279 } 1280 floatIndex++; 1281 } 1282 } 1283 1284 RootInlineBox* RenderBlock::determineStartPosition(bool& firstLine, bool& fullLayout, bool& previousLineBrokeCleanly, 1285 InlineBidiResolver& resolver, Vector<FloatWithRect>& floats, unsigned& numCleanFloats, 1286 bool& useRepaintBounds, int& repaintLogicalTop, int& repaintLogicalBottom) 1287 { 1288 RootInlineBox* curr = 0; 1289 RootInlineBox* last = 0; 1290 1291 bool dirtiedByFloat = false; 1292 if (!fullLayout) { 1293 // Paginate all of the clean lines. 1294 bool paginated = view()->layoutState() && view()->layoutState()->isPaginated(); 1295 int paginationDelta = 0; 1296 size_t floatIndex = 0; 1297 for (curr = firstRootBox(); curr && !curr->isDirty(); curr = curr->nextRootBox()) { 1298 if (paginated) { 1299 paginationDelta -= curr->paginationStrut(); 1300 adjustLinePositionForPagination(curr, paginationDelta); 1301 if (paginationDelta) { 1302 if (containsFloats() || !floats.isEmpty()) { 1303 // FIXME: Do better eventually. For now if we ever shift because of pagination and floats are present just go to a full layout. 1304 fullLayout = true; 1305 break; 1306 } 1307 1308 if (!useRepaintBounds) 1309 useRepaintBounds = true; 1310 1311 repaintLogicalTop = min(repaintLogicalTop, curr->logicalTopVisualOverflow() + min(paginationDelta, 0)); 1312 repaintLogicalBottom = max(repaintLogicalBottom, curr->logicalBottomVisualOverflow() + max(paginationDelta, 0)); 1313 curr->adjustBlockDirectionPosition(paginationDelta); 1314 } 1315 } 1316 1317 // If a new float has been inserted before this line or before its last known float,just do a full layout. 1318 checkFloatsInCleanLine(curr, floats, floatIndex, fullLayout, dirtiedByFloat); 1319 if (dirtiedByFloat || fullLayout) 1320 break; 1321 } 1322 // Check if a new float has been inserted after the last known float. 1323 if (!curr && floatIndex < floats.size()) 1324 fullLayout = true; 1325 } 1326 1327 if (fullLayout) { 1328 // Nuke all our lines. 1329 if (firstRootBox()) { 1330 RenderArena* arena = renderArena(); 1331 curr = firstRootBox(); 1332 while (curr) { 1333 RootInlineBox* next = curr->nextRootBox(); 1334 curr->deleteLine(arena); 1335 curr = next; 1336 } 1337 ASSERT(!firstLineBox() && !lastLineBox()); 1338 } 1339 } else { 1340 if (curr) { 1341 // We have a dirty line. 1342 if (RootInlineBox* prevRootBox = curr->prevRootBox()) { 1343 // We have a previous line. 1344 if (!dirtiedByFloat && (!prevRootBox->endsWithBreak() || (prevRootBox->lineBreakObj()->isText() && prevRootBox->lineBreakPos() >= toRenderText(prevRootBox->lineBreakObj())->textLength()))) 1345 // The previous line didn't break cleanly or broke at a newline 1346 // that has been deleted, so treat it as dirty too. 1347 curr = prevRootBox; 1348 } 1349 } else { 1350 // No dirty lines were found. 1351 // If the last line didn't break cleanly, treat it as dirty. 1352 if (lastRootBox() && !lastRootBox()->endsWithBreak()) 1353 curr = lastRootBox(); 1354 } 1355 1356 // If we have no dirty lines, then last is just the last root box. 1357 last = curr ? curr->prevRootBox() : lastRootBox(); 1358 } 1359 1360 numCleanFloats = 0; 1361 if (!floats.isEmpty()) { 1362 int savedLogicalHeight = logicalHeight(); 1363 // Restore floats from clean lines. 1364 RootInlineBox* line = firstRootBox(); 1365 while (line != curr) { 1366 if (Vector<RenderBox*>* cleanLineFloats = line->floatsPtr()) { 1367 Vector<RenderBox*>::iterator end = cleanLineFloats->end(); 1368 for (Vector<RenderBox*>::iterator f = cleanLineFloats->begin(); f != end; ++f) { 1369 FloatingObject* floatingObject = insertFloatingObject(*f); 1370 ASSERT(!floatingObject->m_originatingLine); 1371 floatingObject->m_originatingLine = line; 1372 setLogicalHeight(logicalTopForChild(*f) - marginBeforeForChild(*f)); 1373 positionNewFloats(); 1374 ASSERT(floats[numCleanFloats].object == *f); 1375 numCleanFloats++; 1376 } 1377 } 1378 line = line->nextRootBox(); 1379 } 1380 setLogicalHeight(savedLogicalHeight); 1381 } 1382 1383 firstLine = !last; 1384 previousLineBrokeCleanly = !last || last->endsWithBreak(); 1385 1386 RenderObject* startObj; 1387 int pos = 0; 1388 if (last) { 1389 setLogicalHeight(last->blockLogicalHeight()); 1390 startObj = last->lineBreakObj(); 1391 pos = last->lineBreakPos(); 1392 resolver.setStatus(last->lineBreakBidiStatus()); 1393 } else { 1394 bool ltr = style()->isLeftToRightDirection(); 1395 Direction direction = ltr ? LeftToRight : RightToLeft; 1396 resolver.setLastStrongDir(direction); 1397 resolver.setLastDir(direction); 1398 resolver.setEorDir(direction); 1399 resolver.setContext(BidiContext::create(ltr ? 0 : 1, direction, style()->unicodeBidi() == Override, FromStyleOrDOM)); 1400 1401 startObj = bidiFirst(this, &resolver); 1402 } 1403 1404 resolver.setPosition(InlineIterator(this, startObj, pos)); 1405 1406 return curr; 1407 } 1408 1409 RootInlineBox* RenderBlock::determineEndPosition(RootInlineBox* startLine, Vector<FloatWithRect>& floats, size_t floatIndex, InlineIterator& cleanLineStart, BidiStatus& cleanLineBidiStatus, int& logicalTop) 1410 { 1411 RootInlineBox* last = 0; 1412 for (RootInlineBox* curr = startLine->nextRootBox(); curr; curr = curr->nextRootBox()) { 1413 if (!curr->isDirty()) { 1414 bool encounteredNewFloat = false; 1415 bool dirtiedByFloat = false; 1416 checkFloatsInCleanLine(curr, floats, floatIndex, encounteredNewFloat, dirtiedByFloat); 1417 if (encounteredNewFloat) 1418 return 0; 1419 } 1420 if (curr->isDirty()) 1421 last = 0; 1422 else if (!last) 1423 last = curr; 1424 } 1425 1426 if (!last) 1427 return 0; 1428 1429 // At this point, |last| is the first line in a run of clean lines that ends with the last line 1430 // in the block. 1431 1432 RootInlineBox* prev = last->prevRootBox(); 1433 cleanLineStart = InlineIterator(this, prev->lineBreakObj(), prev->lineBreakPos()); 1434 cleanLineBidiStatus = prev->lineBreakBidiStatus(); 1435 logicalTop = prev->blockLogicalHeight(); 1436 1437 for (RootInlineBox* line = last; line; line = line->nextRootBox()) 1438 line->extractLine(); // Disconnect all line boxes from their render objects while preserving 1439 // their connections to one another. 1440 1441 return last; 1442 } 1443 1444 bool RenderBlock::matchedEndLine(const InlineBidiResolver& resolver, const InlineIterator& endLineStart, const BidiStatus& endLineStatus, RootInlineBox*& endLine, 1445 int& endLogicalTop, int& repaintLogicalBottom, int& repaintLogicalTop) 1446 { 1447 if (resolver.position() == endLineStart) { 1448 if (resolver.status() != endLineStatus) 1449 return false; 1450 1451 int delta = logicalHeight() - endLogicalTop; 1452 if (!delta || !m_floatingObjects) 1453 return true; 1454 1455 // See if any floats end in the range along which we want to shift the lines vertically. 1456 int logicalTop = min(logicalHeight(), endLogicalTop); 1457 1458 RootInlineBox* lastLine = endLine; 1459 while (RootInlineBox* nextLine = lastLine->nextRootBox()) 1460 lastLine = nextLine; 1461 1462 int logicalBottom = lastLine->blockLogicalHeight() + abs(delta); 1463 1464 FloatingObjectSet& floatingObjectSet = m_floatingObjects->set(); 1465 FloatingObjectSetIterator end = floatingObjectSet.end(); 1466 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) { 1467 FloatingObject* f = *it; 1468 if (logicalBottomForFloat(f) >= logicalTop && logicalBottomForFloat(f) < logicalBottom) 1469 return false; 1470 } 1471 1472 return true; 1473 } 1474 1475 // The first clean line doesn't match, but we can check a handful of following lines to try 1476 // to match back up. 1477 static int numLines = 8; // The # of lines we're willing to match against. 1478 RootInlineBox* line = endLine; 1479 for (int i = 0; i < numLines && line; i++, line = line->nextRootBox()) { 1480 if (line->lineBreakObj() == resolver.position().m_obj && line->lineBreakPos() == resolver.position().m_pos) { 1481 // We have a match. 1482 if (line->lineBreakBidiStatus() != resolver.status()) 1483 return false; // ...but the bidi state doesn't match. 1484 RootInlineBox* result = line->nextRootBox(); 1485 1486 // Set our logical top to be the block height of endLine. 1487 if (result) 1488 endLogicalTop = line->blockLogicalHeight(); 1489 1490 int delta = logicalHeight() - endLogicalTop; 1491 if (delta && m_floatingObjects) { 1492 // See if any floats end in the range along which we want to shift the lines vertically. 1493 int logicalTop = min(logicalHeight(), endLogicalTop); 1494 1495 RootInlineBox* lastLine = endLine; 1496 while (RootInlineBox* nextLine = lastLine->nextRootBox()) 1497 lastLine = nextLine; 1498 1499 int logicalBottom = lastLine->blockLogicalHeight() + abs(delta); 1500 1501 FloatingObjectSet& floatingObjectSet = m_floatingObjects->set(); 1502 FloatingObjectSetIterator end = floatingObjectSet.end(); 1503 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) { 1504 FloatingObject* f = *it; 1505 if (logicalBottomForFloat(f) >= logicalTop && logicalBottomForFloat(f) < logicalBottom) 1506 return false; 1507 } 1508 } 1509 1510 // Now delete the lines that we failed to sync. 1511 RootInlineBox* boxToDelete = endLine; 1512 RenderArena* arena = renderArena(); 1513 while (boxToDelete && boxToDelete != result) { 1514 repaintLogicalTop = min(repaintLogicalTop, boxToDelete->logicalTopVisualOverflow()); 1515 repaintLogicalBottom = max(repaintLogicalBottom, boxToDelete->logicalBottomVisualOverflow()); 1516 RootInlineBox* next = boxToDelete->nextRootBox(); 1517 boxToDelete->deleteLine(arena); 1518 boxToDelete = next; 1519 } 1520 1521 endLine = result; 1522 return result; 1523 } 1524 } 1525 1526 return false; 1527 } 1528 1529 static inline bool skipNonBreakingSpace(const InlineIterator& it, bool isLineEmpty, bool previousLineBrokeCleanly) 1530 { 1531 if (it.m_obj->style()->nbspMode() != SPACE || it.current() != noBreakSpace) 1532 return false; 1533 1534 // FIXME: This is bad. It makes nbsp inconsistent with space and won't work correctly 1535 // with m_minWidth/m_maxWidth. 1536 // Do not skip a non-breaking space if it is the first character 1537 // on a line after a clean line break (or on the first line, since previousLineBrokeCleanly starts off 1538 // |true|). 1539 if (isLineEmpty && previousLineBrokeCleanly) 1540 return false; 1541 1542 return true; 1543 } 1544 1545 static inline bool shouldCollapseWhiteSpace(const RenderStyle* style, bool isLineEmpty, bool previousLineBrokeCleanly) 1546 { 1547 return style->collapseWhiteSpace() || (style->whiteSpace() == PRE_WRAP && (!isLineEmpty || !previousLineBrokeCleanly)); 1548 } 1549 1550 static bool inlineFlowRequiresLineBox(RenderInline* flow) 1551 { 1552 // FIXME: Right now, we only allow line boxes for inlines that are truly empty. 1553 // We need to fix this, though, because at the very least, inlines containing only 1554 // ignorable whitespace should should also have line boxes. 1555 return !flow->firstChild() && flow->hasInlineDirectionBordersPaddingOrMargin(); 1556 } 1557 1558 bool RenderBlock::requiresLineBox(const InlineIterator& it, bool isLineEmpty, bool previousLineBrokeCleanly) 1559 { 1560 if (it.m_obj->isFloatingOrPositioned()) 1561 return false; 1562 1563 if (it.m_obj->isRenderInline() && !inlineFlowRequiresLineBox(toRenderInline(it.m_obj))) 1564 return false; 1565 1566 if (!shouldCollapseWhiteSpace(it.m_obj->style(), isLineEmpty, previousLineBrokeCleanly) || it.m_obj->isBR()) 1567 return true; 1568 1569 UChar current = it.current(); 1570 return current != ' ' && current != '\t' && current != softHyphen && (current != '\n' || it.m_obj->preservesNewline()) 1571 && !skipNonBreakingSpace(it, isLineEmpty, previousLineBrokeCleanly); 1572 } 1573 1574 bool RenderBlock::generatesLineBoxesForInlineChild(RenderObject* inlineObj, bool isLineEmpty, bool previousLineBrokeCleanly) 1575 { 1576 ASSERT(inlineObj->parent() == this); 1577 1578 InlineIterator it(this, inlineObj, 0); 1579 while (!it.atEnd() && !requiresLineBox(it, isLineEmpty, previousLineBrokeCleanly)) 1580 it.increment(); 1581 1582 return !it.atEnd(); 1583 } 1584 1585 // FIXME: The entire concept of the skipTrailingWhitespace function is flawed, since we really need to be building 1586 // line boxes even for containers that may ultimately collapse away. Otherwise we'll never get positioned 1587 // elements quite right. In other words, we need to build this function's work into the normal line 1588 // object iteration process. 1589 // NB. this function will insert any floating elements that would otherwise 1590 // be skipped but it will not position them. 1591 void RenderBlock::skipTrailingWhitespace(InlineIterator& iterator, bool isLineEmpty, bool previousLineBrokeCleanly) 1592 { 1593 while (!iterator.atEnd() && !requiresLineBox(iterator, isLineEmpty, previousLineBrokeCleanly)) { 1594 RenderObject* object = iterator.m_obj; 1595 if (object->isFloating()) { 1596 insertFloatingObject(toRenderBox(object)); 1597 } else if (object->isPositioned()) 1598 setStaticPositions(this, toRenderBox(object)); 1599 iterator.increment(); 1600 } 1601 } 1602 1603 void RenderBlock::skipLeadingWhitespace(InlineBidiResolver& resolver, bool isLineEmpty, bool previousLineBrokeCleanly, 1604 FloatingObject* lastFloatFromPreviousLine, LineWidth& width) 1605 { 1606 while (!resolver.position().atEnd() && !requiresLineBox(resolver.position(), isLineEmpty, previousLineBrokeCleanly)) { 1607 RenderObject* object = resolver.position().m_obj; 1608 if (object->isFloating()) 1609 positionNewFloatOnLine(insertFloatingObject(toRenderBox(object)), lastFloatFromPreviousLine, width); 1610 else if (object->isPositioned()) 1611 setStaticPositions(this, toRenderBox(object)); 1612 resolver.increment(); 1613 } 1614 resolver.commitExplicitEmbedding(); 1615 } 1616 1617 // This is currently just used for list markers and inline flows that have line boxes. Neither should 1618 // have an effect on whitespace at the start of the line. 1619 static bool shouldSkipWhitespaceAfterStartObject(RenderBlock* block, RenderObject* o, LineMidpointState& lineMidpointState) 1620 { 1621 RenderObject* next = bidiNext(block, o); 1622 if (next && !next->isBR() && next->isText() && toRenderText(next)->textLength() > 0) { 1623 RenderText* nextText = toRenderText(next); 1624 UChar nextChar = nextText->characters()[0]; 1625 if (nextText->style()->isCollapsibleWhiteSpace(nextChar)) { 1626 addMidpoint(lineMidpointState, InlineIterator(0, o, 0)); 1627 return true; 1628 } 1629 } 1630 1631 return false; 1632 } 1633 1634 static inline float textWidth(RenderText* text, unsigned from, unsigned len, const Font& font, float xPos, bool isFixedPitch, bool collapseWhiteSpace) 1635 { 1636 if (isFixedPitch || (!from && len == text->textLength()) || text->style()->hasTextCombine()) 1637 return text->width(from, len, font, xPos); 1638 return font.width(TextRun(text->characters() + from, len, !collapseWhiteSpace, xPos)); 1639 } 1640 1641 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) 1642 { 1643 // Map 'hyphenate-limit-{before,after}: auto;' to 2. 1644 if (minimumPrefixLength < 0) 1645 minimumPrefixLength = 2; 1646 1647 if (minimumSuffixLength < 0) 1648 minimumSuffixLength = 2; 1649 1650 if (pos - lastSpace <= minimumSuffixLength) 1651 return; 1652 1653 const AtomicString& hyphenString = text->style()->hyphenString(); 1654 int hyphenWidth = font.width(TextRun(hyphenString.characters(), hyphenString.length())); 1655 1656 float maxPrefixWidth = availableWidth - xPos - hyphenWidth - lastSpaceWordSpacing; 1657 // If the maximum width available for the prefix before the hyphen is small, then it is very unlikely 1658 // that an hyphenation opportunity exists, so do not bother to look for it. 1659 if (maxPrefixWidth <= font.pixelSize() * 5 / 4) 1660 return; 1661 1662 unsigned prefixLength = font.offsetForPosition(TextRun(text->characters() + lastSpace, pos - lastSpace, !collapseWhiteSpace, xPos + lastSpaceWordSpacing), maxPrefixWidth, false); 1663 if (prefixLength < static_cast<unsigned>(minimumPrefixLength)) 1664 return; 1665 1666 prefixLength = lastHyphenLocation(text->characters() + lastSpace, pos - lastSpace, min(prefixLength, static_cast<unsigned>(pos - lastSpace - minimumSuffixLength)) + 1, localeIdentifier); 1667 // FIXME: The following assumes that the character at lastSpace is a space (and therefore should not factor 1668 // into hyphenate-limit-before) unless lastSpace is 0. This is wrong in the rare case of hyphenating 1669 // the first word in a text node which has leading whitespace. 1670 if (!prefixLength || prefixLength - (lastSpace ? 1 : 0) < static_cast<unsigned>(minimumPrefixLength)) 1671 return; 1672 1673 ASSERT(pos - lastSpace - prefixLength >= static_cast<unsigned>(minimumSuffixLength)); 1674 1675 #if !ASSERT_DISABLED 1676 float prefixWidth = hyphenWidth + textWidth(text, lastSpace, prefixLength, font, xPos, isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing; 1677 ASSERT(xPos + prefixWidth <= availableWidth); 1678 #else 1679 UNUSED_PARAM(isFixedPitch); 1680 #endif 1681 1682 lineBreak.moveTo(text, lastSpace + prefixLength, nextBreakable); 1683 hyphenated = true; 1684 } 1685 1686 class LineWidth { 1687 public: 1688 LineWidth(RenderBlock* block, bool isFirstLine) 1689 : m_block(block) 1690 , m_uncommittedWidth(0) 1691 , m_committedWidth(0) 1692 , m_overhangWidth(0) 1693 , m_left(0) 1694 , m_right(0) 1695 , m_availableWidth(0) 1696 , m_isFirstLine(isFirstLine) 1697 { 1698 ASSERT(block); 1699 updateAvailableWidth(); 1700 } 1701 bool fitsOnLine() const { return currentWidth() <= m_availableWidth; } 1702 bool fitsOnLine(float extra) const { return currentWidth() + extra <= m_availableWidth; } 1703 float currentWidth() const { return m_committedWidth + m_uncommittedWidth; } 1704 1705 // FIXME: We should eventually replace these three functions by ones that work on a higher abstraction. 1706 float uncommittedWidth() const { return m_uncommittedWidth; } 1707 float committedWidth() const { return m_committedWidth; } 1708 float availableWidth() const { return m_availableWidth; } 1709 1710 void updateAvailableWidth(); 1711 void shrinkAvailableWidthForNewFloatIfNeeded(RenderBlock::FloatingObject*); 1712 void addUncommittedWidth(float delta) { m_uncommittedWidth += delta; } 1713 void commit() 1714 { 1715 m_committedWidth += m_uncommittedWidth; 1716 m_uncommittedWidth = 0; 1717 } 1718 void applyOverhang(RenderRubyRun*, RenderObject* startRenderer, RenderObject* endRenderer); 1719 void fitBelowFloats(); 1720 1721 private: 1722 void computeAvailableWidthFromLeftAndRight() 1723 { 1724 m_availableWidth = max(0, m_right - m_left) + m_overhangWidth; 1725 } 1726 1727 private: 1728 RenderBlock* m_block; 1729 float m_uncommittedWidth; 1730 float m_committedWidth; 1731 float m_overhangWidth; // The amount by which |m_availableWidth| has been inflated to account for possible contraction due to ruby overhang. 1732 int m_left; 1733 int m_right; 1734 float m_availableWidth; 1735 bool m_isFirstLine; 1736 }; 1737 1738 inline void LineWidth::updateAvailableWidth() 1739 { 1740 int height = m_block->logicalHeight(); 1741 m_left = m_block->logicalLeftOffsetForLine(height, m_isFirstLine); 1742 m_right = m_block->logicalRightOffsetForLine(height, m_isFirstLine); 1743 1744 computeAvailableWidthFromLeftAndRight(); 1745 } 1746 1747 inline void LineWidth::shrinkAvailableWidthForNewFloatIfNeeded(RenderBlock::FloatingObject* newFloat) 1748 { 1749 int height = m_block->logicalHeight(); 1750 if (height < m_block->logicalTopForFloat(newFloat) || height >= m_block->logicalBottomForFloat(newFloat)) 1751 return; 1752 1753 if (newFloat->type() == RenderBlock::FloatingObject::FloatLeft) 1754 m_left = m_block->logicalRightForFloat(newFloat); 1755 else 1756 m_right = m_block->logicalLeftForFloat(newFloat); 1757 1758 computeAvailableWidthFromLeftAndRight(); 1759 } 1760 1761 void LineWidth::applyOverhang(RenderRubyRun* rubyRun, RenderObject* startRenderer, RenderObject* endRenderer) 1762 { 1763 int startOverhang; 1764 int endOverhang; 1765 rubyRun->getOverhang(m_isFirstLine, startRenderer, endRenderer, startOverhang, endOverhang); 1766 1767 startOverhang = min<int>(startOverhang, m_committedWidth); 1768 m_availableWidth += startOverhang; 1769 1770 endOverhang = max(min<int>(endOverhang, m_availableWidth - currentWidth()), 0); 1771 m_availableWidth += endOverhang; 1772 m_overhangWidth += startOverhang + endOverhang; 1773 } 1774 1775 void LineWidth::fitBelowFloats() 1776 { 1777 ASSERT(!m_committedWidth); 1778 ASSERT(!fitsOnLine()); 1779 1780 int floatLogicalBottom; 1781 int lastFloatLogicalBottom = m_block->logicalHeight(); 1782 float newLineWidth = m_availableWidth; 1783 while (true) { 1784 floatLogicalBottom = m_block->nextFloatLogicalBottomBelow(lastFloatLogicalBottom); 1785 if (!floatLogicalBottom) 1786 break; 1787 1788 newLineWidth = m_block->availableLogicalWidthForLine(floatLogicalBottom, m_isFirstLine); 1789 lastFloatLogicalBottom = floatLogicalBottom; 1790 if (newLineWidth >= m_uncommittedWidth) 1791 break; 1792 } 1793 1794 if (newLineWidth > m_availableWidth) { 1795 m_block->setLogicalHeight(lastFloatLogicalBottom); 1796 m_availableWidth = newLineWidth + m_overhangWidth; 1797 } 1798 } 1799 1800 InlineIterator RenderBlock::findNextLineBreak(InlineBidiResolver& resolver, bool firstLine, bool& isLineEmpty, LineBreakIteratorInfo& lineBreakIteratorInfo, bool& previousLineBrokeCleanly, 1801 bool& hyphenated, EClear* clear, FloatingObject* lastFloatFromPreviousLine, Vector<RenderBox*>& positionedBoxes) 1802 { 1803 ASSERT(resolver.position().root() == this); 1804 1805 bool appliedStartWidth = resolver.position().m_pos > 0; 1806 LineMidpointState& lineMidpointState = resolver.midpointState(); 1807 1808 LineWidth width(this, firstLine); 1809 1810 skipLeadingWhitespace(resolver, isLineEmpty, previousLineBrokeCleanly, lastFloatFromPreviousLine, width); 1811 1812 if (resolver.position().atEnd()) 1813 return resolver.position(); 1814 1815 // This variable is used only if whitespace isn't set to PRE, and it tells us whether 1816 // or not we are currently ignoring whitespace. 1817 bool ignoringSpaces = false; 1818 InlineIterator ignoreStart; 1819 1820 // This variable tracks whether the very last character we saw was a space. We use 1821 // this to detect when we encounter a second space so we know we have to terminate 1822 // a run. 1823 bool currentCharacterIsSpace = false; 1824 bool currentCharacterIsWS = false; 1825 RenderObject* trailingSpaceObject = 0; 1826 Vector<RenderBox*, 4> trailingPositionedBoxes; 1827 1828 InlineIterator lBreak = resolver.position(); 1829 1830 // FIXME: It is error-prone to split the position object out like this. 1831 // Teach this code to work with objects instead of this split tuple. 1832 RenderObject* o = resolver.position().m_obj; 1833 RenderObject* last = o; 1834 unsigned pos = resolver.position().m_pos; 1835 int nextBreakable = resolver.position().m_nextBreakablePosition; 1836 bool atStart = true; 1837 1838 bool prevLineBrokeCleanly = previousLineBrokeCleanly; 1839 previousLineBrokeCleanly = false; 1840 1841 hyphenated = false; 1842 1843 bool autoWrapWasEverTrueOnLine = false; 1844 bool floatsFitOnLine = true; 1845 1846 // Firefox and Opera will allow a table cell to grow to fit an image inside it under 1847 // very specific circumstances (in order to match common WinIE renderings). 1848 // Not supporting the quirk has caused us to mis-render some real sites. (See Bugzilla 10517.) 1849 bool allowImagesToBreak = !document()->inQuirksMode() || !isTableCell() || !style()->logicalWidth().isIntrinsicOrAuto(); 1850 1851 EWhiteSpace currWS = style()->whiteSpace(); 1852 EWhiteSpace lastWS = currWS; 1853 while (o) { 1854 RenderObject* next = bidiNext(this, o); 1855 1856 currWS = o->isReplaced() ? o->parent()->style()->whiteSpace() : o->style()->whiteSpace(); 1857 lastWS = last->isReplaced() ? last->parent()->style()->whiteSpace() : last->style()->whiteSpace(); 1858 1859 bool autoWrap = RenderStyle::autoWrap(currWS); 1860 autoWrapWasEverTrueOnLine = autoWrapWasEverTrueOnLine || autoWrap; 1861 1862 #if ENABLE(SVG) 1863 bool preserveNewline = o->isSVGInlineText() ? false : RenderStyle::preserveNewline(currWS); 1864 #else 1865 bool preserveNewline = RenderStyle::preserveNewline(currWS); 1866 #endif 1867 1868 bool collapseWhiteSpace = RenderStyle::collapseWhiteSpace(currWS); 1869 1870 if (o->isBR()) { 1871 if (width.fitsOnLine()) { 1872 lBreak.moveToStartOf(o); 1873 lBreak.increment(); 1874 1875 // A <br> always breaks a line, so don't let the line be collapsed 1876 // away. Also, the space at the end of a line with a <br> does not 1877 // get collapsed away. It only does this if the previous line broke 1878 // cleanly. Otherwise the <br> has no effect on whether the line is 1879 // empty or not. 1880 if (prevLineBrokeCleanly) 1881 isLineEmpty = false; 1882 trailingSpaceObject = 0; 1883 previousLineBrokeCleanly = true; 1884 1885 if (!isLineEmpty && clear) 1886 *clear = o->style()->clear(); 1887 } 1888 goto end; 1889 } 1890 1891 if (o->isFloatingOrPositioned()) { 1892 // add to special objects... 1893 if (o->isFloating()) { 1894 RenderBox* floatBox = toRenderBox(o); 1895 FloatingObject* f = insertFloatingObject(floatBox); 1896 // check if it fits in the current line. 1897 // If it does, position it now, otherwise, position 1898 // it after moving to next line (in newLine() func) 1899 if (floatsFitOnLine && width.fitsOnLine(logicalWidthForFloat(f))) { 1900 positionNewFloatOnLine(f, lastFloatFromPreviousLine, width); 1901 if (lBreak.m_obj == o) { 1902 ASSERT(!lBreak.m_pos); 1903 lBreak.increment(); 1904 } 1905 } else 1906 floatsFitOnLine = false; 1907 } else if (o->isPositioned()) { 1908 // If our original display wasn't an inline type, then we can 1909 // go ahead and determine our static inline position now. 1910 RenderBox* box = toRenderBox(o); 1911 bool isInlineType = box->style()->isOriginalDisplayInlineType(); 1912 if (!isInlineType) 1913 box->layer()->setStaticInlinePosition(borderAndPaddingStart()); 1914 else { 1915 // If our original display was an INLINE type, then we can go ahead 1916 // and determine our static y position now. 1917 box->layer()->setStaticBlockPosition(logicalHeight()); 1918 } 1919 1920 // If we're ignoring spaces, we have to stop and include this object and 1921 // then start ignoring spaces again. 1922 if (isInlineType || o->container()->isRenderInline()) { 1923 if (ignoringSpaces) { 1924 ignoreStart.m_obj = o; 1925 ignoreStart.m_pos = 0; 1926 addMidpoint(lineMidpointState, ignoreStart); // Stop ignoring spaces. 1927 addMidpoint(lineMidpointState, ignoreStart); // Start ignoring again. 1928 } 1929 if (trailingSpaceObject) 1930 trailingPositionedBoxes.append(box); 1931 } else 1932 positionedBoxes.append(box); 1933 } 1934 } else if (o->isRenderInline()) { 1935 // Right now, we should only encounter empty inlines here. 1936 ASSERT(!o->firstChild()); 1937 1938 RenderInline* flowBox = toRenderInline(o); 1939 1940 // Now that some inline flows have line boxes, if we are already ignoring spaces, we need 1941 // to make sure that we stop to include this object and then start ignoring spaces again. 1942 // If this object is at the start of the line, we need to behave like list markers and 1943 // start ignoring spaces. 1944 if (inlineFlowRequiresLineBox(flowBox)) { 1945 isLineEmpty = false; 1946 if (ignoringSpaces) { 1947 trailingSpaceObject = 0; 1948 trailingPositionedBoxes.clear(); 1949 addMidpoint(lineMidpointState, InlineIterator(0, o, 0)); // Stop ignoring spaces. 1950 addMidpoint(lineMidpointState, InlineIterator(0, o, 0)); // Start ignoring again. 1951 } else if (style()->collapseWhiteSpace() && resolver.position().m_obj == o 1952 && shouldSkipWhitespaceAfterStartObject(this, o, lineMidpointState)) { 1953 // Like with list markers, we start ignoring spaces to make sure that any 1954 // additional spaces we see will be discarded. 1955 currentCharacterIsSpace = true; 1956 currentCharacterIsWS = true; 1957 ignoringSpaces = true; 1958 } 1959 } 1960 1961 width.addUncommittedWidth(borderPaddingMarginStart(flowBox) + borderPaddingMarginEnd(flowBox)); 1962 } else if (o->isReplaced()) { 1963 RenderBox* replacedBox = toRenderBox(o); 1964 1965 // Break on replaced elements if either has normal white-space. 1966 if ((autoWrap || RenderStyle::autoWrap(lastWS)) && (!o->isImage() || allowImagesToBreak)) { 1967 width.commit(); 1968 lBreak.moveToStartOf(o); 1969 } 1970 1971 if (ignoringSpaces) 1972 addMidpoint(lineMidpointState, InlineIterator(0, o, 0)); 1973 1974 isLineEmpty = false; 1975 ignoringSpaces = false; 1976 currentCharacterIsSpace = false; 1977 currentCharacterIsWS = false; 1978 trailingSpaceObject = 0; 1979 trailingPositionedBoxes.clear(); 1980 1981 // Optimize for a common case. If we can't find whitespace after the list 1982 // item, then this is all moot. 1983 int replacedLogicalWidth = logicalWidthForChild(replacedBox) + marginStartForChild(replacedBox) + marginEndForChild(replacedBox) + inlineLogicalWidth(o); 1984 if (o->isListMarker()) { 1985 if (style()->collapseWhiteSpace() && shouldSkipWhitespaceAfterStartObject(this, o, lineMidpointState)) { 1986 // Like with inline flows, we start ignoring spaces to make sure that any 1987 // additional spaces we see will be discarded. 1988 currentCharacterIsSpace = true; 1989 currentCharacterIsWS = true; 1990 ignoringSpaces = true; 1991 } 1992 if (toRenderListMarker(o)->isInside()) 1993 width.addUncommittedWidth(replacedLogicalWidth); 1994 } else 1995 width.addUncommittedWidth(replacedLogicalWidth); 1996 if (o->isRubyRun()) 1997 width.applyOverhang(toRenderRubyRun(o), last, next); 1998 } else if (o->isText()) { 1999 if (!pos) 2000 appliedStartWidth = false; 2001 2002 RenderText* t = toRenderText(o); 2003 2004 #if ENABLE(SVG) 2005 bool isSVGText = t->isSVGInlineText(); 2006 #endif 2007 2008 RenderStyle* style = t->style(firstLine); 2009 if (style->hasTextCombine() && o->isCombineText()) 2010 toRenderCombineText(o)->combineText(); 2011 2012 int strlen = t->textLength(); 2013 int len = strlen - pos; 2014 const UChar* str = t->characters(); 2015 2016 const Font& f = style->font(); 2017 bool isFixedPitch = f.isFixedPitch(); 2018 bool canHyphenate = style->hyphens() == HyphensAuto && WebCore::canHyphenate(style->locale()); 2019 2020 int lastSpace = pos; 2021 float wordSpacing = o->style()->wordSpacing(); 2022 float lastSpaceWordSpacing = 0; 2023 2024 // Non-zero only when kerning is enabled, in which case we measure words with their trailing 2025 // space, then subtract its width. 2026 float wordTrailingSpaceWidth = f.typesettingFeatures() & Kerning ? f.width(TextRun(&space, 1)) + wordSpacing : 0; 2027 2028 float wrapW = width.uncommittedWidth() + inlineLogicalWidth(o, !appliedStartWidth, true); 2029 float charWidth = 0; 2030 bool breakNBSP = autoWrap && o->style()->nbspMode() == SPACE; 2031 // Auto-wrapping text should wrap in the middle of a word only if it could not wrap before the word, 2032 // which is only possible if the word is the first thing on the line, that is, if |w| is zero. 2033 bool breakWords = o->style()->breakWords() && ((autoWrap && !width.committedWidth()) || currWS == PRE); 2034 bool midWordBreak = false; 2035 bool breakAll = o->style()->wordBreak() == BreakAllWordBreak && autoWrap; 2036 float hyphenWidth = 0; 2037 2038 if (t->isWordBreak()) { 2039 width.commit(); 2040 lBreak.moveToStartOf(o); 2041 ASSERT(!len); 2042 } 2043 2044 while (len) { 2045 bool previousCharacterIsSpace = currentCharacterIsSpace; 2046 bool previousCharacterIsWS = currentCharacterIsWS; 2047 UChar c = str[pos]; 2048 currentCharacterIsSpace = c == ' ' || c == '\t' || (!preserveNewline && (c == '\n')); 2049 2050 if (!collapseWhiteSpace || !currentCharacterIsSpace) 2051 isLineEmpty = false; 2052 2053 if (c == softHyphen && autoWrap && !hyphenWidth && style->hyphens() != HyphensNone) { 2054 const AtomicString& hyphenString = style->hyphenString(); 2055 hyphenWidth = f.width(TextRun(hyphenString.characters(), hyphenString.length())); 2056 width.addUncommittedWidth(hyphenWidth); 2057 } 2058 2059 bool applyWordSpacing = false; 2060 2061 currentCharacterIsWS = currentCharacterIsSpace || (breakNBSP && c == noBreakSpace); 2062 2063 if ((breakAll || breakWords) && !midWordBreak) { 2064 wrapW += charWidth; 2065 charWidth = textWidth(t, pos, 1, f, width.committedWidth() + wrapW, isFixedPitch, collapseWhiteSpace); 2066 midWordBreak = width.committedWidth() + wrapW + charWidth > width.availableWidth(); 2067 } 2068 2069 if (lineBreakIteratorInfo.first != t) { 2070 lineBreakIteratorInfo.first = t; 2071 lineBreakIteratorInfo.second.reset(str, strlen); 2072 } 2073 2074 bool betweenWords = c == '\n' || (currWS != PRE && !atStart && isBreakable(lineBreakIteratorInfo.second, pos, nextBreakable, breakNBSP) && (style->hyphens() != HyphensNone || (pos && str[pos - 1] != softHyphen))); 2075 2076 if (betweenWords || midWordBreak) { 2077 bool stoppedIgnoringSpaces = false; 2078 if (ignoringSpaces) { 2079 if (!currentCharacterIsSpace) { 2080 // Stop ignoring spaces and begin at this 2081 // new point. 2082 ignoringSpaces = false; 2083 lastSpaceWordSpacing = 0; 2084 lastSpace = pos; // e.g., "Foo goo", don't add in any of the ignored spaces. 2085 addMidpoint(lineMidpointState, InlineIterator(0, o, pos)); 2086 stoppedIgnoringSpaces = true; 2087 } else { 2088 // Just keep ignoring these spaces. 2089 pos++; 2090 len--; 2091 continue; 2092 } 2093 } 2094 2095 float additionalTmpW; 2096 if (wordTrailingSpaceWidth && currentCharacterIsSpace) 2097 additionalTmpW = textWidth(t, lastSpace, pos + 1 - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) - wordTrailingSpaceWidth + lastSpaceWordSpacing; 2098 else 2099 additionalTmpW = textWidth(t, lastSpace, pos - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing; 2100 width.addUncommittedWidth(additionalTmpW); 2101 if (!appliedStartWidth) { 2102 width.addUncommittedWidth(inlineLogicalWidth(o, true, false)); 2103 appliedStartWidth = true; 2104 } 2105 2106 applyWordSpacing = wordSpacing && currentCharacterIsSpace && !previousCharacterIsSpace; 2107 2108 if (!width.committedWidth() && autoWrap && !width.fitsOnLine()) 2109 width.fitBelowFloats(); 2110 2111 if (autoWrap || breakWords) { 2112 // If we break only after white-space, consider the current character 2113 // as candidate width for this line. 2114 bool lineWasTooWide = false; 2115 if (width.fitsOnLine() && currentCharacterIsWS && o->style()->breakOnlyAfterWhiteSpace() && !midWordBreak) { 2116 int charWidth = textWidth(t, pos, 1, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) + (applyWordSpacing ? wordSpacing : 0); 2117 // Check if line is too big even without the extra space 2118 // at the end of the line. If it is not, do nothing. 2119 // If the line needs the extra whitespace to be too long, 2120 // then move the line break to the space and skip all 2121 // additional whitespace. 2122 if (!width.fitsOnLine(charWidth)) { 2123 lineWasTooWide = true; 2124 lBreak.moveTo(o, pos, nextBreakable); 2125 skipTrailingWhitespace(lBreak, isLineEmpty, previousLineBrokeCleanly); 2126 } 2127 } 2128 if (lineWasTooWide || !width.fitsOnLine()) { 2129 if (canHyphenate && !width.fitsOnLine()) { 2130 tryHyphenating(t, f, style->locale(), style->hyphenationLimitBefore(), style->hyphenationLimitAfter(), lastSpace, pos, width.currentWidth() - additionalTmpW, width.availableWidth(), isFixedPitch, collapseWhiteSpace, lastSpaceWordSpacing, lBreak, nextBreakable, hyphenated); 2131 if (hyphenated) 2132 goto end; 2133 } 2134 if (lBreak.atTextParagraphSeparator()) { 2135 if (!stoppedIgnoringSpaces && pos > 0) { 2136 // We need to stop right before the newline and then start up again. 2137 addMidpoint(lineMidpointState, InlineIterator(0, o, pos - 1)); // Stop 2138 addMidpoint(lineMidpointState, InlineIterator(0, o, pos)); // Start 2139 } 2140 lBreak.increment(); 2141 previousLineBrokeCleanly = true; 2142 } 2143 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) 2144 hyphenated = true; 2145 goto end; // Didn't fit. Jump to the end. 2146 } else { 2147 if (!betweenWords || (midWordBreak && !autoWrap)) 2148 width.addUncommittedWidth(-additionalTmpW); 2149 if (hyphenWidth) { 2150 // Subtract the width of the soft hyphen out since we fit on a line. 2151 width.addUncommittedWidth(-hyphenWidth); 2152 hyphenWidth = 0; 2153 } 2154 } 2155 } 2156 2157 if (c == '\n' && preserveNewline) { 2158 if (!stoppedIgnoringSpaces && pos > 0) { 2159 // We need to stop right before the newline and then start up again. 2160 addMidpoint(lineMidpointState, InlineIterator(0, o, pos - 1)); // Stop 2161 addMidpoint(lineMidpointState, InlineIterator(0, o, pos)); // Start 2162 } 2163 lBreak.moveTo(o, pos, nextBreakable); 2164 lBreak.increment(); 2165 previousLineBrokeCleanly = true; 2166 return lBreak; 2167 } 2168 2169 if (autoWrap && betweenWords) { 2170 width.commit(); 2171 wrapW = 0; 2172 lBreak.moveTo(o, pos, nextBreakable); 2173 // Auto-wrapping text should not wrap in the middle of a word once it has had an 2174 // opportunity to break after a word. 2175 breakWords = false; 2176 } 2177 2178 if (midWordBreak) { 2179 // Remember this as a breakable position in case 2180 // adding the end width forces a break. 2181 lBreak.moveTo(o, pos, nextBreakable); 2182 midWordBreak &= (breakWords || breakAll); 2183 } 2184 2185 if (betweenWords) { 2186 lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0; 2187 lastSpace = pos; 2188 } 2189 2190 if (!ignoringSpaces && o->style()->collapseWhiteSpace()) { 2191 // If we encounter a newline, or if we encounter a 2192 // second space, we need to go ahead and break up this 2193 // run and enter a mode where we start collapsing spaces. 2194 if (currentCharacterIsSpace && previousCharacterIsSpace) { 2195 ignoringSpaces = true; 2196 2197 // We just entered a mode where we are ignoring 2198 // spaces. Create a midpoint to terminate the run 2199 // before the second space. 2200 addMidpoint(lineMidpointState, ignoreStart); 2201 } 2202 } 2203 } else if (ignoringSpaces) { 2204 // Stop ignoring spaces and begin at this 2205 // new point. 2206 ignoringSpaces = false; 2207 lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0; 2208 lastSpace = pos; // e.g., "Foo goo", don't add in any of the ignored spaces. 2209 addMidpoint(lineMidpointState, InlineIterator(0, o, pos)); 2210 } 2211 2212 #if ENABLE(SVG) 2213 if (isSVGText && pos > 0) { 2214 // Force creation of new InlineBoxes for each absolute positioned character (those that start new text chunks). 2215 if (static_cast<RenderSVGInlineText*>(t)->characterStartsNewTextChunk(pos)) { 2216 addMidpoint(lineMidpointState, InlineIterator(0, o, pos - 1)); 2217 addMidpoint(lineMidpointState, InlineIterator(0, o, pos)); 2218 } 2219 } 2220 #endif 2221 2222 if (currentCharacterIsSpace && !previousCharacterIsSpace) { 2223 ignoreStart.m_obj = o; 2224 ignoreStart.m_pos = pos; 2225 } 2226 2227 if (!currentCharacterIsWS && previousCharacterIsWS) { 2228 if (autoWrap && o->style()->breakOnlyAfterWhiteSpace()) 2229 lBreak.moveTo(o, pos, nextBreakable); 2230 } 2231 2232 if (collapseWhiteSpace && currentCharacterIsSpace && !ignoringSpaces) 2233 trailingSpaceObject = o; 2234 else if (!o->style()->collapseWhiteSpace() || !currentCharacterIsSpace) { 2235 trailingSpaceObject = 0; 2236 trailingPositionedBoxes.clear(); 2237 } 2238 2239 pos++; 2240 len--; 2241 atStart = false; 2242 } 2243 2244 // IMPORTANT: pos is > length here! 2245 float additionalTmpW = ignoringSpaces ? 0 : textWidth(t, lastSpace, pos - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing; 2246 width.addUncommittedWidth(additionalTmpW + inlineLogicalWidth(o, !appliedStartWidth, true)); 2247 2248 if (!width.fitsOnLine()) { 2249 if (canHyphenate) 2250 tryHyphenating(t, f, style->locale(), style->hyphenationLimitBefore(), style->hyphenationLimitAfter(), lastSpace, pos, width.currentWidth() - additionalTmpW, width.availableWidth(), isFixedPitch, collapseWhiteSpace, lastSpaceWordSpacing, lBreak, nextBreakable, hyphenated); 2251 2252 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) 2253 hyphenated = true; 2254 2255 if (hyphenated) 2256 goto end; 2257 } 2258 } else 2259 ASSERT_NOT_REACHED(); 2260 2261 bool checkForBreak = autoWrap; 2262 if (width.committedWidth() && !width.fitsOnLine() && lBreak.m_obj && currWS == NOWRAP) 2263 checkForBreak = true; 2264 else if (next && o->isText() && next->isText() && !next->isBR()) { 2265 if (autoWrap || (next->style()->autoWrap())) { 2266 if (currentCharacterIsSpace) 2267 checkForBreak = true; 2268 else { 2269 checkForBreak = false; 2270 RenderText* nextText = toRenderText(next); 2271 if (nextText->textLength()) { 2272 UChar c = nextText->characters()[0]; 2273 if (c == ' ' || c == '\t' || (c == '\n' && !next->preservesNewline())) 2274 // If the next item on the line is text, and if we did not end with 2275 // a space, then the next text run continues our word (and so it needs to 2276 // keep adding to |tmpW|. Just update and continue. 2277 checkForBreak = true; 2278 } else if (nextText->isWordBreak()) 2279 checkForBreak = true; 2280 2281 if (!width.fitsOnLine() && !width.committedWidth()) 2282 width.fitBelowFloats(); 2283 2284 bool canPlaceOnLine = width.fitsOnLine() || !autoWrapWasEverTrueOnLine; 2285 if (canPlaceOnLine && checkForBreak) { 2286 width.commit(); 2287 lBreak.moveToStartOf(next); 2288 } 2289 } 2290 } 2291 } 2292 2293 if (checkForBreak && !width.fitsOnLine()) { 2294 // if we have floats, try to get below them. 2295 if (currentCharacterIsSpace && !ignoringSpaces && o->style()->collapseWhiteSpace()) { 2296 trailingSpaceObject = 0; 2297 trailingPositionedBoxes.clear(); 2298 } 2299 2300 if (width.committedWidth()) 2301 goto end; 2302 2303 width.fitBelowFloats(); 2304 2305 // |width| may have been adjusted because we got shoved down past a float (thus 2306 // giving us more room), so we need to retest, and only jump to 2307 // the end label if we still don't fit on the line. -dwh 2308 if (!width.fitsOnLine()) 2309 goto end; 2310 } 2311 2312 if (!o->isFloatingOrPositioned()) { 2313 last = o; 2314 if (last->isReplaced() && autoWrap && (!last->isImage() || allowImagesToBreak) && (!last->isListMarker() || toRenderListMarker(last)->isInside())) { 2315 width.commit(); 2316 lBreak.moveToStartOf(next); 2317 } 2318 } 2319 2320 o = next; 2321 nextBreakable = -1; 2322 2323 // Clear out our character space bool, since inline <pre>s don't collapse whitespace 2324 // with adjacent inline normal/nowrap spans. 2325 if (!collapseWhiteSpace) 2326 currentCharacterIsSpace = false; 2327 2328 pos = 0; 2329 atStart = false; 2330 } 2331 2332 if (width.fitsOnLine() || lastWS == NOWRAP) 2333 lBreak.clear(); 2334 2335 end: 2336 if (lBreak == resolver.position() && (!lBreak.m_obj || !lBreak.m_obj->isBR())) { 2337 // we just add as much as possible 2338 if (style()->whiteSpace() == PRE) { 2339 // FIXME: Don't really understand this case. 2340 if (pos != 0) { 2341 // FIXME: This should call moveTo which would clear m_nextBreakablePosition 2342 // this code as-is is likely wrong. 2343 lBreak.m_obj = o; 2344 lBreak.m_pos = pos - 1; 2345 } else 2346 lBreak.moveTo(last, last->isText() ? last->length() : 0); 2347 } else if (lBreak.m_obj) { 2348 // Don't ever break in the middle of a word if we can help it. 2349 // There's no room at all. We just have to be on this line, 2350 // even though we'll spill out. 2351 lBreak.moveTo(o, pos); 2352 } 2353 } 2354 2355 // make sure we consume at least one char/object. 2356 if (lBreak == resolver.position()) 2357 lBreak.increment(); 2358 2359 // Sanity check our midpoints. 2360 checkMidpoints(lineMidpointState, lBreak); 2361 2362 if (trailingSpaceObject) { 2363 // This object is either going to be part of the last midpoint, or it is going 2364 // to be the actual endpoint. In both cases we just decrease our pos by 1 level to 2365 // exclude the space, allowing it to - in effect - collapse into the newline. 2366 if (lineMidpointState.numMidpoints % 2) { 2367 // Find the trailing space object's midpoint. 2368 int trailingSpaceMidpoint = lineMidpointState.numMidpoints - 1; 2369 for ( ; trailingSpaceMidpoint >= 0 && lineMidpointState.midpoints[trailingSpaceMidpoint].m_obj != trailingSpaceObject; --trailingSpaceMidpoint) { } 2370 ASSERT(trailingSpaceMidpoint >= 0); 2371 lineMidpointState.midpoints[trailingSpaceMidpoint].m_pos--; 2372 2373 // Now make sure every single trailingPositionedBox following the trailingSpaceMidpoint properly stops and starts 2374 // ignoring spaces. 2375 size_t currentMidpoint = trailingSpaceMidpoint + 1; 2376 for (size_t i = 0; i < trailingPositionedBoxes.size(); ++i) { 2377 if (currentMidpoint >= lineMidpointState.numMidpoints) { 2378 // We don't have a midpoint for this box yet. 2379 InlineIterator ignoreStart(this, trailingPositionedBoxes[i], 0); 2380 addMidpoint(lineMidpointState, ignoreStart); // Stop ignoring. 2381 addMidpoint(lineMidpointState, ignoreStart); // Start ignoring again. 2382 } else { 2383 ASSERT(lineMidpointState.midpoints[currentMidpoint].m_obj == trailingPositionedBoxes[i]); 2384 ASSERT(lineMidpointState.midpoints[currentMidpoint + 1].m_obj == trailingPositionedBoxes[i]); 2385 } 2386 currentMidpoint += 2; 2387 } 2388 } else if (!lBreak.m_obj && trailingSpaceObject->isText()) { 2389 // Add a new end midpoint that stops right at the very end. 2390 RenderText* text = toRenderText(trailingSpaceObject); 2391 unsigned length = text->textLength(); 2392 unsigned pos = length >= 2 ? length - 2 : UINT_MAX; 2393 InlineIterator endMid(0, trailingSpaceObject, pos); 2394 addMidpoint(lineMidpointState, endMid); 2395 for (size_t i = 0; i < trailingPositionedBoxes.size(); ++i) { 2396 ignoreStart.m_obj = trailingPositionedBoxes[i]; 2397 ignoreStart.m_pos = 0; 2398 addMidpoint(lineMidpointState, ignoreStart); // Stop ignoring spaces. 2399 addMidpoint(lineMidpointState, ignoreStart); // Start ignoring again. 2400 } 2401 } 2402 } 2403 2404 // We might have made lBreak an iterator that points past the end 2405 // of the object. Do this adjustment to make it point to the start 2406 // of the next object instead to avoid confusing the rest of the 2407 // code. 2408 if (lBreak.m_pos > 0) { 2409 lBreak.m_pos--; 2410 lBreak.increment(); 2411 } 2412 2413 return lBreak; 2414 } 2415 2416 void RenderBlock::addOverflowFromInlineChildren() 2417 { 2418 int endPadding = hasOverflowClip() ? paddingEnd() : 0; 2419 // FIXME: Need to find another way to do this, since scrollbars could show when we don't want them to. 2420 if (hasOverflowClip() && !endPadding && node() && node()->rendererIsEditable() && node() == node()->rootEditableElement() && style()->isLeftToRightDirection()) 2421 endPadding = 1; 2422 for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) { 2423 addLayoutOverflow(curr->paddedLayoutOverflowRect(endPadding)); 2424 if (!hasOverflowClip()) 2425 addVisualOverflow(curr->visualOverflowRect(curr->lineTop(), curr->lineBottom())); 2426 } 2427 } 2428 2429 void RenderBlock::deleteEllipsisLineBoxes() 2430 { 2431 for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) 2432 curr->clearTruncation(); 2433 } 2434 2435 void RenderBlock::checkLinesForTextOverflow() 2436 { 2437 // Determine the width of the ellipsis using the current font. 2438 // FIXME: CSS3 says this is configurable, also need to use 0x002E (FULL STOP) if horizontal ellipsis is "not renderable" 2439 TextRun ellipsisRun(&horizontalEllipsis, 1); 2440 DEFINE_STATIC_LOCAL(AtomicString, ellipsisStr, (&horizontalEllipsis, 1)); 2441 const Font& firstLineFont = firstLineStyle()->font(); 2442 const Font& font = style()->font(); 2443 int firstLineEllipsisWidth = firstLineFont.width(ellipsisRun); 2444 int ellipsisWidth = (font == firstLineFont) ? firstLineEllipsisWidth : font.width(ellipsisRun); 2445 2446 // For LTR text truncation, we want to get the right edge of our padding box, and then we want to see 2447 // if the right edge of a line box exceeds that. For RTL, we use the left edge of the padding box and 2448 // check the left edge of the line box to see if it is less 2449 // Include the scrollbar for overflow blocks, which means we want to use "contentWidth()" 2450 bool ltr = style()->isLeftToRightDirection(); 2451 for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) { 2452 int blockRightEdge = logicalRightOffsetForLine(curr->y(), curr == firstRootBox()); 2453 int blockLeftEdge = logicalLeftOffsetForLine(curr->y(), curr == firstRootBox()); 2454 int lineBoxEdge = ltr ? curr->x() + curr->logicalWidth() : curr->x(); 2455 if ((ltr && lineBoxEdge > blockRightEdge) || (!ltr && lineBoxEdge < blockLeftEdge)) { 2456 // This line spills out of our box in the appropriate direction. Now we need to see if the line 2457 // can be truncated. In order for truncation to be possible, the line must have sufficient space to 2458 // accommodate our truncation string, and no replaced elements (images, tables) can overlap the ellipsis 2459 // space. 2460 int width = curr == firstRootBox() ? firstLineEllipsisWidth : ellipsisWidth; 2461 int blockEdge = ltr ? blockRightEdge : blockLeftEdge; 2462 if (curr->lineCanAccommodateEllipsis(ltr, blockEdge, lineBoxEdge, width)) 2463 curr->placeEllipsis(ellipsisStr, ltr, blockLeftEdge, blockRightEdge, width); 2464 } 2465 } 2466 } 2467 2468 bool RenderBlock::positionNewFloatOnLine(FloatingObject* newFloat, FloatingObject* lastFloatFromPreviousLine, LineWidth& width) 2469 { 2470 if (!positionNewFloats()) 2471 return false; 2472 2473 width.shrinkAvailableWidthForNewFloatIfNeeded(newFloat); 2474 2475 if (!newFloat->m_paginationStrut) 2476 return true; 2477 2478 FloatingObjectSet& floatingObjectSet = m_floatingObjects->set(); 2479 ASSERT(floatingObjectSet.last() == newFloat); 2480 2481 int floatLogicalTop = logicalTopForFloat(newFloat); 2482 int paginationStrut = newFloat->m_paginationStrut; 2483 2484 if (floatLogicalTop - paginationStrut != logicalHeight()) 2485 return true; 2486 2487 FloatingObjectSetIterator it = floatingObjectSet.end(); 2488 --it; // Last float is newFloat, skip that one. 2489 FloatingObjectSetIterator begin = floatingObjectSet.begin(); 2490 while (it != begin) { 2491 --it; 2492 FloatingObject* f = *it; 2493 if (f == lastFloatFromPreviousLine) 2494 break; 2495 if (logicalTopForFloat(f) == logicalHeight()) { 2496 ASSERT(!f->m_paginationStrut); 2497 f->m_paginationStrut = paginationStrut; 2498 RenderBox* o = f->m_renderer; 2499 setLogicalTopForChild(o, logicalTopForChild(o) + marginBeforeForChild(o) + paginationStrut); 2500 if (o->isRenderBlock()) 2501 toRenderBlock(o)->setChildNeedsLayout(true, false); 2502 o->layoutIfNeeded(); 2503 setLogicalTopForFloat(f, logicalTopForFloat(f) + f->m_paginationStrut); 2504 } 2505 } 2506 2507 setLogicalHeight(logicalHeight() + paginationStrut); 2508 width.updateAvailableWidth(); 2509 2510 return true; 2511 } 2512 2513 } 2514