2 * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
3 * Copyright (C) 2003, 2004, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All right reserved.
4 * Copyright (C) 2010 Google Inc. All rights reserved.
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.
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.
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.
25 #include "BidiResolver.h"
26 #include "Hyphenation.h"
27 #include "InlineIterator.h"
28 #include "InlineTextBox.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"
38 #include "TextBreakIterator.h"
39 #include "TrailingFloatsRootInlineBox.h"
40 #include "VerticalPositionCache.h"
41 #include "break_lines.h"
42 #include <wtf/AlwaysInline.h>
43 #include <wtf/RefCountedLeakCounter.h>
44 #include <wtf/StdLibExtras.h>
45 #include <wtf/Vector.h>
46 #include <wtf/unicode/CharacterNames.h>
49 #include "RenderSVGInlineText.h"
50 #include "SVGRootInlineBox.h"
55 using namespace Unicode;
59 // We don't let our line box tree for a single line get any deeper than this.
60 const unsigned cMaxLineDepth = 200;
68 , m_previousLineBrokeCleanly(true)
71 bool isFirstLine() const { return m_isFirstLine; }
72 bool isLastLine() const { return m_isLastLine; }
73 bool isEmpty() const { return m_isEmpty; }
74 bool previousLineBrokeCleanly() const { return m_previousLineBrokeCleanly; }
76 void setFirstLine(bool firstLine) { m_isFirstLine = firstLine; }
77 void setLastLine(bool lastLine) { m_isLastLine = lastLine; }
78 void setEmpty(bool empty) { m_isEmpty = empty; }
79 void setPreviousLineBrokeCleanly(bool previousLineBrokeCleanly) { m_previousLineBrokeCleanly = previousLineBrokeCleanly; }
85 bool m_previousLineBrokeCleanly;
88 static inline int borderPaddingMarginStart(RenderInline* child)
90 return child->marginStart() + child->paddingStart() + child->borderStart();
93 static inline int borderPaddingMarginEnd(RenderInline* child)
95 return child->marginEnd() + child->paddingEnd() + child->borderEnd();
98 static int inlineLogicalWidth(RenderObject* child, bool start = true, bool end = true)
100 unsigned lineDepth = 1;
102 RenderObject* parent = child->parent();
103 while (parent->isRenderInline() && lineDepth++ < cMaxLineDepth) {
104 RenderInline* parentAsRenderInline = toRenderInline(parent);
105 if (start && !child->previousSibling())
106 extraWidth += borderPaddingMarginStart(parentAsRenderInline);
107 if (end && !child->nextSibling())
108 extraWidth += borderPaddingMarginEnd(parentAsRenderInline);
110 parent = child->parent();
115 static void determineParagraphDirection(TextDirection& dir, InlineIterator iter)
117 while (!iter.atEnd()) {
118 if (iter.atParagraphSeparator())
120 if (UChar current = iter.current()) {
121 Direction charDirection = direction(current);
122 if (charDirection == LeftToRight) {
126 if (charDirection == RightToLeft || charDirection == RightToLeftArabic) {
135 static void checkMidpoints(LineMidpointState& lineMidpointState, InlineIterator& lBreak)
137 // Check to see if our last midpoint is a start point beyond the line break. If so,
138 // shave it off the list, and shave off a trailing space if the previous end point doesn't
139 // preserve whitespace.
140 if (lBreak.m_obj && lineMidpointState.numMidpoints && !(lineMidpointState.numMidpoints % 2)) {
141 InlineIterator* midpoints = lineMidpointState.midpoints.data();
142 InlineIterator& endpoint = midpoints[lineMidpointState.numMidpoints - 2];
143 const InlineIterator& startpoint = midpoints[lineMidpointState.numMidpoints - 1];
144 InlineIterator currpoint = endpoint;
145 while (!currpoint.atEnd() && currpoint != startpoint && currpoint != lBreak)
146 currpoint.increment();
147 if (currpoint == lBreak) {
148 // We hit the line break before the start point. Shave off the start point.
149 lineMidpointState.numMidpoints--;
150 if (endpoint.m_obj->style()->collapseWhiteSpace())
156 static void addMidpoint(LineMidpointState& lineMidpointState, const InlineIterator& midpoint)
158 if (lineMidpointState.midpoints.size() <= lineMidpointState.numMidpoints)
159 lineMidpointState.midpoints.grow(lineMidpointState.numMidpoints + 10);
161 InlineIterator* midpoints = lineMidpointState.midpoints.data();
162 midpoints[lineMidpointState.numMidpoints++] = midpoint;
165 static inline BidiRun* createRun(int start, int end, RenderObject* obj, InlineBidiResolver& resolver)
167 return new (obj->renderArena()) BidiRun(start, end, obj, resolver.context(), resolver.dir());
170 void RenderBlock::appendRunsForObject(BidiRunList<BidiRun>& runs, int start, int end, RenderObject* obj, InlineBidiResolver& resolver)
172 if (start > end || obj->isFloating() ||
173 (obj->isPositioned() && !obj->style()->isOriginalDisplayInlineType() && !obj->container()->isRenderInline()))
176 LineMidpointState& lineMidpointState = resolver.midpointState();
177 bool haveNextMidpoint = (lineMidpointState.currentMidpoint < lineMidpointState.numMidpoints);
178 InlineIterator nextMidpoint;
179 if (haveNextMidpoint)
180 nextMidpoint = lineMidpointState.midpoints[lineMidpointState.currentMidpoint];
181 if (lineMidpointState.betweenMidpoints) {
182 if (!(haveNextMidpoint && nextMidpoint.m_obj == obj))
184 // This is a new start point. Stop ignoring objects and
186 lineMidpointState.betweenMidpoints = false;
187 start = nextMidpoint.m_pos;
188 lineMidpointState.currentMidpoint++;
190 return appendRunsForObject(runs, start, end, obj, resolver);
192 if (!haveNextMidpoint || (obj != nextMidpoint.m_obj)) {
193 runs.addRun(createRun(start, end, obj, resolver));
197 // An end midpoint has been encountered within our object. We
198 // need to go ahead and append a run with our endpoint.
199 if (static_cast<int>(nextMidpoint.m_pos + 1) <= end) {
200 lineMidpointState.betweenMidpoints = true;
201 lineMidpointState.currentMidpoint++;
202 if (nextMidpoint.m_pos != UINT_MAX) { // UINT_MAX means stop at the object and don't include any of it.
203 if (static_cast<int>(nextMidpoint.m_pos + 1) > start)
204 runs.addRun(createRun(start, nextMidpoint.m_pos + 1, obj, resolver));
205 return appendRunsForObject(runs, nextMidpoint.m_pos + 1, end, obj, resolver);
208 runs.addRun(createRun(start, end, obj, resolver));
212 static inline InlineBox* createInlineBoxForRenderer(RenderObject* obj, bool isRootLineBox, bool isOnlyRun = false)
215 return toRenderBlock(obj)->createAndAppendRootInlineBox();
218 InlineTextBox* textBox = toRenderText(obj)->createInlineTextBox();
219 // We only treat a box as text for a <br> if we are on a line by ourself or in strict mode
220 // (Note the use of strict mode. In "almost strict" mode, we don't treat the box for <br> as text.)
222 textBox->setIsText(isOnlyRun || obj->document()->inNoQuirksMode());
227 return toRenderBox(obj)->createInlineBox();
229 return toRenderInline(obj)->createAndAppendInlineFlowBox();
232 static inline void dirtyLineBoxesForRenderer(RenderObject* o, bool fullLayout)
235 if (o->preferredLogicalWidthsDirty() && (o->isCounter() || o->isQuote()))
236 toRenderText(o)->computePreferredLogicalWidths(0); // FIXME: Counters depend on this hack. No clue why. Should be investigated and removed.
237 toRenderText(o)->dirtyLineBoxes(fullLayout);
239 toRenderInline(o)->dirtyLineBoxes(fullLayout);
242 static bool parentIsConstructedOrHaveNext(InlineFlowBox* parentBox)
245 if (parentBox->isConstructed() || parentBox->nextOnLine())
247 parentBox = parentBox->parent();
252 InlineFlowBox* RenderBlock::createLineBoxes(RenderObject* obj, const LineInfo& lineInfo, InlineBox* childBox)
254 // See if we have an unconstructed line box for this object that is also
255 // the last item on the line.
256 unsigned lineDepth = 1;
257 InlineFlowBox* parentBox = 0;
258 InlineFlowBox* result = 0;
259 bool hasDefaultLineBoxContain = style()->lineBoxContain() == RenderStyle::initialLineBoxContain();
261 ASSERT(obj->isRenderInline() || obj == this);
263 RenderInline* inlineFlow = (obj != this) ? toRenderInline(obj) : 0;
265 // Get the last box we made for this render object.
266 parentBox = inlineFlow ? inlineFlow->lastLineBox() : toRenderBlock(obj)->lastLineBox();
268 // If this box or its ancestor is constructed then it is from a previous line, and we need
269 // to make a new box for our line. If this box or its ancestor is unconstructed but it has
270 // something following it on the line, then we know we have to make a new box
271 // as well. In this situation our inline has actually been split in two on
272 // the same line (this can happen with very fancy language mixtures).
273 bool constructedNewBox = false;
274 bool allowedToConstructNewBox = !hasDefaultLineBoxContain || !inlineFlow || inlineFlow->alwaysCreateLineBoxes();
275 bool canUseExistingParentBox = parentBox && !parentIsConstructedOrHaveNext(parentBox);
276 if (allowedToConstructNewBox && !canUseExistingParentBox) {
277 // We need to make a new box for this render object. Once
278 // made, we need to place it at the end of the current line.
279 InlineBox* newBox = createInlineBoxForRenderer(obj, obj == this);
280 ASSERT(newBox->isInlineFlowBox());
281 parentBox = toInlineFlowBox(newBox);
282 parentBox->setFirstLineStyleBit(lineInfo.isFirstLine());
283 parentBox->setIsHorizontal(isHorizontalWritingMode());
284 if (!hasDefaultLineBoxContain)
285 parentBox->clearDescendantsHaveSameLineHeightAndBaseline();
286 constructedNewBox = true;
289 if (constructedNewBox || canUseExistingParentBox) {
293 // If we have hit the block itself, then |box| represents the root
294 // inline box for the line, and it doesn't have to be appended to any parent
297 parentBox->addToLine(childBox);
299 if (!constructedNewBox || obj == this)
302 childBox = parentBox;
305 // If we've exceeded our line depth, then jump straight to the root and skip all the remaining
306 // intermediate inline flows.
307 obj = (++lineDepth >= cMaxLineDepth) ? this : obj->parent();
314 static bool reachedEndOfTextRenderer(const BidiRunList<BidiRun>& bidiRuns)
316 BidiRun* run = bidiRuns.logicallyLastRun();
319 unsigned int pos = run->stop();
320 RenderObject* r = run->m_object;
321 if (!r->isText() || r->isBR())
323 RenderText* renderText = toRenderText(r);
324 if (pos >= renderText->textLength())
327 while (isASCIISpace(renderText->characters()[pos])) {
329 if (pos >= renderText->textLength())
335 RootInlineBox* RenderBlock::constructLine(BidiRunList<BidiRun>& bidiRuns, const LineInfo& lineInfo)
337 ASSERT(bidiRuns.firstRun());
339 bool rootHasSelectedChildren = false;
340 InlineFlowBox* parentBox = 0;
341 for (BidiRun* r = bidiRuns.firstRun(); r; r = r->next()) {
342 // Create a box for our object.
343 bool isOnlyRun = (bidiRuns.runCount() == 1);
344 if (bidiRuns.runCount() == 2 && !r->m_object->isListMarker())
345 isOnlyRun = (!style()->isLeftToRightDirection() ? bidiRuns.lastRun() : bidiRuns.firstRun())->m_object->isListMarker();
347 InlineBox* box = createInlineBoxForRenderer(r->m_object, false, isOnlyRun);
354 if (!rootHasSelectedChildren && box->renderer()->selectionState() != RenderObject::SelectionNone)
355 rootHasSelectedChildren = true;
357 // If we have no parent box yet, or if the run is not simply a sibling,
358 // then we need to construct inline boxes as necessary to properly enclose the
360 if (!parentBox || parentBox->renderer() != r->m_object->parent())
361 // Create new inline boxes all the way back to the appropriate insertion point.
362 parentBox = createLineBoxes(r->m_object->parent(), lineInfo, box);
364 // Append the inline box to this line.
365 parentBox->addToLine(box);
368 bool visuallyOrdered = r->m_object->style()->rtlOrdering() == VisualOrder;
369 box->setBidiLevel(r->level());
371 if (box->isInlineTextBox()) {
372 InlineTextBox* text = toInlineTextBox(box);
373 text->setStart(r->m_start);
374 text->setLen(r->m_stop - r->m_start);
375 text->m_dirOverride = r->dirOverride(visuallyOrdered);
377 text->setHasHyphen(true);
381 // We should have a root inline box. It should be unconstructed and
382 // be the last continuation of our line list.
383 ASSERT(lastLineBox() && !lastLineBox()->isConstructed());
385 // Set the m_selectedChildren flag on the root inline box if one of the leaf inline box
386 // from the bidi runs walk above has a selection state.
387 if (rootHasSelectedChildren)
388 lastLineBox()->root()->setHasSelectedChildren(true);
390 // Set bits on our inline flow boxes that indicate which sides should
391 // paint borders/margins/padding. This knowledge will ultimately be used when
392 // we determine the horizontal positions and widths of all the inline boxes on
394 bool isLogicallyLastRunWrapped = bidiRuns.logicallyLastRun()->m_object && bidiRuns.logicallyLastRun()->m_object->isText() ? !reachedEndOfTextRenderer(bidiRuns) : true;
395 lastLineBox()->determineSpacingForFlowBoxes(lineInfo.isLastLine(), isLogicallyLastRunWrapped, bidiRuns.logicallyLastRun()->m_object);
397 // Now mark the line boxes as being constructed.
398 lastLineBox()->setConstructed();
400 // Return the last line.
401 return lastRootBox();
404 ETextAlign RenderBlock::textAlignmentForLine(bool endsWithSoftBreak) const
406 ETextAlign alignment = style()->textAlign();
407 if (!endsWithSoftBreak && alignment == JUSTIFY)
413 static void updateLogicalWidthForLeftAlignedBlock(bool isLeftToRightDirection, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float availableLogicalWidth)
415 // The direction of the block should determine what happens with wide lines.
416 // In particular with RTL blocks, wide lines should still spill out to the left.
417 if (isLeftToRightDirection) {
418 if (totalLogicalWidth > availableLogicalWidth && trailingSpaceRun)
419 trailingSpaceRun->m_box->setLogicalWidth(max<float>(0, trailingSpaceRun->m_box->logicalWidth() - totalLogicalWidth + availableLogicalWidth));
423 if (trailingSpaceRun)
424 trailingSpaceRun->m_box->setLogicalWidth(0);
425 else if (totalLogicalWidth > availableLogicalWidth)
426 logicalLeft -= (totalLogicalWidth - availableLogicalWidth);
429 static void updateLogicalWidthForRightAlignedBlock(bool isLeftToRightDirection, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float availableLogicalWidth)
431 // Wide lines spill out of the block based off direction.
432 // So even if text-align is right, if direction is LTR, wide lines should overflow out of the right
433 // side of the block.
434 if (isLeftToRightDirection) {
435 if (trailingSpaceRun) {
436 totalLogicalWidth -= trailingSpaceRun->m_box->logicalWidth();
437 trailingSpaceRun->m_box->setLogicalWidth(0);
439 if (totalLogicalWidth < availableLogicalWidth)
440 logicalLeft += availableLogicalWidth - totalLogicalWidth;
444 if (totalLogicalWidth > availableLogicalWidth && trailingSpaceRun) {
445 trailingSpaceRun->m_box->setLogicalWidth(max<float>(0, trailingSpaceRun->m_box->logicalWidth() - totalLogicalWidth + availableLogicalWidth));
446 totalLogicalWidth -= trailingSpaceRun->m_box->logicalWidth();
448 logicalLeft += availableLogicalWidth - totalLogicalWidth;
451 static void updateLogicalWidthForCenterAlignedBlock(bool isLeftToRightDirection, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float availableLogicalWidth)
453 float trailingSpaceWidth = 0;
454 if (trailingSpaceRun) {
455 totalLogicalWidth -= trailingSpaceRun->m_box->logicalWidth();
456 trailingSpaceWidth = min(trailingSpaceRun->m_box->logicalWidth(), (availableLogicalWidth - totalLogicalWidth + 1) / 2);
457 trailingSpaceRun->m_box->setLogicalWidth(max<float>(0, trailingSpaceWidth));
459 if (isLeftToRightDirection)
460 logicalLeft += max<float>((availableLogicalWidth - totalLogicalWidth) / 2, 0);
462 logicalLeft += totalLogicalWidth > availableLogicalWidth ? (availableLogicalWidth - totalLogicalWidth) : (availableLogicalWidth - totalLogicalWidth) / 2 - trailingSpaceWidth;
465 void RenderBlock::setMarginsForRubyRun(BidiRun* run, RenderRubyRun* renderer, RenderObject* previousObject, const LineInfo& lineInfo)
469 RenderObject* nextObject = 0;
470 for (BidiRun* runWithNextObject = run->next(); runWithNextObject; runWithNextObject = runWithNextObject->next()) {
471 if (!runWithNextObject->m_object->isPositioned() && !runWithNextObject->m_box->isLineBreak()) {
472 nextObject = runWithNextObject->m_object;
476 renderer->getOverhang(lineInfo.isFirstLine(), renderer->style()->isLeftToRightDirection() ? previousObject : nextObject, renderer->style()->isLeftToRightDirection() ? nextObject : previousObject, startOverhang, endOverhang);
477 setMarginStartForChild(renderer, -startOverhang);
478 setMarginEndForChild(renderer, -endOverhang);
481 static inline float measureHyphenWidth(RenderText* renderer, const Font& font)
483 RenderStyle* style = renderer->style();
484 return font.width(RenderBlock::constructTextRun(renderer, font, style->hyphenString().string(), style));
487 static inline void setLogicalWidthForTextRun(RootInlineBox* lineBox, BidiRun* run, RenderText* renderer, float xPos, const LineInfo& lineInfo,
488 GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache)
490 HashSet<const SimpleFontData*> fallbackFonts;
491 GlyphOverflow glyphOverflow;
493 // Always compute glyph overflow if the block's line-box-contain value is "glyphs".
494 if (lineBox->fitsToGlyphs()) {
495 // If we don't stick out of the root line's font box, then don't bother computing our glyph overflow. This optimization
496 // will keep us from computing glyph bounds in nearly all cases.
497 bool includeRootLine = lineBox->includesRootLineBoxFontOrLeading();
498 int baselineShift = lineBox->verticalPositionForBox(run->m_box, verticalPositionCache);
499 int rootDescent = includeRootLine ? lineBox->renderer()->style(lineInfo.isFirstLine())->font().fontMetrics().descent() : 0;
500 int rootAscent = includeRootLine ? lineBox->renderer()->style(lineInfo.isFirstLine())->font().fontMetrics().ascent() : 0;
501 int boxAscent = renderer->style(lineInfo.isFirstLine())->font().fontMetrics().ascent() - baselineShift;
502 int boxDescent = renderer->style(lineInfo.isFirstLine())->font().fontMetrics().descent() + baselineShift;
503 if (boxAscent > rootDescent || boxDescent > rootAscent)
504 glyphOverflow.computeBounds = true;
508 if (toInlineTextBox(run->m_box)->hasHyphen()) {
509 const Font& font = renderer->style(lineInfo.isFirstLine())->font();
510 hyphenWidth = measureHyphenWidth(renderer, font);
512 run->m_box->setLogicalWidth(renderer->width(run->m_start, run->m_stop - run->m_start, xPos, lineInfo.isFirstLine(), &fallbackFonts, &glyphOverflow) + hyphenWidth);
513 if (!fallbackFonts.isEmpty()) {
514 ASSERT(run->m_box->isText());
515 GlyphOverflowAndFallbackFontsMap::iterator it = textBoxDataMap.add(toInlineTextBox(run->m_box), make_pair(Vector<const SimpleFontData*>(), GlyphOverflow())).first;
516 ASSERT(it->second.first.isEmpty());
517 copyToVector(fallbackFonts, it->second.first);
518 run->m_box->parent()->clearDescendantsHaveSameLineHeightAndBaseline();
520 if ((glyphOverflow.top || glyphOverflow.bottom || glyphOverflow.left || glyphOverflow.right)) {
521 ASSERT(run->m_box->isText());
522 GlyphOverflowAndFallbackFontsMap::iterator it = textBoxDataMap.add(toInlineTextBox(run->m_box), make_pair(Vector<const SimpleFontData*>(), GlyphOverflow())).first;
523 it->second.second = glyphOverflow;
524 run->m_box->clearKnownToHaveNoOverflow();
528 static inline void computeExpansionForJustifiedText(BidiRun* firstRun, BidiRun* trailingSpaceRun, Vector<unsigned, 16>& expansionOpportunities, unsigned expansionOpportunityCount, float& totalLogicalWidth, float availableLogicalWidth)
530 if (!expansionOpportunityCount || availableLogicalWidth <= totalLogicalWidth)
534 for (BidiRun* r = firstRun; r; r = r->next()) {
535 if (!r->m_box || r == trailingSpaceRun)
538 if (r->m_object->isText()) {
539 unsigned opportunitiesInRun = expansionOpportunities[i++];
541 ASSERT(opportunitiesInRun <= expansionOpportunityCount);
543 // Only justify text if whitespace is collapsed.
544 if (r->m_object->style()->collapseWhiteSpace()) {
545 InlineTextBox* textBox = toInlineTextBox(r->m_box);
546 int expansion = (availableLogicalWidth - totalLogicalWidth) * opportunitiesInRun / expansionOpportunityCount;
547 textBox->setExpansion(expansion);
548 totalLogicalWidth += expansion;
550 expansionOpportunityCount -= opportunitiesInRun;
551 if (!expansionOpportunityCount)
557 void RenderBlock::updateLogicalWidthForAlignment(const ETextAlign& textAlign, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float& availableLogicalWidth, int expansionOpportunityCount)
559 // Armed with the total width of the line (without justification),
560 // we now examine our text-align property in order to determine where to position the
561 // objects horizontally. The total width of the line can be increased if we end up
566 updateLogicalWidthForLeftAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
569 adjustInlineDirectionLineBounds(expansionOpportunityCount, logicalLeft, availableLogicalWidth);
570 if (expansionOpportunityCount) {
571 if (trailingSpaceRun) {
572 totalLogicalWidth -= trailingSpaceRun->m_box->logicalWidth();
573 trailingSpaceRun->m_box->setLogicalWidth(0);
579 // for right to left fall through to right aligned
580 if (style()->isLeftToRightDirection()) {
581 if (totalLogicalWidth > availableLogicalWidth && trailingSpaceRun)
582 trailingSpaceRun->m_box->setLogicalWidth(max<float>(0, trailingSpaceRun->m_box->logicalWidth() - totalLogicalWidth + availableLogicalWidth));
587 updateLogicalWidthForRightAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
591 updateLogicalWidthForCenterAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
594 if (style()->isLeftToRightDirection())
595 updateLogicalWidthForLeftAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
597 updateLogicalWidthForRightAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
600 if (style()->isLeftToRightDirection())
601 updateLogicalWidthForRightAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
603 updateLogicalWidthForLeftAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
608 void RenderBlock::computeInlineDirectionPositionsForLine(RootInlineBox* lineBox, const LineInfo& lineInfo, BidiRun* firstRun, BidiRun* trailingSpaceRun, bool reachedEnd,
609 GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache)
611 ETextAlign textAlign = textAlignmentForLine(!reachedEnd && !lineBox->endsWithBreak());
612 float logicalLeft = logicalLeftOffsetForLine(logicalHeight(), lineInfo.isFirstLine());
613 float availableLogicalWidth = logicalRightOffsetForLine(logicalHeight(), lineInfo.isFirstLine()) - logicalLeft;
615 bool needsWordSpacing = false;
616 float totalLogicalWidth = lineBox->getFlowSpacingLogicalWidth();
617 unsigned expansionOpportunityCount = 0;
618 bool isAfterExpansion = true;
619 Vector<unsigned, 16> expansionOpportunities;
620 RenderObject* previousObject = 0;
622 for (BidiRun* r = firstRun; r; r = r->next()) {
623 if (!r->m_box || r->m_object->isPositioned() || r->m_box->isLineBreak())
624 continue; // Positioned objects are only participating to figure out their
625 // correct static x position. They have no effect on the width.
626 // Similarly, line break boxes have no effect on the width.
627 if (r->m_object->isText()) {
628 RenderText* rt = toRenderText(r->m_object);
629 if (textAlign == JUSTIFY && r != trailingSpaceRun) {
630 if (!isAfterExpansion)
631 toInlineTextBox(r->m_box)->setCanHaveLeadingExpansion(true);
632 unsigned opportunitiesInRun = Font::expansionOpportunityCount(rt->characters() + r->m_start, r->m_stop - r->m_start, r->m_box->direction(), isAfterExpansion);
633 expansionOpportunities.append(opportunitiesInRun);
634 expansionOpportunityCount += opportunitiesInRun;
637 if (int length = rt->textLength()) {
638 if (!r->m_start && needsWordSpacing && isSpaceOrNewline(rt->characters()[r->m_start]))
639 totalLogicalWidth += rt->style(lineInfo.isFirstLine())->font().wordSpacing();
640 needsWordSpacing = !isSpaceOrNewline(rt->characters()[r->m_stop - 1]) && r->m_stop == length;
643 setLogicalWidthForTextRun(lineBox, r, rt, totalLogicalWidth, lineInfo, textBoxDataMap, verticalPositionCache);
645 isAfterExpansion = false;
646 if (!r->m_object->isRenderInline()) {
647 RenderBox* renderBox = toRenderBox(r->m_object);
648 if (renderBox->isRubyRun())
649 setMarginsForRubyRun(r, toRenderRubyRun(renderBox), previousObject, lineInfo);
650 r->m_box->setLogicalWidth(logicalWidthForChild(renderBox));
651 totalLogicalWidth += marginStartForChild(renderBox) + marginEndForChild(renderBox);
655 totalLogicalWidth += r->m_box->logicalWidth();
656 previousObject = r->m_object;
659 if (isAfterExpansion && !expansionOpportunities.isEmpty()) {
660 expansionOpportunities.last()--;
661 expansionOpportunityCount--;
664 updateLogicalWidthForAlignment(textAlign, trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth, expansionOpportunityCount);
666 computeExpansionForJustifiedText(firstRun, trailingSpaceRun, expansionOpportunities, expansionOpportunityCount, totalLogicalWidth, availableLogicalWidth);
668 // The widths of all runs are now known. We can now place every inline box (and
669 // compute accurate widths for the inline flow boxes).
670 needsWordSpacing = false;
671 lineBox->placeBoxesInInlineDirection(logicalLeft, needsWordSpacing, textBoxDataMap);
674 void RenderBlock::computeBlockDirectionPositionsForLine(RootInlineBox* lineBox, BidiRun* firstRun, GlyphOverflowAndFallbackFontsMap& textBoxDataMap,
675 VerticalPositionCache& verticalPositionCache)
677 setLogicalHeight(lineBox->alignBoxesInBlockDirection(logicalHeight(), textBoxDataMap, verticalPositionCache));
679 // Now make sure we place replaced render objects correctly.
680 for (BidiRun* r = firstRun; r; r = r->next()) {
683 continue; // Skip runs with no line boxes.
685 // Align positioned boxes with the top of the line box. This is
686 // a reasonable approximation of an appropriate y position.
687 if (r->m_object->isPositioned())
688 r->m_box->setLogicalTop(logicalHeight());
690 // Position is used to properly position both replaced elements and
691 // to update the static normal flow x/y of positioned elements.
692 if (r->m_object->isText())
693 toRenderText(r->m_object)->positionLineBox(r->m_box);
694 else if (r->m_object->isBox())
695 toRenderBox(r->m_object)->positionLineBox(r->m_box);
697 // Positioned objects and zero-length text nodes destroy their boxes in
698 // position(), which unnecessarily dirties the line.
699 lineBox->markDirty(false);
702 static inline bool isCollapsibleSpace(UChar character, RenderText* renderer)
704 if (character == ' ' || character == '\t' || character == softHyphen)
706 if (character == '\n')
707 return !renderer->style()->preserveNewline();
708 if (character == noBreakSpace)
709 return renderer->style()->nbspMode() == SPACE;
714 static void setStaticPositions(RenderBlock* block, RenderBox* child)
716 // FIXME: The math here is actually not really right. It's a best-guess approximation that
717 // will work for the common cases
718 RenderObject* containerBlock = child->container();
719 int blockHeight = block->logicalHeight();
720 if (containerBlock->isRenderInline()) {
721 // A relative positioned inline encloses us. In this case, we also have to determine our
722 // position as though we were an inline. Set |staticInlinePosition| and |staticBlockPosition| on the relative positioned
723 // inline so that we can obtain the value later.
724 toRenderInline(containerBlock)->layer()->setStaticInlinePosition(block->startAlignedOffsetForLine(child, blockHeight, false));
725 toRenderInline(containerBlock)->layer()->setStaticBlockPosition(blockHeight);
728 if (child->style()->isOriginalDisplayInlineType())
729 child->layer()->setStaticInlinePosition(block->startAlignedOffsetForLine(child, blockHeight, false));
731 child->layer()->setStaticInlinePosition(block->borderAndPaddingStart());
732 child->layer()->setStaticBlockPosition(blockHeight);
735 inline BidiRun* RenderBlock::handleTrailingSpaces(BidiRunList<BidiRun>& bidiRuns, BidiContext* currentContext)
737 if (!bidiRuns.runCount()
738 || !bidiRuns.logicallyLastRun()->m_object->style()->breakOnlyAfterWhiteSpace()
739 || !bidiRuns.logicallyLastRun()->m_object->style()->autoWrap())
742 BidiRun* trailingSpaceRun = bidiRuns.logicallyLastRun();
743 RenderObject* lastObject = trailingSpaceRun->m_object;
744 if (!lastObject->isText())
747 RenderText* lastText = toRenderText(lastObject);
748 const UChar* characters = lastText->characters();
749 int firstSpace = trailingSpaceRun->stop();
750 while (firstSpace > trailingSpaceRun->start()) {
751 UChar current = characters[firstSpace - 1];
752 if (!isCollapsibleSpace(current, lastText))
756 if (firstSpace == trailingSpaceRun->stop())
759 TextDirection direction = style()->direction();
760 bool shouldReorder = trailingSpaceRun != (direction == LTR ? bidiRuns.lastRun() : bidiRuns.firstRun());
761 if (firstSpace != trailingSpaceRun->start()) {
762 BidiContext* baseContext = currentContext;
763 while (BidiContext* parent = baseContext->parent())
764 baseContext = parent;
766 BidiRun* newTrailingRun = new (renderArena()) BidiRun(firstSpace, trailingSpaceRun->m_stop, trailingSpaceRun->m_object, baseContext, OtherNeutral);
767 trailingSpaceRun->m_stop = firstSpace;
768 if (direction == LTR)
769 bidiRuns.addRun(newTrailingRun);
771 bidiRuns.prependRun(newTrailingRun);
772 trailingSpaceRun = newTrailingRun;
773 return trailingSpaceRun;
776 return trailingSpaceRun;
778 if (direction == LTR) {
779 bidiRuns.moveRunToEnd(trailingSpaceRun);
780 trailingSpaceRun->m_level = 0;
782 bidiRuns.moveRunToBeginning(trailingSpaceRun);
783 trailingSpaceRun->m_level = 1;
785 return trailingSpaceRun;
788 void RenderBlock::appendFloatingObjectToLastLine(FloatingObject* floatingObject)
790 ASSERT(!floatingObject->m_originatingLine);
791 floatingObject->m_originatingLine = lastRootBox();
792 lastRootBox()->appendFloat(floatingObject->renderer());
795 // FIXME: This should be a BidiStatus constructor or create method.
796 static inline BidiStatus statusWithDirection(TextDirection textDirection)
798 WTF::Unicode::Direction direction = textDirection == LTR ? LeftToRight : RightToLeft;
799 RefPtr<BidiContext> context = BidiContext::create(textDirection == LTR ? 0 : 1, direction, false, FromStyleOrDOM);
801 // This copies BidiStatus and may churn the ref on BidiContext. I doubt it matters.
802 return BidiStatus(direction, direction, direction, context.release());
805 // FIXME: BidiResolver should have this logic.
806 static inline void constructBidiRuns(InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfLine, VisualDirectionOverride override, bool previousLineBrokeCleanly)
808 // FIXME: We should pass a BidiRunList into createBidiRunsForLine instead
809 // of the resolver owning the runs.
810 ASSERT(&topResolver.runs() == &bidiRuns);
811 topResolver.createBidiRunsForLine(endOfLine, override, previousLineBrokeCleanly);
813 while (!topResolver.isolatedRuns().isEmpty()) {
814 // It does not matter which order we resolve the runs as long as we resolve them all.
815 BidiRun* isolatedRun = topResolver.isolatedRuns().last();
816 topResolver.isolatedRuns().removeLast();
818 // Only inlines make sense with unicode-bidi: isolate (blocks are already isolated).
819 RenderInline* isolatedSpan = toRenderInline(isolatedRun->object());
820 InlineBidiResolver isolatedResolver;
821 isolatedResolver.setStatus(statusWithDirection(isolatedSpan->style()->direction()));
823 // FIXME: The fact that we have to construct an Iterator here
824 // currently prevents this code from moving into BidiResolver.
825 RenderObject* startObj = bidiFirstSkippingEmptyInlines(isolatedSpan, &isolatedResolver);
826 isolatedResolver.setPosition(InlineIterator(isolatedSpan, startObj, 0));
828 // FIXME: isolatedEnd should probably equal end or the last char in isolatedSpan.
829 InlineIterator isolatedEnd = endOfLine;
830 // FIXME: What should end and previousLineBrokeCleanly be?
831 // rniwa says previousLineBrokeCleanly is just a WinIE hack and could always be false here?
832 isolatedResolver.createBidiRunsForLine(isolatedEnd, NoVisualOverride, previousLineBrokeCleanly);
833 // Note that we do not delete the runs from the resolver.
834 bidiRuns.replaceRunWithRuns(isolatedRun, isolatedResolver.runs());
836 // If we encountered any nested isolate runs, just move them
837 // to the top resolver's list for later processing.
838 if (!isolatedResolver.isolatedRuns().isEmpty()) {
839 topResolver.isolatedRuns().append(isolatedResolver.isolatedRuns());
840 isolatedResolver.isolatedRuns().clear();
845 // This function constructs line boxes for all of the text runs in the resolver and computes their position.
846 RootInlineBox* RenderBlock::createLineBoxesFromBidiRuns(BidiRunList<BidiRun>& bidiRuns, const InlineIterator& end, LineInfo& lineInfo, VerticalPositionCache& verticalPositionCache, BidiRun* trailingSpaceRun)
848 if (!bidiRuns.runCount())
851 // FIXME: Why is this only done when we had runs?
852 lineInfo.setLastLine(!end.m_obj);
854 RootInlineBox* lineBox = constructLine(bidiRuns, lineInfo);
858 lineBox->setEndsWithBreak(lineInfo.previousLineBrokeCleanly());
861 bool isSVGRootInlineBox = lineBox->isSVGRootInlineBox();
863 bool isSVGRootInlineBox = false;
866 GlyphOverflowAndFallbackFontsMap textBoxDataMap;
868 // Now we position all of our text runs horizontally.
869 if (!isSVGRootInlineBox)
870 computeInlineDirectionPositionsForLine(lineBox, lineInfo, bidiRuns.firstRun(), trailingSpaceRun, end.atEnd(), textBoxDataMap, verticalPositionCache);
872 // Now position our text runs vertically.
873 computeBlockDirectionPositionsForLine(lineBox, bidiRuns.firstRun(), textBoxDataMap, verticalPositionCache);
876 // SVG text layout code computes vertical & horizontal positions on its own.
877 // Note that we still need to execute computeVerticalPositionsForLine() as
878 // it calls InlineTextBox::positionLineBox(), which tracks whether the box
879 // contains reversed text or not. If we wouldn't do that editing and thus
880 // text selection in RTL boxes would not work as expected.
881 if (isSVGRootInlineBox) {
883 static_cast<SVGRootInlineBox*>(lineBox)->computePerCharacterLayoutInformation();
887 // Compute our overflow now.
888 lineBox->computeOverflow(lineBox->lineTop(), lineBox->lineBottom(), textBoxDataMap);
891 // Highlight acts as an overflow inflation.
892 if (style()->highlight() != nullAtom)
893 lineBox->addHighlightOverflow();
898 // Like LayoutState for layout(), LineLayoutState keeps track of global information
899 // during an entire linebox tree layout pass (aka layoutInlineChildren).
900 class LineLayoutState {
902 LineLayoutState(bool fullLayout, int& repaintLogicalTop, int& repaintLogicalBottom)
906 , m_endLineLogicalTop(0)
907 , m_endLineMatched(false)
908 , m_checkForFloatsFromLastLine(false)
909 , m_isFullLayout(fullLayout)
910 , m_repaintLogicalTop(repaintLogicalTop)
911 , m_repaintLogicalBottom(repaintLogicalBottom)
912 , m_usesRepaintBounds(false)
915 void markForFullLayout() { m_isFullLayout = true; }
916 bool isFullLayout() const { return m_isFullLayout; }
918 bool usesRepaintBounds() const { return m_usesRepaintBounds; }
920 void setRepaintRange(int logicalHeight)
922 m_usesRepaintBounds = true;
923 m_repaintLogicalTop = m_repaintLogicalBottom = logicalHeight;
926 void updateRepaintRangeFromBox(RootInlineBox* box, int paginationDelta = 0)
928 m_usesRepaintBounds = true;
929 m_repaintLogicalTop = min(m_repaintLogicalTop, box->logicalTopVisualOverflow() + min(paginationDelta, 0));
930 m_repaintLogicalBottom = max(m_repaintLogicalBottom, box->logicalBottomVisualOverflow() + max(paginationDelta, 0));
933 bool endLineMatched() const { return m_endLineMatched; }
934 void setEndLineMatched(bool endLineMatched) { m_endLineMatched = endLineMatched; }
936 bool checkForFloatsFromLastLine() const { return m_checkForFloatsFromLastLine; }
937 void setCheckForFloatsFromLastLine(bool check) { m_checkForFloatsFromLastLine = check; }
939 LineInfo& lineInfo() { return m_lineInfo; }
940 const LineInfo& lineInfo() const { return m_lineInfo; }
942 int endLineLogicalTop() const { return m_endLineLogicalTop; }
943 void setEndLineLogicalTop(int logicalTop) { m_endLineLogicalTop = logicalTop; }
945 RootInlineBox* endLine() const { return m_endLine; }
946 void setEndLine(RootInlineBox* line) { m_endLine = line; }
948 RenderBlock::FloatingObject* lastFloat() const { return m_lastFloat; }
949 void setLastFloat(RenderBlock::FloatingObject* lastFloat) { m_lastFloat = lastFloat; }
951 Vector<RenderBlock::FloatWithRect>& floats() { return m_floats; }
953 unsigned floatIndex() const { return m_floatIndex; }
954 void setFloatIndex(unsigned floatIndex) { m_floatIndex = floatIndex; }
957 Vector<RenderBlock::FloatWithRect> m_floats;
958 RenderBlock::FloatingObject* m_lastFloat;
959 RootInlineBox* m_endLine;
961 unsigned m_floatIndex;
962 int m_endLineLogicalTop;
963 bool m_endLineMatched;
964 bool m_checkForFloatsFromLastLine;
968 // FIXME: Should this be a range object instead of two ints?
969 int& m_repaintLogicalTop;
970 int& m_repaintLogicalBottom;
972 bool m_usesRepaintBounds;
975 static void deleteLineRange(LineLayoutState& layoutState, RenderArena* arena, RootInlineBox* startLine, RootInlineBox* stopLine = 0)
977 RootInlineBox* boxToDelete = startLine;
978 while (boxToDelete && boxToDelete != stopLine) {
979 layoutState.updateRepaintRangeFromBox(boxToDelete);
980 // Note: deleteLineRange(renderArena(), firstRootBox()) is not identical to deleteLineBoxTree().
981 // deleteLineBoxTree uses nextLineBox() instead of nextRootBox() when traversing.
982 RootInlineBox* next = boxToDelete->nextRootBox();
983 boxToDelete->deleteLine(arena);
988 void RenderBlock::layoutRunsAndFloats(LineLayoutState& layoutState, bool hasInlineChild)
990 // We want to skip ahead to the first dirty line
991 InlineBidiResolver resolver;
992 RootInlineBox* startLine = determineStartPosition(layoutState, resolver);
994 unsigned consecutiveHyphenatedLines = 0;
996 for (RootInlineBox* line = startLine->prevRootBox(); line && line->isHyphenated(); line = line->prevRootBox())
997 consecutiveHyphenatedLines++;
1000 // FIXME: This would make more sense outside of this function, but since
1001 // determineStartPosition can change the fullLayout flag we have to do this here. Failure to call
1002 // determineStartPosition first will break fast/repaint/line-flow-with-floats-9.html.
1003 if (layoutState.isFullLayout() && hasInlineChild && !selfNeedsLayout()) {
1004 setNeedsLayout(true, false); // Mark ourselves as needing a full layout. This way we'll repaint like
1005 // we're supposed to.
1006 RenderView* v = view();
1007 if (v && !v->doingFullRepaint() && hasLayer()) {
1008 // Because we waited until we were already inside layout to discover
1009 // that the block really needed a full layout, we missed our chance to repaint the layer
1010 // before layout started. Luckily the layer has cached the repaint rect for its original
1011 // position and size, and so we can use that to make a repaint happen now.
1012 repaintUsingContainer(containerForRepaint(), layer()->repaintRect());
1016 if (m_floatingObjects && !m_floatingObjects->set().isEmpty())
1017 layoutState.setLastFloat(m_floatingObjects->set().last());
1019 // We also find the first clean line and extract these lines. We will add them back
1020 // if we determine that we're able to synchronize after handling all our dirty lines.
1021 InlineIterator cleanLineStart;
1022 BidiStatus cleanLineBidiStatus;
1023 if (!layoutState.isFullLayout() && startLine)
1024 determineEndPosition(layoutState, startLine, cleanLineStart, cleanLineBidiStatus);
1027 if (!layoutState.usesRepaintBounds())
1028 layoutState.setRepaintRange(logicalHeight());
1029 deleteLineRange(layoutState, renderArena(), startLine);
1032 if (!layoutState.isFullLayout() && lastRootBox() && lastRootBox()->endsWithBreak()) {
1033 // If the last line before the start line ends with a line break that clear floats,
1034 // adjust the height accordingly.
1035 // A line break can be either the first or the last object on a line, depending on its direction.
1036 if (InlineBox* lastLeafChild = lastRootBox()->lastLeafChild()) {
1037 RenderObject* lastObject = lastLeafChild->renderer();
1038 if (!lastObject->isBR())
1039 lastObject = lastRootBox()->firstLeafChild()->renderer();
1040 if (lastObject->isBR()) {
1041 EClear clear = lastObject->style()->clear();
1048 layoutRunsAndFloatsInRange(layoutState, resolver, cleanLineStart, cleanLineBidiStatus, consecutiveHyphenatedLines);
1049 linkToEndLineIfNeeded(layoutState);
1050 repaintDirtyFloats(layoutState.floats());
1053 void RenderBlock::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, InlineBidiResolver& resolver, const InlineIterator& cleanLineStart, const BidiStatus& cleanLineBidiStatus, unsigned consecutiveHyphenatedLines)
1055 bool paginated = view()->layoutState() && view()->layoutState()->isPaginated();
1056 LineMidpointState& lineMidpointState = resolver.midpointState();
1057 InlineIterator end = resolver.position();
1058 bool checkForEndLineMatch = layoutState.endLine();
1059 LineBreakIteratorInfo lineBreakIteratorInfo;
1060 VerticalPositionCache verticalPositionCache;
1062 LineBreaker lineBreaker(this);
1064 while (!end.atEnd()) {
1065 // FIXME: Is this check necessary before the first iteration or can it be moved to the end?
1066 if (checkForEndLineMatch) {
1067 layoutState.setEndLineMatched(matchedEndLine(layoutState, resolver, cleanLineStart, cleanLineBidiStatus));
1068 if (layoutState.endLineMatched())
1072 lineMidpointState.reset();
1074 layoutState.lineInfo().setEmpty(true);
1076 InlineIterator oldEnd = end;
1077 bool isNewUBAParagraph = layoutState.lineInfo().previousLineBrokeCleanly();
1078 FloatingObject* lastFloatFromPreviousLine = (m_floatingObjects && !m_floatingObjects->set().isEmpty()) ? m_floatingObjects->set().last() : 0;
1079 end = lineBreaker.nextLineBreak(resolver, layoutState.lineInfo(), lineBreakIteratorInfo, lastFloatFromPreviousLine, consecutiveHyphenatedLines);
1080 if (resolver.position().atEnd()) {
1081 // FIXME: We shouldn't be creating any runs in findNextLineBreak to begin with!
1082 // Once BidiRunList is separated from BidiResolver this will not be needed.
1083 resolver.runs().deleteRuns();
1084 resolver.markCurrentRunEmpty(); // FIXME: This can probably be replaced by an ASSERT (or just removed).
1085 layoutState.setCheckForFloatsFromLastLine(true);
1088 ASSERT(end != resolver.position());
1090 // This is a short-cut for empty lines.
1091 if (layoutState.lineInfo().isEmpty()) {
1093 lastRootBox()->setLineBreakInfo(end.m_obj, end.m_pos, resolver.status());
1095 VisualDirectionOverride override = (style()->rtlOrdering() == VisualOrder ? (style()->direction() == LTR ? VisualLeftToRightOverride : VisualRightToLeftOverride) : NoVisualOverride);
1097 if (isNewUBAParagraph && style()->unicodeBidi() == Plaintext && !resolver.context()->parent()) {
1098 TextDirection direction = style()->direction();
1099 determineParagraphDirection(direction, resolver.position());
1100 resolver.setStatus(BidiStatus(direction, style()->unicodeBidi() == Override));
1102 // FIXME: This ownership is reversed. We should own the BidiRunList and pass it to createBidiRunsForLine.
1103 BidiRunList<BidiRun>& bidiRuns = resolver.runs();
1104 constructBidiRuns(resolver, bidiRuns, end, override, layoutState.lineInfo().previousLineBrokeCleanly());
1105 ASSERT(resolver.position() == end);
1107 BidiRun* trailingSpaceRun = !layoutState.lineInfo().previousLineBrokeCleanly() ? handleTrailingSpaces(bidiRuns, resolver.context()) : 0;
1109 if (bidiRuns.runCount() && lineBreaker.lineWasHyphenated()) {
1110 bidiRuns.logicallyLastRun()->m_hasHyphen = true;
1111 consecutiveHyphenatedLines++;
1113 consecutiveHyphenatedLines = 0;
1115 // Now that the runs have been ordered, we create the line boxes.
1116 // At the same time we figure out where border/padding/margin should be applied for
1117 // inline flow boxes.
1119 int oldLogicalHeight = logicalHeight();
1120 RootInlineBox* lineBox = createLineBoxesFromBidiRuns(bidiRuns, end, layoutState.lineInfo(), verticalPositionCache, trailingSpaceRun);
1122 bidiRuns.deleteRuns();
1123 resolver.markCurrentRunEmpty(); // FIXME: This can probably be replaced by an ASSERT (or just removed).
1126 lineBox->setLineBreakInfo(end.m_obj, end.m_pos, resolver.status());
1127 if (layoutState.usesRepaintBounds())
1128 layoutState.updateRepaintRangeFromBox(lineBox);
1132 adjustLinePositionForPagination(lineBox, adjustment);
1134 int oldLineWidth = availableLogicalWidthForLine(oldLogicalHeight, layoutState.lineInfo().isFirstLine());
1135 lineBox->adjustBlockDirectionPosition(adjustment);
1136 if (layoutState.usesRepaintBounds())
1137 layoutState.updateRepaintRangeFromBox(lineBox);
1139 if (availableLogicalWidthForLine(oldLogicalHeight + adjustment, layoutState.lineInfo().isFirstLine()) != oldLineWidth) {
1140 // We have to delete this line, remove all floats that got added, and let line layout re-run.
1141 lineBox->deleteLine(renderArena());
1142 removeFloatingObjectsBelow(lastFloatFromPreviousLine, oldLogicalHeight);
1143 setLogicalHeight(oldLogicalHeight + adjustment);
1144 resolver.setPosition(oldEnd);
1149 setLogicalHeight(lineBox->lineBottomWithLeading());
1154 for (size_t i = 0; i < lineBreaker.positionedObjects().size(); ++i)
1155 setStaticPositions(this, lineBreaker.positionedObjects()[i]);
1157 layoutState.lineInfo().setFirstLine(false);
1158 newLine(lineBreaker.clear());
1161 if (m_floatingObjects && lastRootBox()) {
1162 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1163 FloatingObjectSetIterator it = floatingObjectSet.begin();
1164 FloatingObjectSetIterator end = floatingObjectSet.end();
1165 if (layoutState.lastFloat()) {
1166 FloatingObjectSetIterator lastFloatIterator = floatingObjectSet.find(layoutState.lastFloat());
1167 ASSERT(lastFloatIterator != end);
1168 ++lastFloatIterator;
1169 it = lastFloatIterator;
1171 for (; it != end; ++it) {
1172 FloatingObject* f = *it;
1173 appendFloatingObjectToLastLine(f);
1174 ASSERT(f->m_renderer == layoutState.floats()[layoutState.floatIndex()].object);
1175 // If a float's geometry has changed, give up on syncing with clean lines.
1176 if (layoutState.floats()[layoutState.floatIndex()].rect != f->frameRect())
1177 checkForEndLineMatch = false;
1178 layoutState.setFloatIndex(layoutState.floatIndex() + 1);
1180 layoutState.setLastFloat(!floatingObjectSet.isEmpty() ? floatingObjectSet.last() : 0);
1183 lineMidpointState.reset();
1184 resolver.setPosition(end);
1188 void RenderBlock::linkToEndLineIfNeeded(LineLayoutState& layoutState)
1190 if (layoutState.endLine()) {
1191 if (layoutState.endLineMatched()) {
1192 bool paginated = view()->layoutState() && view()->layoutState()->isPaginated();
1193 // Attach all the remaining lines, and then adjust their y-positions as needed.
1194 int delta = logicalHeight() - layoutState.endLineLogicalTop();
1195 for (RootInlineBox* line = layoutState.endLine(); line; line = line->nextRootBox()) {
1198 delta -= line->paginationStrut();
1199 adjustLinePositionForPagination(line, delta);
1202 layoutState.updateRepaintRangeFromBox(line, delta);
1203 line->adjustBlockDirectionPosition(delta);
1205 if (Vector<RenderBox*>* cleanLineFloats = line->floatsPtr()) {
1206 Vector<RenderBox*>::iterator end = cleanLineFloats->end();
1207 for (Vector<RenderBox*>::iterator f = cleanLineFloats->begin(); f != end; ++f) {
1208 FloatingObject* floatingObject = insertFloatingObject(*f);
1209 ASSERT(!floatingObject->m_originatingLine);
1210 floatingObject->m_originatingLine = line;
1211 setLogicalHeight(logicalTopForChild(*f) - marginBeforeForChild(*f) + delta);
1212 positionNewFloats();
1216 setLogicalHeight(lastRootBox()->lineBottomWithLeading());
1218 // Delete all the remaining lines.
1219 deleteLineRange(layoutState, renderArena(), layoutState.endLine());
1223 if (m_floatingObjects && (layoutState.checkForFloatsFromLastLine() || positionNewFloats()) && lastRootBox()) {
1224 // In case we have a float on the last line, it might not be positioned up to now.
1225 // This has to be done before adding in the bottom border/padding, or the float will
1226 // include the padding incorrectly. -dwh
1227 if (layoutState.checkForFloatsFromLastLine()) {
1228 int bottomVisualOverflow = lastRootBox()->logicalBottomVisualOverflow();
1229 int bottomLayoutOverflow = lastRootBox()->logicalBottomLayoutOverflow();
1230 TrailingFloatsRootInlineBox* trailingFloatsLineBox = new (renderArena()) TrailingFloatsRootInlineBox(this);
1231 m_lineBoxes.appendLineBox(trailingFloatsLineBox);
1232 trailingFloatsLineBox->setConstructed();
1233 GlyphOverflowAndFallbackFontsMap textBoxDataMap;
1234 VerticalPositionCache verticalPositionCache;
1235 int blockLogicalHeight = logicalHeight();
1236 trailingFloatsLineBox->alignBoxesInBlockDirection(blockLogicalHeight, textBoxDataMap, verticalPositionCache);
1237 trailingFloatsLineBox->setLineTopBottomPositions(blockLogicalHeight, blockLogicalHeight, blockLogicalHeight, blockLogicalHeight);
1238 IntRect logicalLayoutOverflow(0, blockLogicalHeight, 1, bottomLayoutOverflow - blockLogicalHeight);
1239 IntRect logicalVisualOverflow(0, blockLogicalHeight, 1, bottomVisualOverflow - blockLogicalHeight);
1240 trailingFloatsLineBox->setOverflowFromLogicalRects(logicalLayoutOverflow, logicalVisualOverflow, trailingFloatsLineBox->lineTop(), trailingFloatsLineBox->lineBottom());
1243 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1244 FloatingObjectSetIterator it = floatingObjectSet.begin();
1245 FloatingObjectSetIterator end = floatingObjectSet.end();
1246 if (layoutState.lastFloat()) {
1247 FloatingObjectSetIterator lastFloatIterator = floatingObjectSet.find(layoutState.lastFloat());
1248 ASSERT(lastFloatIterator != end);
1249 ++lastFloatIterator;
1250 it = lastFloatIterator;
1252 for (; it != end; ++it)
1253 appendFloatingObjectToLastLine(*it);
1254 layoutState.setLastFloat(!floatingObjectSet.isEmpty() ? floatingObjectSet.last() : 0);
1258 void RenderBlock::repaintDirtyFloats(Vector<FloatWithRect>& floats)
1260 size_t floatCount = floats.size();
1261 // Floats that did not have layout did not repaint when we laid them out. They would have
1262 // painted by now if they had moved, but if they stayed at (0, 0), they still need to be
1264 for (size_t i = 0; i < floatCount; ++i) {
1265 if (!floats[i].everHadLayout) {
1266 RenderBox* f = floats[i].object;
1267 if (!f->x() && !f->y() && f->checkForRepaintDuringLayout())
1273 void RenderBlock::layoutInlineChildren(bool relayoutChildren, int& repaintLogicalTop, int& repaintLogicalBottom)
1277 setLogicalHeight(borderBefore() + paddingBefore());
1279 // Figure out if we should clear out our line boxes.
1280 // FIXME: Handle resize eventually!
1281 bool isFullLayout = !firstLineBox() || selfNeedsLayout() || relayoutChildren;
1282 LineLayoutState layoutState(isFullLayout, repaintLogicalTop, repaintLogicalBottom);
1285 lineBoxes()->deleteLineBoxes(renderArena());
1287 // Text truncation only kicks in if your overflow isn't visible and your text-overflow-mode isn't
1289 // FIXME: CSS3 says that descendants that are clipped must also know how to truncate. This is insanely
1290 // difficult to figure out (especially in the middle of doing layout), and is really an esoteric pile of nonsense
1291 // anyway, so we won't worry about following the draft here.
1292 bool hasTextOverflow = style()->textOverflow() && hasOverflowClip();
1294 // Walk all the lines and delete our ellipsis line boxes if they exist.
1295 if (hasTextOverflow)
1296 deleteEllipsisLineBoxes();
1299 // layout replaced elements
1300 bool hasInlineChild = false;
1301 for (InlineWalker walker(this); !walker.atEnd(); walker.advance()) {
1302 RenderObject* o = walker.current();
1303 if (!hasInlineChild && o->isInline())
1304 hasInlineChild = true;
1306 if (o->isReplaced() || o->isFloating() || o->isPositioned()) {
1307 RenderBox* box = toRenderBox(o);
1309 if (relayoutChildren || o->style()->width().isPercent() || o->style()->height().isPercent())
1310 o->setChildNeedsLayout(true, false);
1312 // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
1313 if (relayoutChildren && box->needsPreferredWidthsRecalculation())
1314 o->setPreferredLogicalWidthsDirty(true, false);
1316 if (o->isPositioned())
1317 o->containingBlock()->insertPositionedObject(box);
1318 else if (o->isFloating())
1319 layoutState.floats().append(FloatWithRect(box));
1320 else if (layoutState.isFullLayout() || o->needsLayout()) {
1321 // Replaced elements
1322 toRenderBox(o)->dirtyLineBoxes(layoutState.isFullLayout());
1323 o->layoutIfNeeded();
1325 } else if (o->isText() || (o->isRenderInline() && !walker.atEndOfInline())) {
1327 toRenderInline(o)->updateAlwaysCreateLineBoxes(layoutState.isFullLayout());
1328 if (layoutState.isFullLayout() || o->selfNeedsLayout())
1329 dirtyLineBoxesForRenderer(o, layoutState.isFullLayout());
1330 o->setNeedsLayout(false);
1334 layoutRunsAndFloats(layoutState, hasInlineChild);
1337 // Expand the last line to accommodate Ruby and emphasis marks.
1338 int lastLineAnnotationsAdjustment = 0;
1339 if (lastRootBox()) {
1340 int lowestAllowedPosition = max(lastRootBox()->lineBottom(), logicalHeight() + paddingAfter());
1341 if (!style()->isFlippedLinesWritingMode())
1342 lastLineAnnotationsAdjustment = lastRootBox()->computeUnderAnnotationAdjustment(lowestAllowedPosition);
1344 lastLineAnnotationsAdjustment = lastRootBox()->computeOverAnnotationAdjustment(lowestAllowedPosition);
1347 // Now add in the bottom border/padding.
1348 setLogicalHeight(logicalHeight() + lastLineAnnotationsAdjustment + borderAfter() + paddingAfter() + scrollbarLogicalHeight());
1350 if (!firstLineBox() && hasLineIfEmpty())
1351 setLogicalHeight(logicalHeight() + lineHeight(true, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes));
1353 // See if we have any lines that spill out of our block. If we do, then we will possibly need to
1355 if (hasTextOverflow)
1356 checkLinesForTextOverflow();
1359 void RenderBlock::checkFloatsInCleanLine(RootInlineBox* line, Vector<FloatWithRect>& floats, size_t& floatIndex, bool& encounteredNewFloat, bool& dirtiedByFloat)
1361 Vector<RenderBox*>* cleanLineFloats = line->floatsPtr();
1362 if (!cleanLineFloats)
1365 Vector<RenderBox*>::iterator end = cleanLineFloats->end();
1366 for (Vector<RenderBox*>::iterator it = cleanLineFloats->begin(); it != end; ++it) {
1367 RenderBox* floatingBox = *it;
1368 floatingBox->layoutIfNeeded();
1369 IntSize newSize(floatingBox->width() + floatingBox->marginLeft() + floatingBox->marginRight(), floatingBox->height() + floatingBox->marginTop() + floatingBox->marginBottom());
1370 ASSERT(floatIndex < floats.size());
1371 if (floats[floatIndex].object != floatingBox) {
1372 encounteredNewFloat = true;
1376 if (floats[floatIndex].rect.size() != newSize) {
1377 int floatTop = isHorizontalWritingMode() ? floats[floatIndex].rect.y() : floats[floatIndex].rect.x();
1378 int floatHeight = isHorizontalWritingMode() ? max(floats[floatIndex].rect.height(), newSize.height())
1379 : max(floats[floatIndex].rect.width(), newSize.width());
1380 floatHeight = min(floatHeight, numeric_limits<int>::max() - floatTop);
1382 markLinesDirtyInBlockRange(line->lineBottomWithLeading(), floatTop + floatHeight, line);
1383 floats[floatIndex].rect.setSize(newSize);
1384 dirtiedByFloat = true;
1390 RootInlineBox* RenderBlock::determineStartPosition(LineLayoutState& layoutState, InlineBidiResolver& resolver)
1392 RootInlineBox* curr = 0;
1393 RootInlineBox* last = 0;
1395 // FIXME: This entire float-checking block needs to be broken into a new function.
1396 bool dirtiedByFloat = false;
1397 if (!layoutState.isFullLayout()) {
1398 // Paginate all of the clean lines.
1399 bool paginated = view()->layoutState() && view()->layoutState()->isPaginated();
1400 int paginationDelta = 0;
1401 size_t floatIndex = 0;
1402 for (curr = firstRootBox(); curr && !curr->isDirty(); curr = curr->nextRootBox()) {
1404 paginationDelta -= curr->paginationStrut();
1405 adjustLinePositionForPagination(curr, paginationDelta);
1406 if (paginationDelta) {
1407 if (containsFloats() || !layoutState.floats().isEmpty()) {
1408 // FIXME: Do better eventually. For now if we ever shift because of pagination and floats are present just go to a full layout.
1409 layoutState.markForFullLayout();
1413 layoutState.updateRepaintRangeFromBox(curr, paginationDelta);
1414 curr->adjustBlockDirectionPosition(paginationDelta);
1418 // If a new float has been inserted before this line or before its last known float, just do a full layout.
1419 bool encounteredNewFloat = false;
1420 checkFloatsInCleanLine(curr, layoutState.floats(), floatIndex, encounteredNewFloat, dirtiedByFloat);
1421 if (encounteredNewFloat)
1422 layoutState.markForFullLayout();
1424 if (dirtiedByFloat || layoutState.isFullLayout())
1427 // Check if a new float has been inserted after the last known float.
1428 if (!curr && floatIndex < layoutState.floats().size())
1429 layoutState.markForFullLayout();
1432 if (layoutState.isFullLayout()) {
1433 // FIXME: This should just call deleteLineBoxTree, but that causes
1434 // crashes for fast/repaint tests.
1435 RenderArena* arena = renderArena();
1436 curr = firstRootBox();
1438 // Note: This uses nextRootBox() insted of nextLineBox() like deleteLineBoxTree does.
1439 RootInlineBox* next = curr->nextRootBox();
1440 curr->deleteLine(arena);
1443 ASSERT(!firstLineBox() && !lastLineBox());
1446 // We have a dirty line.
1447 if (RootInlineBox* prevRootBox = curr->prevRootBox()) {
1448 // We have a previous line.
1449 if (!dirtiedByFloat && (!prevRootBox->endsWithBreak() || (prevRootBox->lineBreakObj()->isText() && prevRootBox->lineBreakPos() >= toRenderText(prevRootBox->lineBreakObj())->textLength())))
1450 // The previous line didn't break cleanly or broke at a newline
1451 // that has been deleted, so treat it as dirty too.
1455 // No dirty lines were found.
1456 // If the last line didn't break cleanly, treat it as dirty.
1457 if (lastRootBox() && !lastRootBox()->endsWithBreak())
1458 curr = lastRootBox();
1461 // If we have no dirty lines, then last is just the last root box.
1462 last = curr ? curr->prevRootBox() : lastRootBox();
1465 unsigned numCleanFloats = 0;
1466 if (!layoutState.floats().isEmpty()) {
1467 int savedLogicalHeight = logicalHeight();
1468 // Restore floats from clean lines.
1469 RootInlineBox* line = firstRootBox();
1470 while (line != curr) {
1471 if (Vector<RenderBox*>* cleanLineFloats = line->floatsPtr()) {
1472 Vector<RenderBox*>::iterator end = cleanLineFloats->end();
1473 for (Vector<RenderBox*>::iterator f = cleanLineFloats->begin(); f != end; ++f) {
1474 FloatingObject* floatingObject = insertFloatingObject(*f);
1475 ASSERT(!floatingObject->m_originatingLine);
1476 floatingObject->m_originatingLine = line;
1477 setLogicalHeight(logicalTopForChild(*f) - marginBeforeForChild(*f));
1478 positionNewFloats();
1479 ASSERT(layoutState.floats()[numCleanFloats].object == *f);
1483 line = line->nextRootBox();
1485 setLogicalHeight(savedLogicalHeight);
1487 layoutState.setFloatIndex(numCleanFloats);
1489 layoutState.lineInfo().setFirstLine(!last);
1490 layoutState.lineInfo().setPreviousLineBrokeCleanly(!last || last->endsWithBreak());
1493 setLogicalHeight(last->lineBottomWithLeading());
1494 resolver.setPosition(InlineIterator(this, last->lineBreakObj(), last->lineBreakPos()));
1495 resolver.setStatus(last->lineBreakBidiStatus());
1497 TextDirection direction = style()->direction();
1498 if (style()->unicodeBidi() == Plaintext) {
1499 // FIXME: Why does "unicode-bidi: plaintext" bidiFirstIncludingEmptyInlines when all other line layout code uses bidiFirstSkippingEmptyInlines?
1500 determineParagraphDirection(direction, InlineIterator(this, bidiFirstIncludingEmptyInlines(this), 0));
1502 resolver.setStatus(BidiStatus(direction, style()->unicodeBidi() == Override));
1503 resolver.setPosition(InlineIterator(this, bidiFirstSkippingEmptyInlines(this, &resolver), 0));
1508 void RenderBlock::determineEndPosition(LineLayoutState& layoutState, RootInlineBox* startLine, InlineIterator& cleanLineStart, BidiStatus& cleanLineBidiStatus)
1510 ASSERT(!layoutState.endLine());
1511 size_t floatIndex = layoutState.floatIndex();
1512 RootInlineBox* last = 0;
1513 for (RootInlineBox* curr = startLine->nextRootBox(); curr; curr = curr->nextRootBox()) {
1514 if (!curr->isDirty()) {
1515 bool encounteredNewFloat = false;
1516 bool dirtiedByFloat = false;
1517 checkFloatsInCleanLine(curr, layoutState.floats(), floatIndex, encounteredNewFloat, dirtiedByFloat);
1518 if (encounteredNewFloat)
1521 if (curr->isDirty())
1530 // At this point, |last| is the first line in a run of clean lines that ends with the last line
1533 RootInlineBox* prev = last->prevRootBox();
1534 cleanLineStart = InlineIterator(this, prev->lineBreakObj(), prev->lineBreakPos());
1535 cleanLineBidiStatus = prev->lineBreakBidiStatus();
1536 layoutState.setEndLineLogicalTop(prev->lineBottomWithLeading());
1538 for (RootInlineBox* line = last; line; line = line->nextRootBox())
1539 line->extractLine(); // Disconnect all line boxes from their render objects while preserving
1540 // their connections to one another.
1542 layoutState.setEndLine(last);
1545 bool RenderBlock::matchedEndLine(LineLayoutState& layoutState, const InlineBidiResolver& resolver, const InlineIterator& endLineStart, const BidiStatus& endLineStatus)
1547 if (resolver.position() == endLineStart) {
1548 if (resolver.status() != endLineStatus)
1551 int delta = logicalHeight() - layoutState.endLineLogicalTop();
1552 if (!delta || !m_floatingObjects)
1555 // See if any floats end in the range along which we want to shift the lines vertically.
1556 int logicalTop = min(logicalHeight(), layoutState.endLineLogicalTop());
1558 RootInlineBox* lastLine = layoutState.endLine();
1559 while (RootInlineBox* nextLine = lastLine->nextRootBox())
1560 lastLine = nextLine;
1562 int logicalBottom = lastLine->lineBottomWithLeading() + abs(delta);
1564 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1565 FloatingObjectSetIterator end = floatingObjectSet.end();
1566 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1567 FloatingObject* f = *it;
1568 if (logicalBottomForFloat(f) >= logicalTop && logicalBottomForFloat(f) < logicalBottom)
1575 // The first clean line doesn't match, but we can check a handful of following lines to try
1576 // to match back up.
1577 static int numLines = 8; // The # of lines we're willing to match against.
1578 RootInlineBox* line = layoutState.endLine();
1579 for (int i = 0; i < numLines && line; i++, line = line->nextRootBox()) {
1580 if (line->lineBreakObj() == resolver.position().m_obj && line->lineBreakPos() == resolver.position().m_pos) {
1582 if (line->lineBreakBidiStatus() != resolver.status())
1583 return false; // ...but the bidi state doesn't match.
1584 RootInlineBox* result = line->nextRootBox();
1586 // Set our logical top to be the block height of endLine.
1588 layoutState.setEndLineLogicalTop(line->lineBottomWithLeading());
1590 int delta = logicalHeight() - layoutState.endLineLogicalTop();
1591 if (delta && m_floatingObjects) {
1592 // See if any floats end in the range along which we want to shift the lines vertically.
1593 int logicalTop = min(logicalHeight(), layoutState.endLineLogicalTop());
1595 RootInlineBox* lastLine = layoutState.endLine();
1596 while (RootInlineBox* nextLine = lastLine->nextRootBox())
1597 lastLine = nextLine;
1599 int logicalBottom = lastLine->lineBottomWithLeading() + abs(delta);
1601 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1602 FloatingObjectSetIterator end = floatingObjectSet.end();
1603 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1604 FloatingObject* f = *it;
1605 if (logicalBottomForFloat(f) >= logicalTop && logicalBottomForFloat(f) < logicalBottom)
1610 // Now delete the lines that we failed to sync.
1611 deleteLineRange(layoutState, renderArena(), layoutState.endLine(), result);
1612 layoutState.setEndLine(result);
1620 static inline bool skipNonBreakingSpace(const InlineIterator& it, const LineInfo& lineInfo)
1622 if (it.m_obj->style()->nbspMode() != SPACE || it.current() != noBreakSpace)
1625 // FIXME: This is bad. It makes nbsp inconsistent with space and won't work correctly
1626 // with m_minWidth/m_maxWidth.
1627 // Do not skip a non-breaking space if it is the first character
1628 // on a line after a clean line break (or on the first line, since previousLineBrokeCleanly starts off
1630 if (lineInfo.isEmpty() && lineInfo.previousLineBrokeCleanly())
1636 enum WhitespacePosition { LeadingWhitespace, TrailingWhitespace };
1637 static inline bool shouldCollapseWhiteSpace(const RenderStyle* style, const LineInfo& lineInfo, WhitespacePosition whitespacePosition)
1640 // If a space (U+0020) at the beginning of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is removed.
1641 // If a space (U+0020) at the end of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is also removed.
1642 // If spaces (U+0020) or tabs (U+0009) at the end of a line have 'white-space' set to 'pre-wrap', UAs may visually collapse them.
1643 return style->collapseWhiteSpace()
1644 || (whitespacePosition == TrailingWhitespace && style->whiteSpace() == PRE_WRAP && (!lineInfo.isEmpty() || !lineInfo.previousLineBrokeCleanly()));
1647 static bool inlineFlowRequiresLineBox(RenderInline* flow)
1649 // FIXME: Right now, we only allow line boxes for inlines that are truly empty.
1650 // We need to fix this, though, because at the very least, inlines containing only
1651 // ignorable whitespace should should also have line boxes.
1652 return !flow->firstChild() && flow->hasInlineDirectionBordersPaddingOrMargin();
1655 static bool requiresLineBox(const InlineIterator& it, const LineInfo& lineInfo = LineInfo(), WhitespacePosition whitespacePosition = LeadingWhitespace)
1657 if (it.m_obj->isFloatingOrPositioned())
1660 if (it.m_obj->isRenderInline() && !inlineFlowRequiresLineBox(toRenderInline(it.m_obj)))
1663 if (!shouldCollapseWhiteSpace(it.m_obj->style(), lineInfo, whitespacePosition) || it.m_obj->isBR())
1666 UChar current = it.current();
1667 return current != ' ' && current != '\t' && current != softHyphen && (current != '\n' || it.m_obj->preservesNewline())
1668 && !skipNonBreakingSpace(it, lineInfo);
1671 bool RenderBlock::generatesLineBoxesForInlineChild(RenderObject* inlineObj)
1673 ASSERT(inlineObj->parent() == this);
1675 InlineIterator it(this, inlineObj, 0);
1676 // FIXME: We should pass correct value for WhitespacePosition.
1677 while (!it.atEnd() && !requiresLineBox(it))
1683 // FIXME: The entire concept of the skipTrailingWhitespace function is flawed, since we really need to be building
1684 // line boxes even for containers that may ultimately collapse away. Otherwise we'll never get positioned
1685 // elements quite right. In other words, we need to build this function's work into the normal line
1686 // object iteration process.
1687 // NB. this function will insert any floating elements that would otherwise
1688 // be skipped but it will not position them.
1689 void RenderBlock::LineBreaker::skipTrailingWhitespace(InlineIterator& iterator, const LineInfo& lineInfo)
1691 while (!iterator.atEnd() && !requiresLineBox(iterator, lineInfo, TrailingWhitespace)) {
1692 RenderObject* object = iterator.m_obj;
1693 if (object->isFloating()) {
1694 m_block->insertFloatingObject(toRenderBox(object));
1695 } else if (object->isPositioned())
1696 setStaticPositions(m_block, toRenderBox(object));
1697 iterator.increment();
1701 void RenderBlock::LineBreaker::skipLeadingWhitespace(InlineBidiResolver& resolver, const LineInfo& lineInfo,
1702 FloatingObject* lastFloatFromPreviousLine, LineWidth& width)
1704 while (!resolver.position().atEnd() && !requiresLineBox(resolver.position(), lineInfo, LeadingWhitespace)) {
1705 RenderObject* object = resolver.position().m_obj;
1706 if (object->isFloating())
1707 m_block->positionNewFloatOnLine(m_block->insertFloatingObject(toRenderBox(object)), lastFloatFromPreviousLine, width);
1708 else if (object->isPositioned())
1709 setStaticPositions(m_block, toRenderBox(object));
1710 resolver.increment();
1712 resolver.commitExplicitEmbedding();
1715 // This is currently just used for list markers and inline flows that have line boxes. Neither should
1716 // have an effect on whitespace at the start of the line.
1717 static bool shouldSkipWhitespaceAfterStartObject(RenderBlock* block, RenderObject* o, LineMidpointState& lineMidpointState)
1719 RenderObject* next = bidiNextSkippingEmptyInlines(block, o);
1720 if (next && !next->isBR() && next->isText() && toRenderText(next)->textLength() > 0) {
1721 RenderText* nextText = toRenderText(next);
1722 UChar nextChar = nextText->characters()[0];
1723 if (nextText->style()->isCollapsibleWhiteSpace(nextChar)) {
1724 addMidpoint(lineMidpointState, InlineIterator(0, o, 0));
1732 static inline float textWidth(RenderText* text, unsigned from, unsigned len, const Font& font, float xPos, bool isFixedPitch, bool collapseWhiteSpace)
1734 if (isFixedPitch || (!from && len == text->textLength()) || text->style()->hasTextCombine())
1735 return text->width(from, len, font, xPos);
1737 TextRun run = RenderBlock::constructTextRun(text, font, text->characters() + from, len, text->style());
1738 run.setCharactersLength(text->textLength() - from);
1739 ASSERT(run.charactersLength() >= run.length());
1741 run.setAllowTabs(!collapseWhiteSpace);
1743 return font.width(run);
1746 static void tryHyphenating(RenderText* text, const Font& font, const AtomicString& localeIdentifier, unsigned consecutiveHyphenatedLines, int consecutiveHyphenatedLinesLimit, int minimumPrefixLength, int minimumSuffixLength, int lastSpace, int pos, float xPos, int availableWidth, bool isFixedPitch, bool collapseWhiteSpace, int lastSpaceWordSpacing, InlineIterator& lineBreak, int nextBreakable, bool& hyphenated)
1748 // Map 'hyphenate-limit-{before,after}: auto;' to 2.
1749 if (minimumPrefixLength < 0)
1750 minimumPrefixLength = 2;
1752 if (minimumSuffixLength < 0)
1753 minimumSuffixLength = 2;
1755 if (pos - lastSpace <= minimumSuffixLength)
1758 if (consecutiveHyphenatedLinesLimit >= 0 && consecutiveHyphenatedLines >= static_cast<unsigned>(consecutiveHyphenatedLinesLimit))
1761 int hyphenWidth = measureHyphenWidth(text, font);
1763 float maxPrefixWidth = availableWidth - xPos - hyphenWidth - lastSpaceWordSpacing;
1764 // If the maximum width available for the prefix before the hyphen is small, then it is very unlikely
1765 // that an hyphenation opportunity exists, so do not bother to look for it.
1766 if (maxPrefixWidth <= font.pixelSize() * 5 / 4)
1769 TextRun run = RenderBlock::constructTextRun(text, font, text->characters() + lastSpace, pos - lastSpace, text->style());
1770 run.setCharactersLength(text->textLength() - lastSpace);
1771 ASSERT(run.charactersLength() >= run.length());
1773 run.setAllowTabs(!collapseWhiteSpace);
1774 run.setXPos(xPos + lastSpaceWordSpacing);
1776 unsigned prefixLength = font.offsetForPosition(run, maxPrefixWidth, false);
1777 if (prefixLength < static_cast<unsigned>(minimumPrefixLength))
1780 prefixLength = lastHyphenLocation(text->characters() + lastSpace, pos - lastSpace, min(prefixLength, static_cast<unsigned>(pos - lastSpace - minimumSuffixLength)) + 1, localeIdentifier);
1781 // FIXME: The following assumes that the character at lastSpace is a space (and therefore should not factor
1782 // into hyphenate-limit-before) unless lastSpace is 0. This is wrong in the rare case of hyphenating
1783 // the first word in a text node which has leading whitespace.
1784 if (!prefixLength || prefixLength - (lastSpace ? 1 : 0) < static_cast<unsigned>(minimumPrefixLength))
1787 ASSERT(pos - lastSpace - prefixLength >= static_cast<unsigned>(minimumSuffixLength));
1789 #if !ASSERT_DISABLED
1790 float prefixWidth = hyphenWidth + textWidth(text, lastSpace, prefixLength, font, xPos, isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing;
1791 ASSERT(xPos + prefixWidth <= availableWidth);
1793 UNUSED_PARAM(isFixedPitch);
1796 lineBreak.moveTo(text, lastSpace + prefixLength, nextBreakable);
1802 LineWidth(RenderBlock* block, bool isFirstLine)
1804 , m_uncommittedWidth(0)
1805 , m_committedWidth(0)
1806 , m_overhangWidth(0)
1809 , m_availableWidth(0)
1810 , m_isFirstLine(isFirstLine)
1813 updateAvailableWidth();
1815 bool fitsOnLine() const { return currentWidth() <= m_availableWidth; }
1816 bool fitsOnLine(float extra) const { return currentWidth() + extra <= m_availableWidth; }
1817 float currentWidth() const { return m_committedWidth + m_uncommittedWidth; }
1819 // FIXME: We should eventually replace these three functions by ones that work on a higher abstraction.
1820 float uncommittedWidth() const { return m_uncommittedWidth; }
1821 float committedWidth() const { return m_committedWidth; }
1822 float availableWidth() const { return m_availableWidth; }
1824 void updateAvailableWidth();
1825 void shrinkAvailableWidthForNewFloatIfNeeded(RenderBlock::FloatingObject*);
1826 void addUncommittedWidth(float delta) { m_uncommittedWidth += delta; }
1829 m_committedWidth += m_uncommittedWidth;
1830 m_uncommittedWidth = 0;
1832 void applyOverhang(RenderRubyRun*, RenderObject* startRenderer, RenderObject* endRenderer);
1833 void fitBelowFloats();
1836 void computeAvailableWidthFromLeftAndRight()
1838 m_availableWidth = max(0, m_right - m_left) + m_overhangWidth;
1842 RenderBlock* m_block;
1843 float m_uncommittedWidth;
1844 float m_committedWidth;
1845 float m_overhangWidth; // The amount by which |m_availableWidth| has been inflated to account for possible contraction due to ruby overhang.
1848 float m_availableWidth;
1852 inline void LineWidth::updateAvailableWidth()
1854 int height = m_block->logicalHeight();
1855 m_left = m_block->logicalLeftOffsetForLine(height, m_isFirstLine);
1856 m_right = m_block->logicalRightOffsetForLine(height, m_isFirstLine);
1858 computeAvailableWidthFromLeftAndRight();
1861 inline void LineWidth::shrinkAvailableWidthForNewFloatIfNeeded(RenderBlock::FloatingObject* newFloat)
1863 int height = m_block->logicalHeight();
1864 if (height < m_block->logicalTopForFloat(newFloat) || height >= m_block->logicalBottomForFloat(newFloat))
1867 if (newFloat->type() == RenderBlock::FloatingObject::FloatLeft) {
1868 m_left = m_block->logicalRightForFloat(newFloat);
1869 if (m_isFirstLine && m_block->style()->isLeftToRightDirection())
1870 m_left += m_block->textIndentOffset();
1872 m_right = m_block->logicalLeftForFloat(newFloat);
1873 if (m_isFirstLine && !m_block->style()->isLeftToRightDirection())
1874 m_right -= m_block->textIndentOffset();
1877 computeAvailableWidthFromLeftAndRight();
1880 void LineWidth::applyOverhang(RenderRubyRun* rubyRun, RenderObject* startRenderer, RenderObject* endRenderer)
1884 rubyRun->getOverhang(m_isFirstLine, startRenderer, endRenderer, startOverhang, endOverhang);
1886 startOverhang = min<int>(startOverhang, m_committedWidth);
1887 m_availableWidth += startOverhang;
1889 endOverhang = max(min<int>(endOverhang, m_availableWidth - currentWidth()), 0);
1890 m_availableWidth += endOverhang;
1891 m_overhangWidth += startOverhang + endOverhang;
1894 void LineWidth::fitBelowFloats()
1896 ASSERT(!m_committedWidth);
1897 ASSERT(!fitsOnLine());
1899 int floatLogicalBottom;
1900 int lastFloatLogicalBottom = m_block->logicalHeight();
1901 float newLineWidth = m_availableWidth;
1902 float newLineLeft = m_left;
1903 float newLineRight = m_right;
1905 floatLogicalBottom = m_block->nextFloatLogicalBottomBelow(lastFloatLogicalBottom);
1906 if (!floatLogicalBottom)
1909 newLineLeft = m_block->logicalLeftOffsetForLine(floatLogicalBottom, m_isFirstLine);
1910 newLineRight = m_block->logicalRightOffsetForLine(floatLogicalBottom, m_isFirstLine);
1911 newLineWidth = max(0.0f, newLineRight - newLineLeft);
1912 lastFloatLogicalBottom = floatLogicalBottom;
1913 if (newLineWidth >= m_uncommittedWidth)
1917 if (newLineWidth > m_availableWidth) {
1918 m_block->setLogicalHeight(lastFloatLogicalBottom);
1919 m_availableWidth = newLineWidth + m_overhangWidth;
1920 m_left = newLineLeft;
1921 m_right = newLineRight;
1925 class TrailingObjects {
1928 void setTrailingWhitespace(RenderText*);
1930 void appendBoxIfNeeded(RenderBox*);
1932 enum CollapseFirstSpaceOrNot { DoNotCollapseFirstSpace, CollapseFirstSpace };
1934 void updateMidpointsForTrailingBoxes(LineMidpointState&, const InlineIterator& lBreak, CollapseFirstSpaceOrNot);
1937 RenderText* m_whitespace;
1938 Vector<RenderBox*, 4> m_boxes;
1941 TrailingObjects::TrailingObjects()
1946 inline void TrailingObjects::setTrailingWhitespace(RenderText* whitespace)
1949 m_whitespace = whitespace;
1952 inline void TrailingObjects::clear()
1958 inline void TrailingObjects::appendBoxIfNeeded(RenderBox* box)
1961 m_boxes.append(box);
1964 void TrailingObjects::updateMidpointsForTrailingBoxes(LineMidpointState& lineMidpointState, const InlineIterator& lBreak, CollapseFirstSpaceOrNot collapseFirstSpace)
1969 // This object is either going to be part of the last midpoint, or it is going to be the actual endpoint.
1970 // In both cases we just decrease our pos by 1 level to exclude the space, allowing it to - in effect - collapse into the newline.
1971 if (lineMidpointState.numMidpoints % 2) {
1972 // Find the trailing space object's midpoint.
1973 int trailingSpaceMidpoint = lineMidpointState.numMidpoints - 1;
1974 for ( ; trailingSpaceMidpoint > 0 && lineMidpointState.midpoints[trailingSpaceMidpoint].m_obj != m_whitespace; --trailingSpaceMidpoint) { }
1975 ASSERT(trailingSpaceMidpoint >= 0);
1976 if (collapseFirstSpace == CollapseFirstSpace)
1977 lineMidpointState.midpoints[trailingSpaceMidpoint].m_pos--;
1979 // Now make sure every single trailingPositionedBox following the trailingSpaceMidpoint properly stops and starts
1981 size_t currentMidpoint = trailingSpaceMidpoint + 1;
1982 for (size_t i = 0; i < m_boxes.size(); ++i) {
1983 if (currentMidpoint >= lineMidpointState.numMidpoints) {
1984 // We don't have a midpoint for this box yet.
1985 InlineIterator ignoreStart(0, m_boxes[i], 0);
1986 addMidpoint(lineMidpointState, ignoreStart); // Stop ignoring.
1987 addMidpoint(lineMidpointState, ignoreStart); // Start ignoring again.
1989 ASSERT(lineMidpointState.midpoints[currentMidpoint].m_obj == m_boxes[i]);
1990 ASSERT(lineMidpointState.midpoints[currentMidpoint + 1].m_obj == m_boxes[i]);
1992 currentMidpoint += 2;
1994 } else if (!lBreak.m_obj) {
1995 ASSERT(m_whitespace->isText());
1996 ASSERT(collapseFirstSpace == CollapseFirstSpace);
1997 // Add a new end midpoint that stops right at the very end.
1998 unsigned length = m_whitespace->textLength();
1999 unsigned pos = length >= 2 ? length - 2 : UINT_MAX;
2000 InlineIterator endMid(0, m_whitespace, pos);
2001 addMidpoint(lineMidpointState, endMid);
2002 for (size_t i = 0; i < m_boxes.size(); ++i) {
2003 InlineIterator ignoreStart(0, m_boxes[i], 0);
2004 addMidpoint(lineMidpointState, ignoreStart); // Stop ignoring spaces.
2005 addMidpoint(lineMidpointState, ignoreStart); // Start ignoring again.
2010 void RenderBlock::LineBreaker::reset()
2012 m_positionedObjects.clear();
2013 m_hyphenated = false;
2017 InlineIterator RenderBlock::LineBreaker::nextLineBreak(InlineBidiResolver& resolver, LineInfo& lineInfo,
2018 LineBreakIteratorInfo& lineBreakIteratorInfo, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines)
2022 ASSERT(resolver.position().root() == m_block);
2024 bool appliedStartWidth = resolver.position().m_pos > 0;
2025 bool includeEndWidth = true;
2026 LineMidpointState& lineMidpointState = resolver.midpointState();
2028 LineWidth width(m_block, lineInfo.isFirstLine());
2030 skipLeadingWhitespace(resolver, lineInfo, lastFloatFromPreviousLine, width);
2032 if (resolver.position().atEnd())
2033 return resolver.position();
2035 // This variable is used only if whitespace isn't set to PRE, and it tells us whether
2036 // or not we are currently ignoring whitespace.
2037 bool ignoringSpaces = false;
2038 InlineIterator ignoreStart;
2040 // This variable tracks whether the very last character we saw was a space. We use
2041 // this to detect when we encounter a second space so we know we have to terminate
2043 bool currentCharacterIsSpace = false;
2044 bool currentCharacterIsWS = false;
2045 TrailingObjects trailingObjects;
2047 InlineIterator lBreak = resolver.position();
2049 // FIXME: It is error-prone to split the position object out like this.
2050 // Teach this code to work with objects instead of this split tuple.
2051 InlineIterator current = resolver.position();
2052 RenderObject* last = current.m_obj;
2053 bool atStart = true;
2055 bool startingNewParagraph = lineInfo.previousLineBrokeCleanly();
2056 lineInfo.setPreviousLineBrokeCleanly(false);
2058 bool autoWrapWasEverTrueOnLine = false;
2059 bool floatsFitOnLine = true;
2061 // Firefox and Opera will allow a table cell to grow to fit an image inside it under
2062 // very specific circumstances (in order to match common WinIE renderings).
2063 // Not supporting the quirk has caused us to mis-render some real sites. (See Bugzilla 10517.)
2064 bool allowImagesToBreak = !m_block->document()->inQuirksMode() || !m_block->isTableCell() || !m_block->style()->logicalWidth().isIntrinsicOrAuto();
2066 EWhiteSpace currWS = m_block->style()->whiteSpace();
2067 EWhiteSpace lastWS = currWS;
2068 while (current.m_obj) {
2069 RenderObject* next = bidiNextSkippingEmptyInlines(m_block, current.m_obj);
2070 if (next && next->parent() && !next->parent()->isDescendantOf(current.m_obj->parent()))
2071 includeEndWidth = true;
2073 currWS = current.m_obj->isReplaced() ? current.m_obj->parent()->style()->whiteSpace() : current.m_obj->style()->whiteSpace();
2074 lastWS = last->isReplaced() ? last->parent()->style()->whiteSpace() : last->style()->whiteSpace();
2076 bool autoWrap = RenderStyle::autoWrap(currWS);
2077 autoWrapWasEverTrueOnLine = autoWrapWasEverTrueOnLine || autoWrap;
2080 bool preserveNewline = current.m_obj->isSVGInlineText() ? false : RenderStyle::preserveNewline(currWS);
2082 bool preserveNewline = RenderStyle::preserveNewline(currWS);
2085 bool collapseWhiteSpace = RenderStyle::collapseWhiteSpace(currWS);
2087 if (current.m_obj->isBR()) {
2088 if (width.fitsOnLine()) {
2089 lBreak.moveToStartOf(current.m_obj);
2092 // A <br> always breaks a line, so don't let the line be collapsed
2093 // away. Also, the space at the end of a line with a <br> does not
2094 // get collapsed away. It only does this if the previous line broke
2095 // cleanly. Otherwise the <br> has no effect on whether the line is
2097 if (startingNewParagraph)
2098 lineInfo.setEmpty(false);
2099 trailingObjects.clear();
2100 lineInfo.setPreviousLineBrokeCleanly(true);
2102 if (!lineInfo.isEmpty())
2103 m_clear = current.m_obj->style()->clear();
2108 if (current.m_obj->isFloating()) {
2109 RenderBox* floatBox = toRenderBox(current.m_obj);
2110 FloatingObject* f = m_block->insertFloatingObject(floatBox);
2111 // check if it fits in the current line.
2112 // If it does, position it now, otherwise, position
2113 // it after moving to next line (in newLine() func)
2114 if (floatsFitOnLine && width.fitsOnLine(m_block->logicalWidthForFloat(f))) {
2115 m_block->positionNewFloatOnLine(f, lastFloatFromPreviousLine, width);
2116 if (lBreak.m_obj == current.m_obj) {
2117 ASSERT(!lBreak.m_pos);
2121 floatsFitOnLine = false;
2122 } else if (current.m_obj->isPositioned()) {
2123 // If our original display wasn't an inline type, then we can
2124 // go ahead and determine our static inline position now.
2125 RenderBox* box = toRenderBox(current.m_obj);
2126 bool isInlineType = box->style()->isOriginalDisplayInlineType();
2128 box->layer()->setStaticInlinePosition(m_block->borderAndPaddingStart());
2130 // If our original display was an INLINE type, then we can go ahead
2131 // and determine our static y position now.
2132 box->layer()->setStaticBlockPosition(m_block->logicalHeight());
2135 // If we're ignoring spaces, we have to stop and include this object and
2136 // then start ignoring spaces again.
2137 if (isInlineType || current.m_obj->container()->isRenderInline()) {
2138 if (ignoringSpaces) {
2139 ignoreStart.m_obj = current.m_obj;
2140 ignoreStart.m_pos = 0;
2141 addMidpoint(lineMidpointState, ignoreStart); // Stop ignoring spaces.
2142 addMidpoint(lineMidpointState, ignoreStart); // Start ignoring again.
2144 trailingObjects.appendBoxIfNeeded(box);
2146 m_positionedObjects.append(box);
2147 } else if (current.m_obj->isRenderInline()) {
2148 // Right now, we should only encounter empty inlines here.
2149 ASSERT(!current.m_obj->firstChild());
2151 RenderInline* flowBox = toRenderInline(current.m_obj);
2153 // Now that some inline flows have line boxes, if we are already ignoring spaces, we need
2154 // to make sure that we stop to include this object and then start ignoring spaces again.
2155 // If this object is at the start of the line, we need to behave like list markers and
2156 // start ignoring spaces.
2157 if (inlineFlowRequiresLineBox(flowBox)) {
2158 lineInfo.setEmpty(false);
2159 if (ignoringSpaces) {
2160 trailingObjects.clear();
2161 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, 0)); // Stop ignoring spaces.
2162 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, 0)); // Start ignoring again.
2163 } else if (m_block->style()->collapseWhiteSpace() && resolver.position().m_obj == current.m_obj
2164 && shouldSkipWhitespaceAfterStartObject(m_block, current.m_obj, lineMidpointState)) {
2165 // Like with list markers, we start ignoring spaces to make sure that any
2166 // additional spaces we see will be discarded.
2167 currentCharacterIsSpace = true;
2168 currentCharacterIsWS = true;
2169 ignoringSpaces = true;
2173 width.addUncommittedWidth(borderPaddingMarginStart(flowBox) + borderPaddingMarginEnd(flowBox));
2174 } else if (current.m_obj->isReplaced()) {
2175 RenderBox* replacedBox = toRenderBox(current.m_obj);
2177 // Break on replaced elements if either has normal white-space.
2178 if ((autoWrap || RenderStyle::autoWrap(lastWS)) && (!current.m_obj->isImage() || allowImagesToBreak)) {
2180 lBreak.moveToStartOf(current.m_obj);
2184 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, 0));
2186 lineInfo.setEmpty(false);
2187 ignoringSpaces = false;
2188 currentCharacterIsSpace = false;
2189 currentCharacterIsWS = false;
2190 trailingObjects.clear();
2192 // Optimize for a common case. If we can't find whitespace after the list
2193 // item, then this is all moot.
2194 int replacedLogicalWidth = m_block->logicalWidthForChild(replacedBox) + m_block->marginStartForChild(replacedBox) + m_block->marginEndForChild(replacedBox) + inlineLogicalWidth(current.m_obj);
2195 if (current.m_obj->isListMarker()) {
2196 if (m_block->style()->collapseWhiteSpace() && shouldSkipWhitespaceAfterStartObject(m_block, current.m_obj, lineMidpointState)) {
2197 // Like with inline flows, we start ignoring spaces to make sure that any
2198 // additional spaces we see will be discarded.
2199 currentCharacterIsSpace = true;
2200 currentCharacterIsWS = true;
2201 ignoringSpaces = true;
2203 if (toRenderListMarker(current.m_obj)->isInside())
2204 width.addUncommittedWidth(replacedLogicalWidth);
2206 width.addUncommittedWidth(replacedLogicalWidth);
2207 if (current.m_obj->isRubyRun())
2208 width.applyOverhang(toRenderRubyRun(current.m_obj), last, next);
2209 } else if (current.m_obj->isText()) {
2211 appliedStartWidth = false;
2213 RenderText* t = toRenderText(current.m_obj);
2216 bool isSVGText = t->isSVGInlineText();
2219 RenderStyle* style = t->style(lineInfo.isFirstLine());
2220 if (style->hasTextCombine() && current.m_obj->isCombineText())
2221 toRenderCombineText(current.m_obj)->combineText();
2223 const Font& f = style->font();
2224 bool isFixedPitch = f.isFixedPitch();
2225 bool canHyphenate = style->hyphens() == HyphensAuto && WebCore::canHyphenate(style->locale());
2227 int lastSpace = current.m_pos;
2228 float wordSpacing = current.m_obj->style()->wordSpacing();
2229 float lastSpaceWordSpacing = 0;
2231 // Non-zero only when kerning is enabled, in which case we measure words with their trailing
2232 // space, then subtract its width.
2233 float wordTrailingSpaceWidth = f.typesettingFeatures() & Kerning ? f.width(constructTextRun(t, f, &space, 1, style)) + wordSpacing : 0;
2235 float wrapW = width.uncommittedWidth() + inlineLogicalWidth(current.m_obj, !appliedStartWidth, true);
2236 float charWidth = 0;
2237 bool breakNBSP = autoWrap && current.m_obj->style()->nbspMode() == SPACE;
2238 // Auto-wrapping text should wrap in the middle of a word only if it could not wrap before the word,
2239 // which is only possible if the word is the first thing on the line, that is, if |w| is zero.
2240 bool breakWords = current.m_obj->style()->breakWords() && ((autoWrap && !width.committedWidth()) || currWS == PRE);
2241 bool midWordBreak = false;
2242 bool breakAll = current.m_obj->style()->wordBreak() == BreakAllWordBreak && autoWrap;
2243 float hyphenWidth = 0;
2245 if (t->isWordBreak()) {
2247 lBreak.moveToStartOf(current.m_obj);
2248 ASSERT(current.m_pos == t->textLength());
2251 for (; current.m_pos < t->textLength(); current.fastIncrementInTextNode()) {
2252 bool previousCharacterIsSpace = currentCharacterIsSpace;
2253 bool previousCharacterIsWS = currentCharacterIsWS;
2254 UChar c = current.current();
2255 currentCharacterIsSpace = c == ' ' || c == '\t' || (!preserveNewline && (c == '\n'));
2257 if (!collapseWhiteSpace || !currentCharacterIsSpace)
2258 lineInfo.setEmpty(false);
2260 if (c == softHyphen && autoWrap && !hyphenWidth && style->hyphens() != HyphensNone) {
2261 hyphenWidth = measureHyphenWidth(t, f);
2262 width.addUncommittedWidth(hyphenWidth);
2265 bool applyWordSpacing = false;
2267 currentCharacterIsWS = currentCharacterIsSpace || (breakNBSP && c == noBreakSpace);
2269 if ((breakAll || breakWords) && !midWordBreak) {
2271 bool midWordBreakIsBeforeSurrogatePair = U16_IS_LEAD(c) && current.m_pos + 1 < t->textLength() && U16_IS_TRAIL(t->characters()[current.m_pos + 1]);
2272 charWidth = textWidth(t, current.m_pos, midWordBreakIsBeforeSurrogatePair ? 2 : 1, f, width.committedWidth() + wrapW, isFixedPitch, collapseWhiteSpace);
2273 midWordBreak = width.committedWidth() + wrapW + charWidth > width.availableWidth();
2276 if (lineBreakIteratorInfo.first != t) {
2277 lineBreakIteratorInfo.first = t;
2278 lineBreakIteratorInfo.second.reset(t->characters(), t->textLength(), style->locale());
2281 bool betweenWords = c == '\n' || (currWS != PRE && !atStart && isBreakable(lineBreakIteratorInfo.second, current.m_pos, current.m_nextBreakablePosition, breakNBSP)
2282 && (style->hyphens() != HyphensNone || (current.previousInSameNode() != softHyphen)));
2284 if (betweenWords || midWordBreak) {
2285 bool stoppedIgnoringSpaces = false;
2286 if (ignoringSpaces) {
2287 if (!currentCharacterIsSpace) {
2288 // Stop ignoring spaces and begin at this
2290 ignoringSpaces = false;
2291 lastSpaceWordSpacing = 0;
2292 lastSpace = current.m_pos; // e.g., "Foo goo", don't add in any of the ignored spaces.
2293 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos));
2294 stoppedIgnoringSpaces = true;
2296 // Just keep ignoring these spaces.
2301 float additionalTmpW;
2302 if (wordTrailingSpaceWidth && currentCharacterIsSpace)
2303 additionalTmpW = textWidth(t, lastSpace, current.m_pos + 1 - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) - wordTrailingSpaceWidth + lastSpaceWordSpacing;
2305 additionalTmpW = textWidth(t, lastSpace, current.m_pos - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing;
2306 width.addUncommittedWidth(additionalTmpW);
2307 if (!appliedStartWidth) {
2308 width.addUncommittedWidth(inlineLogicalWidth(current.m_obj, true, false));
2309 appliedStartWidth = true;
2312 applyWordSpacing = wordSpacing && currentCharacterIsSpace && !previousCharacterIsSpace;
2314 if (!width.committedWidth() && autoWrap && !width.fitsOnLine())
2315 width.fitBelowFloats();
2317 if (autoWrap || breakWords) {
2318 // If we break only after white-space, consider the current character
2319 // as candidate width for this line.
2320 bool lineWasTooWide = false;
2321 if (width.fitsOnLine() && currentCharacterIsWS && current.m_obj->style()->breakOnlyAfterWhiteSpace() && !midWordBreak) {
2322 float charWidth = textWidth(t, current.m_pos, 1, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) + (applyWordSpacing ? wordSpacing : 0);
2323 // Check if line is too big even without the extra space
2324 // at the end of the line. If it is not, do nothing.
2325 // If the line needs the extra whitespace to be too long,
2326 // then move the line break to the space and skip all
2327 // additional whitespace.
2328 if (!width.fitsOnLine(charWidth)) {
2329 lineWasTooWide = true;
2330 lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2331 skipTrailingWhitespace(lBreak, lineInfo);
2334 if (lineWasTooWide || !width.fitsOnLine()) {
2335 if (canHyphenate && !width.fitsOnLine()) {
2336 tryHyphenating(t, f, style->locale(), consecutiveHyphenatedLines, m_block->style()->hyphenationLimitLines(), style->hyphenationLimitBefore(), style->hyphenationLimitAfter(), lastSpace, current.m_pos, width.currentWidth() - additionalTmpW, width.availableWidth(), isFixedPitch, collapseWhiteSpace, lastSpaceWordSpacing, lBreak, current.m_nextBreakablePosition, m_hyphenated);
2340 if (lBreak.atTextParagraphSeparator()) {
2341 if (!stoppedIgnoringSpaces && current.m_pos > 0) {
2342 // We need to stop right before the newline and then start up again.
2343 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos - 1)); // Stop
2344 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos)); // Start
2347 lineInfo.setPreviousLineBrokeCleanly(true);
2349 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)
2350 m_hyphenated = true;
2351 goto end; // Didn't fit. Jump to the end.
2353 if (!betweenWords || (midWordBreak && !autoWrap))
2354 width.addUncommittedWidth(-additionalTmpW);
2356 // Subtract the width of the soft hyphen out since we fit on a line.
2357 width.addUncommittedWidth(-hyphenWidth);
2363 if (c == '\n' && preserveNewline) {
2364 if (!stoppedIgnoringSpaces && current.m_pos > 0) {
2365 // We need to stop right before the newline and then start up again.
2366 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos - 1)); // Stop
2367 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos)); // Start
2369 lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2371 lineInfo.setPreviousLineBrokeCleanly(true);
2375 if (autoWrap && betweenWords) {
2378 lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2379 // Auto-wrapping text should not wrap in the middle of a word once it has had an
2380 // opportunity to break after a word.
2384 if (midWordBreak && !U16_IS_TRAIL(c) && !(category(c) & (Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining))) {
2385 // Remember this as a breakable position in case
2386 // adding the end width forces a break.
2387 lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2388 midWordBreak &= (breakWords || breakAll);
2392 lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
2393 lastSpace = current.m_pos;
2396 if (!ignoringSpaces && current.m_obj->style()->collapseWhiteSpace()) {
2397 // If we encounter a newline, or if we encounter a
2398 // second space, we need to go ahead and break up this
2399 // run and enter a mode where we start collapsing spaces.
2400 if (currentCharacterIsSpace && previousCharacterIsSpace) {
2401 ignoringSpaces = true;
2403 // We just entered a mode where we are ignoring
2404 // spaces. Create a midpoint to terminate the run
2405 // before the second space.
2406 addMidpoint(lineMidpointState, ignoreStart);
2407 trailingObjects.updateMidpointsForTrailingBoxes(lineMidpointState, InlineIterator(), TrailingObjects::DoNotCollapseFirstSpace);
2410 } else if (ignoringSpaces) {
2411 // Stop ignoring spaces and begin at this
2413 ignoringSpaces = false;
2414 lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
2415 lastSpace = current.m_pos; // e.g., "Foo goo", don't add in any of the ignored spaces.
2416 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos));
2420 if (isSVGText && current.m_pos > 0) {
2421 // Force creation of new InlineBoxes for each absolute positioned character (those that start new text chunks).
2422 if (toRenderSVGInlineText(t)->characterStartsNewTextChunk(current.m_pos)) {
2423 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos - 1));
2424 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos));
2429 if (currentCharacterIsSpace && !previousCharacterIsSpace) {
2430 ignoreStart.m_obj = current.m_obj;
2431 ignoreStart.m_pos = current.m_pos;
2434 if (!currentCharacterIsWS && previousCharacterIsWS) {
2435 if (autoWrap && current.m_obj->style()->breakOnlyAfterWhiteSpace())
2436 lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2439 if (collapseWhiteSpace && currentCharacterIsSpace && !ignoringSpaces)
2440 trailingObjects.setTrailingWhitespace(toRenderText(current.m_obj));
2441 else if (!current.m_obj->style()->collapseWhiteSpace() || !currentCharacterIsSpace)
2442 trailingObjects.clear();
2447 // IMPORTANT: current.m_pos is > length here!
2448 float additionalTmpW = ignoringSpaces ? 0 : textWidth(t, lastSpace, current.m_pos - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing;
2449 width.addUncommittedWidth(additionalTmpW + inlineLogicalWidth(current.m_obj, !appliedStartWidth, includeEndWidth));
2450 includeEndWidth = false;
2452 if (!width.fitsOnLine()) {
2454 tryHyphenating(t, f, style->locale(), consecutiveHyphenatedLines, m_block->style()->hyphenationLimitLines(), style->hyphenationLimitBefore(), style->hyphenationLimitAfter(), lastSpace, current.m_pos, width.currentWidth() - additionalTmpW, width.availableWidth(), isFixedPitch, collapseWhiteSpace, lastSpaceWordSpacing, lBreak, current.m_nextBreakablePosition, m_hyphenated);
2456 if (!m_hyphenated && lBreak.previousInSameNode() == softHyphen && style->hyphens() != HyphensNone)
2457 m_hyphenated = true;
2463 ASSERT_NOT_REACHED();
2465 bool checkForBreak = autoWrap;
2466 if (width.committedWidth() && !width.fitsOnLine() && lBreak.m_obj && currWS == NOWRAP)
2467 checkForBreak = true;
2468 else if (next && current.m_obj->isText() && next->isText() && !next->isBR() && (autoWrap || (next->style()->autoWrap()))) {
2469 if (currentCharacterIsSpace)
2470 checkForBreak = true;
2472 RenderText* nextText = toRenderText(next);
2473 if (nextText->textLength()) {
2474 UChar c = nextText->characters()[0];
2475 checkForBreak = (c == ' ' || c == '\t' || (c == '\n' && !next->preservesNewline()));
2476 // If the next item on the line is text, and if we did not end with
2477 // a space, then the next text run continues our word (and so it needs to
2478 // keep adding to |tmpW|. Just update and continue.
2479 } else if (nextText->isWordBreak())
2480 checkForBreak = true;
2482 if (!width.fitsOnLine() && !width.committedWidth())
2483 width.fitBelowFloats();
2485 bool canPlaceOnLine = width.fitsOnLine() || !autoWrapWasEverTrueOnLine;
2486 if (canPlaceOnLine && checkForBreak) {
2488 lBreak.moveToStartOf(next);
2493 if (checkForBreak && !width.fitsOnLine()) {
2494 // if we have floats, try to get below them.
2495 if (currentCharacterIsSpace && !ignoringSpaces && current.m_obj->style()->collapseWhiteSpace())
2496 trailingObjects.clear();
2498 if (width.committedWidth())
2501 width.fitBelowFloats();
2503 // |width| may have been adjusted because we got shoved down past a float (thus
2504 // giving us more room), so we need to retest, and only jump to
2505 // the end label if we still don't fit on the line. -dwh
2506 if (!width.fitsOnLine())
2510 if (!current.m_obj->isFloatingOrPositioned()) {
2511 last = current.m_obj;
2512 if (last->isReplaced() && autoWrap && (!last->isImage() || allowImagesToBreak) && (!last->isListMarker() || toRenderListMarker(last)->isInside())) {
2514 lBreak.moveToStartOf(next);
2518 // Clear out our character space bool, since inline <pre>s don't collapse whitespace
2519 // with adjacent inline normal/nowrap spans.
2520 if (!collapseWhiteSpace)
2521 currentCharacterIsSpace = false;
2523 current.moveToStartOf(next);
2527 if (width.fitsOnLine() || lastWS == NOWRAP)
2531 if (lBreak == resolver.position() && (!lBreak.m_obj || !lBreak.m_obj->isBR())) {
2532 // we just add as much as possible
2533 if (m_block->style()->whiteSpace() == PRE) {
2534 // FIXME: Don't really understand this case.
2535 if (current.m_pos) {
2536 // FIXME: This should call moveTo which would clear m_nextBreakablePosition
2537 // this code as-is is likely wrong.
2538 lBreak.m_obj = current.m_obj;
2539 lBreak.m_pos = current.m_pos - 1;
2541 lBreak.moveTo(last, last->isText() ? last->length() : 0);
2542 } else if (lBreak.m_obj) {
2543 // Don't ever break in the middle of a word if we can help it.
2544 // There's no room at all. We just have to be on this line,
2545 // even though we'll spill out.
2546 lBreak.moveTo(current.m_obj, current.m_pos);
2550 // make sure we consume at least one char/object.
2551 if (lBreak == resolver.position())
2554 // Sanity check our midpoints.
2555 checkMidpoints(lineMidpointState, lBreak);
2557 trailingObjects.updateMidpointsForTrailingBoxes(lineMidpointState, lBreak, TrailingObjects::CollapseFirstSpace);
2559 // We might have made lBreak an iterator that points past the end
2560 // of the object. Do this adjustment to make it point to the start
2561 // of the next object instead to avoid confusing the rest of the
2563 if (lBreak.m_pos > 0) {
2571 void RenderBlock::addOverflowFromInlineChildren()
2573 int endPadding = hasOverflowClip() ? paddingEnd() : 0;
2574 // FIXME: Need to find another way to do this, since scrollbars could show when we don't want them to.
2575 if (hasOverflowClip() && !endPadding && node() && node()->rendererIsEditable() && node() == node()->rootEditableElement() && style()->isLeftToRightDirection())
2577 for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
2578 addLayoutOverflow(curr->paddedLayoutOverflowRect(endPadding));
2579 if (!hasOverflowClip())
2580 addVisualOverflow(curr->visualOverflowRect(curr->lineTop(), curr->lineBottom()));
2584 void RenderBlock::deleteEllipsisLineBoxes()
2586 for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox())
2587 curr->clearTruncation();
2590 void RenderBlock::checkLinesForTextOverflow()
2592 // Determine the width of the ellipsis using the current font.
2593 // FIXME: CSS3 says this is configurable, also need to use 0x002E (FULL STOP) if horizontal ellipsis is "not renderable"
2594 const Font& font = style()->font();
2595 DEFINE_STATIC_LOCAL(AtomicString, ellipsisStr, (&horizontalEllipsis, 1));
2596 const Font& firstLineFont = firstLineStyle()->font();
2597 int firstLineEllipsisWidth = firstLineFont.width(constructTextRun(this, firstLineFont, &horizontalEllipsis, 1, firstLineStyle()));
2598 int ellipsisWidth = (font == firstLineFont) ? firstLineEllipsisWidth : font.width(constructTextRun(this, font, &horizontalEllipsis, 1, style()));
2600 // For LTR text truncation, we want to get the right edge of our padding box, and then we want to see
2601 // if the right edge of a line box exceeds that. For RTL, we use the left edge of the padding box and
2602 // check the left edge of the line box to see if it is less
2603 // Include the scrollbar for overflow blocks, which means we want to use "contentWidth()"
2604 bool ltr = style()->isLeftToRightDirection();
2605 for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
2606 int blockRightEdge = logicalRightOffsetForLine(curr->y(), curr == firstRootBox());
2607 int blockLeftEdge = logicalLeftOffsetForLine(curr->y(), curr == firstRootBox());
2608 int lineBoxEdge = ltr ? curr->x() + curr->logicalWidth() : curr->x();
2609 if ((ltr && lineBoxEdge > blockRightEdge) || (!ltr && lineBoxEdge < blockLeftEdge)) {
2610 // This line spills out of our box in the appropriate direction. Now we need to see if the line
2611 // can be truncated. In order for truncation to be possible, the line must have sufficient space to
2612 // accommodate our truncation string, and no replaced elements (images, tables) can overlap the ellipsis
2614 int width = curr == firstRootBox() ? firstLineEllipsisWidth : ellipsisWidth;
2615 int blockEdge = ltr ? blockRightEdge : blockLeftEdge;
2616 if (curr->lineCanAccommodateEllipsis(ltr, blockEdge, lineBoxEdge, width))
2617 curr->placeEllipsis(ellipsisStr, ltr, blockLeftEdge, blockRightEdge, width);
2622 bool RenderBlock::positionNewFloatOnLine(FloatingObject* newFloat, FloatingObject* lastFloatFromPreviousLine, LineWidth& width)
2624 if (!positionNewFloats())
2627 width.shrinkAvailableWidthForNewFloatIfNeeded(newFloat);
2629 if (!newFloat->m_paginationStrut)
2632 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2633 ASSERT(floatingObjectSet.last() == newFloat);
2635 int floatLogicalTop = logicalTopForFloat(newFloat);
2636 int paginationStrut = newFloat->m_paginationStrut;
2638 if (floatLogicalTop - paginationStrut != logicalHeight())
2641 FloatingObjectSetIterator it = floatingObjectSet.end();
2642 --it; // Last float is newFloat, skip that one.
2643 FloatingObjectSetIterator begin = floatingObjectSet.begin();
2644 while (it != begin) {
2646 FloatingObject* f = *it;
2647 if (f == lastFloatFromPreviousLine)
2649 if (logicalTopForFloat(f) == logicalHeight()) {
2650 ASSERT(!f->m_paginationStrut);
2651 f->m_paginationStrut = paginationStrut;
2652 RenderBox* o = f->m_renderer;
2653 setLogicalTopForChild(o, logicalTopForChild(o) + marginBeforeForChild(o) + paginationStrut);
2654 if (o->isRenderBlock())
2655 toRenderBlock(o)->setChildNeedsLayout(true, false);
2656 o->layoutIfNeeded();
2657 // Save the old logical top before calling removePlacedObject which will set
2658 // isPlaced to false. Otherwise it will trigger an assert in logicalTopForFloat.
2659 LayoutUnit oldLogicalTop = logicalTopForFloat(f);
2660 m_floatingObjects->removePlacedObject(f);
2661 setLogicalTopForFloat(f, oldLogicalTop + f->m_paginationStrut);
2662 m_floatingObjects->addPlacedObject(f);
2666 setLogicalHeight(logicalHeight() + paginationStrut);
2667 width.updateAvailableWidth();
2672 LayoutUnit RenderBlock::startAlignedOffsetForLine(RenderBox* child, LayoutUnit position, bool firstLine)
2674 ETextAlign textAlign = style()->textAlign();
2676 if (textAlign == TAAUTO)
2677 return startOffsetForLine(position, firstLine);
2679 // updateLogicalWidthForAlignment() handles the direction of the block so no need to consider it here
2681 float availableLogicalWidth;
2682 logicalLeft = logicalLeftOffsetForLine(logicalHeight(), false);
2683 availableLogicalWidth = logicalRightOffsetForLine(logicalHeight(), false) - logicalLeft;
2684 float totalLogicalWidth = logicalWidthForChild(child);
2685 updateLogicalWidthForAlignment(textAlign, 0l, logicalLeft, totalLogicalWidth, availableLogicalWidth, 0);