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 void setLogicalWidthForTextRun(RootInlineBox* lineBox, BidiRun* run, RenderText* renderer, float xPos, const LineInfo& lineInfo,
482 GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache)
484 HashSet<const SimpleFontData*> fallbackFonts;
485 GlyphOverflow glyphOverflow;
487 // Always compute glyph overflow if the block's line-box-contain value is "glyphs".
488 if (lineBox->fitsToGlyphs()) {
489 // If we don't stick out of the root line's font box, then don't bother computing our glyph overflow. This optimization
490 // will keep us from computing glyph bounds in nearly all cases.
491 bool includeRootLine = lineBox->includesRootLineBoxFontOrLeading();
492 int baselineShift = lineBox->verticalPositionForBox(run->m_box, verticalPositionCache);
493 int rootDescent = includeRootLine ? lineBox->renderer()->style(lineInfo.isFirstLine())->font().fontMetrics().descent() : 0;
494 int rootAscent = includeRootLine ? lineBox->renderer()->style(lineInfo.isFirstLine())->font().fontMetrics().ascent() : 0;
495 int boxAscent = renderer->style(lineInfo.isFirstLine())->font().fontMetrics().ascent() - baselineShift;
496 int boxDescent = renderer->style(lineInfo.isFirstLine())->font().fontMetrics().descent() + baselineShift;
497 if (boxAscent > rootDescent || boxDescent > rootAscent)
498 glyphOverflow.computeBounds = true;
502 if (toInlineTextBox(run->m_box)->hasHyphen()) {
503 const AtomicString& hyphenString = renderer->style()->hyphenString();
504 const Font& font = renderer->style(lineInfo.isFirstLine())->font();
505 hyphenWidth = font.width(RenderBlock::constructTextRun(renderer, font, hyphenString.string(), renderer->style()));
507 run->m_box->setLogicalWidth(renderer->width(run->m_start, run->m_stop - run->m_start, xPos, lineInfo.isFirstLine(), &fallbackFonts, &glyphOverflow) + hyphenWidth);
508 if (!fallbackFonts.isEmpty()) {
509 ASSERT(run->m_box->isText());
510 GlyphOverflowAndFallbackFontsMap::iterator it = textBoxDataMap.add(toInlineTextBox(run->m_box), make_pair(Vector<const SimpleFontData*>(), GlyphOverflow())).first;
511 ASSERT(it->second.first.isEmpty());
512 copyToVector(fallbackFonts, it->second.first);
513 run->m_box->parent()->clearDescendantsHaveSameLineHeightAndBaseline();
515 if ((glyphOverflow.top || glyphOverflow.bottom || glyphOverflow.left || glyphOverflow.right)) {
516 ASSERT(run->m_box->isText());
517 GlyphOverflowAndFallbackFontsMap::iterator it = textBoxDataMap.add(toInlineTextBox(run->m_box), make_pair(Vector<const SimpleFontData*>(), GlyphOverflow())).first;
518 it->second.second = glyphOverflow;
519 run->m_box->clearKnownToHaveNoOverflow();
523 static inline void computeExpansionForJustifiedText(BidiRun* firstRun, BidiRun* trailingSpaceRun, Vector<unsigned, 16>& expansionOpportunities, unsigned expansionOpportunityCount, float& totalLogicalWidth, float availableLogicalWidth)
525 if (!expansionOpportunityCount || availableLogicalWidth <= totalLogicalWidth)
529 for (BidiRun* r = firstRun; r; r = r->next()) {
530 if (!r->m_box || r == trailingSpaceRun)
533 if (r->m_object->isText()) {
534 unsigned opportunitiesInRun = expansionOpportunities[i++];
536 ASSERT(opportunitiesInRun <= expansionOpportunityCount);
538 // Only justify text if whitespace is collapsed.
539 if (r->m_object->style()->collapseWhiteSpace()) {
540 InlineTextBox* textBox = toInlineTextBox(r->m_box);
541 int expansion = (availableLogicalWidth - totalLogicalWidth) * opportunitiesInRun / expansionOpportunityCount;
542 textBox->setExpansion(expansion);
543 totalLogicalWidth += expansion;
545 expansionOpportunityCount -= opportunitiesInRun;
546 if (!expansionOpportunityCount)
552 void RenderBlock::computeInlineDirectionPositionsForLine(RootInlineBox* lineBox, const LineInfo& lineInfo, BidiRun* firstRun, BidiRun* trailingSpaceRun, bool reachedEnd,
553 GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache)
555 ETextAlign textAlign = textAlignmentForLine(!reachedEnd && !lineBox->endsWithBreak());
556 float logicalLeft = logicalLeftOffsetForLine(logicalHeight(), lineInfo.isFirstLine());
557 float availableLogicalWidth = logicalRightOffsetForLine(logicalHeight(), lineInfo.isFirstLine()) - logicalLeft;
559 bool needsWordSpacing = false;
560 float totalLogicalWidth = lineBox->getFlowSpacingLogicalWidth();
561 unsigned expansionOpportunityCount = 0;
562 bool isAfterExpansion = true;
563 Vector<unsigned, 16> expansionOpportunities;
564 RenderObject* previousObject = 0;
566 for (BidiRun* r = firstRun; r; r = r->next()) {
567 if (!r->m_box || r->m_object->isPositioned() || r->m_box->isLineBreak())
568 continue; // Positioned objects are only participating to figure out their
569 // correct static x position. They have no effect on the width.
570 // Similarly, line break boxes have no effect on the width.
571 if (r->m_object->isText()) {
572 RenderText* rt = toRenderText(r->m_object);
573 if (textAlign == JUSTIFY && r != trailingSpaceRun) {
574 if (!isAfterExpansion)
575 toInlineTextBox(r->m_box)->setCanHaveLeadingExpansion(true);
576 unsigned opportunitiesInRun = Font::expansionOpportunityCount(rt->characters() + r->m_start, r->m_stop - r->m_start, r->m_box->direction(), isAfterExpansion);
577 expansionOpportunities.append(opportunitiesInRun);
578 expansionOpportunityCount += opportunitiesInRun;
581 if (int length = rt->textLength()) {
582 if (!r->m_start && needsWordSpacing && isSpaceOrNewline(rt->characters()[r->m_start]))
583 totalLogicalWidth += rt->style(lineInfo.isFirstLine())->font().wordSpacing();
584 needsWordSpacing = !isSpaceOrNewline(rt->characters()[r->m_stop - 1]) && r->m_stop == length;
587 setLogicalWidthForTextRun(lineBox, r, rt, totalLogicalWidth, lineInfo, textBoxDataMap, verticalPositionCache);
589 isAfterExpansion = false;
590 if (!r->m_object->isRenderInline()) {
591 RenderBox* renderBox = toRenderBox(r->m_object);
592 if (renderBox->isRubyRun())
593 setMarginsForRubyRun(r, toRenderRubyRun(renderBox), previousObject, lineInfo);
594 r->m_box->setLogicalWidth(logicalWidthForChild(renderBox));
595 totalLogicalWidth += marginStartForChild(renderBox) + marginEndForChild(renderBox);
599 totalLogicalWidth += r->m_box->logicalWidth();
600 previousObject = r->m_object;
603 if (isAfterExpansion && !expansionOpportunities.isEmpty()) {
604 expansionOpportunities.last()--;
605 expansionOpportunityCount--;
608 // Armed with the total width of the line (without justification),
609 // we now examine our text-align property in order to determine where to position the
610 // objects horizontally. The total width of the line can be increased if we end up
615 updateLogicalWidthForLeftAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
618 adjustInlineDirectionLineBounds(expansionOpportunityCount, logicalLeft, availableLogicalWidth);
619 if (expansionOpportunityCount) {
620 if (trailingSpaceRun) {
621 totalLogicalWidth -= trailingSpaceRun->m_box->logicalWidth();
622 trailingSpaceRun->m_box->setLogicalWidth(0);
628 // for right to left fall through to right aligned
629 if (style()->isLeftToRightDirection()) {
630 if (totalLogicalWidth > availableLogicalWidth && trailingSpaceRun)
631 trailingSpaceRun->m_box->setLogicalWidth(max<float>(0, trailingSpaceRun->m_box->logicalWidth() - totalLogicalWidth + availableLogicalWidth));
636 updateLogicalWidthForRightAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
640 updateLogicalWidthForCenterAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
643 if (style()->isLeftToRightDirection())
644 updateLogicalWidthForLeftAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
646 updateLogicalWidthForRightAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
649 if (style()->isLeftToRightDirection())
650 updateLogicalWidthForRightAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
652 updateLogicalWidthForLeftAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
656 computeExpansionForJustifiedText(firstRun, trailingSpaceRun, expansionOpportunities, expansionOpportunityCount, totalLogicalWidth, availableLogicalWidth);
658 // The widths of all runs are now known. We can now place every inline box (and
659 // compute accurate widths for the inline flow boxes).
660 needsWordSpacing = false;
661 lineBox->placeBoxesInInlineDirection(logicalLeft, needsWordSpacing, textBoxDataMap);
664 void RenderBlock::computeBlockDirectionPositionsForLine(RootInlineBox* lineBox, BidiRun* firstRun, GlyphOverflowAndFallbackFontsMap& textBoxDataMap,
665 VerticalPositionCache& verticalPositionCache)
667 setLogicalHeight(lineBox->alignBoxesInBlockDirection(logicalHeight(), textBoxDataMap, verticalPositionCache));
668 lineBox->setBlockLogicalHeight(logicalHeight());
670 // Now make sure we place replaced render objects correctly.
671 for (BidiRun* r = firstRun; r; r = r->next()) {
674 continue; // Skip runs with no line boxes.
676 // Align positioned boxes with the top of the line box. This is
677 // a reasonable approximation of an appropriate y position.
678 if (r->m_object->isPositioned())
679 r->m_box->setLogicalTop(logicalHeight());
681 // Position is used to properly position both replaced elements and
682 // to update the static normal flow x/y of positioned elements.
683 if (r->m_object->isText())
684 toRenderText(r->m_object)->positionLineBox(r->m_box);
685 else if (r->m_object->isBox())
686 toRenderBox(r->m_object)->positionLineBox(r->m_box);
688 // Positioned objects and zero-length text nodes destroy their boxes in
689 // position(), which unnecessarily dirties the line.
690 lineBox->markDirty(false);
693 static inline bool isCollapsibleSpace(UChar character, RenderText* renderer)
695 if (character == ' ' || character == '\t' || character == softHyphen)
697 if (character == '\n')
698 return !renderer->style()->preserveNewline();
699 if (character == noBreakSpace)
700 return renderer->style()->nbspMode() == SPACE;
705 static void setStaticPositions(RenderBlock* block, RenderBox* child)
707 // FIXME: The math here is actually not really right. It's a best-guess approximation that
708 // will work for the common cases
709 RenderObject* containerBlock = child->container();
710 int blockHeight = block->logicalHeight();
711 if (containerBlock->isRenderInline()) {
712 // A relative positioned inline encloses us. In this case, we also have to determine our
713 // position as though we were an inline. Set |staticInlinePosition| and |staticBlockPosition| on the relative positioned
714 // inline so that we can obtain the value later.
715 toRenderInline(containerBlock)->layer()->setStaticInlinePosition(block->startOffsetForLine(blockHeight, false));
716 toRenderInline(containerBlock)->layer()->setStaticBlockPosition(blockHeight);
719 if (child->style()->isOriginalDisplayInlineType())
720 child->layer()->setStaticInlinePosition(block->startOffsetForLine(blockHeight, false));
722 child->layer()->setStaticInlinePosition(block->borderAndPaddingStart());
723 child->layer()->setStaticBlockPosition(blockHeight);
726 inline BidiRun* RenderBlock::handleTrailingSpaces(BidiRunList<BidiRun>& bidiRuns, BidiContext* currentContext)
728 if (!bidiRuns.runCount()
729 || !bidiRuns.logicallyLastRun()->m_object->style()->breakOnlyAfterWhiteSpace()
730 || !bidiRuns.logicallyLastRun()->m_object->style()->autoWrap())
733 BidiRun* trailingSpaceRun = bidiRuns.logicallyLastRun();
734 RenderObject* lastObject = trailingSpaceRun->m_object;
735 if (!lastObject->isText())
738 RenderText* lastText = toRenderText(lastObject);
739 const UChar* characters = lastText->characters();
740 int firstSpace = trailingSpaceRun->stop();
741 while (firstSpace > trailingSpaceRun->start()) {
742 UChar current = characters[firstSpace - 1];
743 if (!isCollapsibleSpace(current, lastText))
747 if (firstSpace == trailingSpaceRun->stop())
750 TextDirection direction = style()->direction();
751 bool shouldReorder = trailingSpaceRun != (direction == LTR ? bidiRuns.lastRun() : bidiRuns.firstRun());
752 if (firstSpace != trailingSpaceRun->start()) {
753 BidiContext* baseContext = currentContext;
754 while (BidiContext* parent = baseContext->parent())
755 baseContext = parent;
757 BidiRun* newTrailingRun = new (renderArena()) BidiRun(firstSpace, trailingSpaceRun->m_stop, trailingSpaceRun->m_object, baseContext, OtherNeutral);
758 trailingSpaceRun->m_stop = firstSpace;
759 if (direction == LTR)
760 bidiRuns.addRun(newTrailingRun);
762 bidiRuns.prependRun(newTrailingRun);
763 trailingSpaceRun = newTrailingRun;
764 return trailingSpaceRun;
767 return trailingSpaceRun;
769 if (direction == LTR) {
770 bidiRuns.moveRunToEnd(trailingSpaceRun);
771 trailingSpaceRun->m_level = 0;
773 bidiRuns.moveRunToBeginning(trailingSpaceRun);
774 trailingSpaceRun->m_level = 1;
776 return trailingSpaceRun;
779 void RenderBlock::appendFloatingObjectToLastLine(FloatingObject* floatingObject)
781 ASSERT(!floatingObject->m_originatingLine);
782 floatingObject->m_originatingLine = lastRootBox();
783 lastRootBox()->appendFloat(floatingObject->renderer());
786 // This function constructs line boxes for all of the text runs in the resolver and computes their position.
787 RootInlineBox* RenderBlock::createLineBoxesFromBidiRuns(BidiRunList<BidiRun>& bidiRuns, const InlineIterator& end, LineInfo& lineInfo, VerticalPositionCache& verticalPositionCache, BidiRun* trailingSpaceRun)
789 if (!bidiRuns.runCount())
792 // FIXME: Why is this only done when we had runs?
793 lineInfo.setLastLine(!end.m_obj);
795 RootInlineBox* lineBox = constructLine(bidiRuns, lineInfo);
799 lineBox->setEndsWithBreak(lineInfo.previousLineBrokeCleanly());
802 bool isSVGRootInlineBox = lineBox->isSVGRootInlineBox();
804 bool isSVGRootInlineBox = false;
807 GlyphOverflowAndFallbackFontsMap textBoxDataMap;
809 // Now we position all of our text runs horizontally.
810 if (!isSVGRootInlineBox)
811 computeInlineDirectionPositionsForLine(lineBox, lineInfo, bidiRuns.firstRun(), trailingSpaceRun, end.atEnd(), textBoxDataMap, verticalPositionCache);
813 // Now position our text runs vertically.
814 computeBlockDirectionPositionsForLine(lineBox, bidiRuns.firstRun(), textBoxDataMap, verticalPositionCache);
817 // SVG text layout code computes vertical & horizontal positions on its own.
818 // Note that we still need to execute computeVerticalPositionsForLine() as
819 // it calls InlineTextBox::positionLineBox(), which tracks whether the box
820 // contains reversed text or not. If we wouldn't do that editing and thus
821 // text selection in RTL boxes would not work as expected.
822 if (isSVGRootInlineBox) {
824 static_cast<SVGRootInlineBox*>(lineBox)->computePerCharacterLayoutInformation();
828 // Compute our overflow now.
829 lineBox->computeOverflow(lineBox->lineTop(), lineBox->lineBottom(), textBoxDataMap);
832 // Highlight acts as an overflow inflation.
833 if (style()->highlight() != nullAtom)
834 lineBox->addHighlightOverflow();
839 // Like LayoutState for layout(), LineLayoutState keeps track of global information
840 // during an entire linebox tree layout pass (aka layoutInlineChildren).
841 class LineLayoutState {
843 LineLayoutState(bool fullLayout, int& repaintLogicalTop, int& repaintLogicalBottom)
847 , m_endLineLogicalTop(0)
848 , m_endLineMatched(false)
849 , m_checkForFloatsFromLastLine(false)
850 , m_isFullLayout(fullLayout)
851 , m_repaintLogicalTop(repaintLogicalTop)
852 , m_repaintLogicalBottom(repaintLogicalBottom)
853 , m_usesRepaintBounds(false)
856 void markForFullLayout() { m_isFullLayout = true; }
857 bool isFullLayout() const { return m_isFullLayout; }
859 bool usesRepaintBounds() const { return m_usesRepaintBounds; }
861 void setRepaintRange(int logicalHeight)
863 m_usesRepaintBounds = true;
864 m_repaintLogicalTop = m_repaintLogicalBottom = logicalHeight;
867 void updateRepaintRangeFromBox(RootInlineBox* box, int paginationDelta = 0)
869 m_usesRepaintBounds = true;
870 m_repaintLogicalTop = min(m_repaintLogicalTop, box->logicalTopVisualOverflow() + min(paginationDelta, 0));
871 m_repaintLogicalBottom = max(m_repaintLogicalBottom, box->logicalBottomVisualOverflow() + max(paginationDelta, 0));
874 bool endLineMatched() const { return m_endLineMatched; }
875 void setEndLineMatched(bool endLineMatched) { m_endLineMatched = endLineMatched; }
877 bool checkForFloatsFromLastLine() const { return m_checkForFloatsFromLastLine; }
878 void setCheckForFloatsFromLastLine(bool check) { m_checkForFloatsFromLastLine = check; }
880 LineInfo& lineInfo() { return m_lineInfo; }
881 const LineInfo& lineInfo() const { return m_lineInfo; }
883 int endLineLogicalTop() const { return m_endLineLogicalTop; }
884 void setEndLineLogicalTop(int logicalTop) { m_endLineLogicalTop = logicalTop; }
886 RootInlineBox* endLine() const { return m_endLine; }
887 void setEndLine(RootInlineBox* line) { m_endLine = line; }
889 RenderBlock::FloatingObject* lastFloat() const { return m_lastFloat; }
890 void setLastFloat(RenderBlock::FloatingObject* lastFloat) { m_lastFloat = lastFloat; }
892 Vector<RenderBlock::FloatWithRect>& floats() { return m_floats; }
894 unsigned floatIndex() const { return m_floatIndex; }
895 void setFloatIndex(unsigned floatIndex) { m_floatIndex = floatIndex; }
898 Vector<RenderBlock::FloatWithRect> m_floats;
899 RenderBlock::FloatingObject* m_lastFloat;
900 RootInlineBox* m_endLine;
902 unsigned m_floatIndex;
903 int m_endLineLogicalTop;
904 bool m_endLineMatched;
905 bool m_checkForFloatsFromLastLine;
909 // FIXME: Should this be a range object instead of two ints?
910 int& m_repaintLogicalTop;
911 int& m_repaintLogicalBottom;
913 bool m_usesRepaintBounds;
916 static void deleteLineRange(LineLayoutState& layoutState, RenderArena* arena, RootInlineBox* startLine, RootInlineBox* stopLine = 0)
918 RootInlineBox* boxToDelete = startLine;
919 while (boxToDelete && boxToDelete != stopLine) {
920 layoutState.updateRepaintRangeFromBox(boxToDelete);
921 // Note: deleteLineRange(renderArena(), firstRootBox()) is not identical to deleteLineBoxTree().
922 // deleteLineBoxTree uses nextLineBox() instead of nextRootBox() when traversing.
923 RootInlineBox* next = boxToDelete->nextRootBox();
924 boxToDelete->deleteLine(arena);
929 void RenderBlock::layoutRunsAndFloats(LineLayoutState& layoutState, bool hasInlineChild)
931 // We want to skip ahead to the first dirty line
932 InlineBidiResolver resolver;
933 RootInlineBox* startLine = determineStartPosition(layoutState, resolver);
935 // FIXME: This would make more sense outside of this function, but since
936 // determineStartPosition can change the fullLayout flag we have to do this here. Failure to call
937 // determineStartPosition first will break fast/repaint/line-flow-with-floats-9.html.
938 if (layoutState.isFullLayout() && hasInlineChild && !selfNeedsLayout()) {
939 setNeedsLayout(true, false); // Mark ourselves as needing a full layout. This way we'll repaint like
940 // we're supposed to.
941 RenderView* v = view();
942 if (v && !v->doingFullRepaint() && hasLayer()) {
943 // Because we waited until we were already inside layout to discover
944 // that the block really needed a full layout, we missed our chance to repaint the layer
945 // before layout started. Luckily the layer has cached the repaint rect for its original
946 // position and size, and so we can use that to make a repaint happen now.
947 repaintUsingContainer(containerForRepaint(), layer()->repaintRect());
951 if (m_floatingObjects && !m_floatingObjects->set().isEmpty())
952 layoutState.setLastFloat(m_floatingObjects->set().last());
954 // We also find the first clean line and extract these lines. We will add them back
955 // if we determine that we're able to synchronize after handling all our dirty lines.
956 InlineIterator cleanLineStart;
957 BidiStatus cleanLineBidiStatus;
958 if (!layoutState.isFullLayout() && startLine)
959 determineEndPosition(layoutState, startLine, cleanLineStart, cleanLineBidiStatus);
962 if (!layoutState.usesRepaintBounds())
963 layoutState.setRepaintRange(logicalHeight());
964 deleteLineRange(layoutState, renderArena(), startLine);
967 if (!layoutState.isFullLayout() && lastRootBox() && lastRootBox()->endsWithBreak()) {
968 // If the last line before the start line ends with a line break that clear floats,
969 // adjust the height accordingly.
970 // A line break can be either the first or the last object on a line, depending on its direction.
971 if (InlineBox* lastLeafChild = lastRootBox()->lastLeafChild()) {
972 RenderObject* lastObject = lastLeafChild->renderer();
973 if (!lastObject->isBR())
974 lastObject = lastRootBox()->firstLeafChild()->renderer();
975 if (lastObject->isBR()) {
976 EClear clear = lastObject->style()->clear();
983 layoutRunsAndFloatsInRange(layoutState, resolver, cleanLineStart, cleanLineBidiStatus);
984 linkToEndLineIfNeeded(layoutState);
985 repaintDirtyFloats(layoutState.floats());
988 void RenderBlock::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, InlineBidiResolver& resolver, const InlineIterator& cleanLineStart, const BidiStatus& cleanLineBidiStatus)
990 bool paginated = view()->layoutState() && view()->layoutState()->isPaginated();
991 LineMidpointState& lineMidpointState = resolver.midpointState();
992 InlineIterator end = resolver.position();
993 bool checkForEndLineMatch = layoutState.endLine();
994 LineBreakIteratorInfo lineBreakIteratorInfo;
995 VerticalPositionCache verticalPositionCache;
997 LineBreaker lineBreaker(this);
999 while (!end.atEnd()) {
1000 // FIXME: Is this check necessary before the first iteration or can it be moved to the end?
1001 if (checkForEndLineMatch) {
1002 layoutState.setEndLineMatched(matchedEndLine(layoutState, resolver, cleanLineStart, cleanLineBidiStatus));
1003 if (layoutState.endLineMatched())
1007 lineMidpointState.reset();
1009 layoutState.lineInfo().setEmpty(true);
1011 InlineIterator oldEnd = end;
1012 bool isNewUBAParagraph = layoutState.lineInfo().previousLineBrokeCleanly();
1013 FloatingObject* lastFloatFromPreviousLine = (m_floatingObjects && !m_floatingObjects->set().isEmpty()) ? m_floatingObjects->set().last() : 0;
1014 end = lineBreaker.nextLineBreak(resolver, layoutState.lineInfo(), lineBreakIteratorInfo, lastFloatFromPreviousLine);
1015 if (resolver.position().atEnd()) {
1016 // FIXME: We shouldn't be creating any runs in findNextLineBreak to begin with!
1017 // Once BidiRunList is separated from BidiResolver this will not be needed.
1018 resolver.runs().deleteRuns();
1019 resolver.markCurrentRunEmpty(); // FIXME: This can probably be replaced by an ASSERT (or just removed).
1020 layoutState.setCheckForFloatsFromLastLine(true);
1023 ASSERT(end != resolver.position());
1025 // This is a short-cut for empty lines.
1026 if (layoutState.lineInfo().isEmpty()) {
1028 lastRootBox()->setLineBreakInfo(end.m_obj, end.m_pos, resolver.status());
1030 VisualDirectionOverride override = (style()->rtlOrdering() == VisualOrder ? (style()->direction() == LTR ? VisualLeftToRightOverride : VisualRightToLeftOverride) : NoVisualOverride);
1032 if (isNewUBAParagraph && style()->unicodeBidi() == Plaintext && !resolver.context()->parent()) {
1033 TextDirection direction = style()->direction();
1034 determineParagraphDirection(direction, resolver.position());
1035 resolver.setStatus(BidiStatus(direction, style()->unicodeBidi() == Override));
1037 // FIXME: This ownership is reversed. We should own the BidiRunList and pass it to createBidiRunsForLine.
1038 BidiRunList<BidiRun>& bidiRuns = resolver.runs();
1039 resolver.createBidiRunsForLine(end, override, layoutState.lineInfo().previousLineBrokeCleanly());
1040 ASSERT(resolver.position() == end);
1042 BidiRun* trailingSpaceRun = !layoutState.lineInfo().previousLineBrokeCleanly() ? handleTrailingSpaces(bidiRuns, resolver.context()) : 0;
1044 if (bidiRuns.runCount() && lineBreaker.lineWasHyphenated())
1045 bidiRuns.logicallyLastRun()->m_hasHyphen = true;
1047 // Now that the runs have been ordered, we create the line boxes.
1048 // At the same time we figure out where border/padding/margin should be applied for
1049 // inline flow boxes.
1051 int oldLogicalHeight = logicalHeight();
1052 RootInlineBox* lineBox = createLineBoxesFromBidiRuns(bidiRuns, end, layoutState.lineInfo(), verticalPositionCache, trailingSpaceRun);
1054 bidiRuns.deleteRuns();
1055 resolver.markCurrentRunEmpty(); // FIXME: This can probably be replaced by an ASSERT (or just removed).
1058 lineBox->setLineBreakInfo(end.m_obj, end.m_pos, resolver.status());
1059 if (layoutState.usesRepaintBounds())
1060 layoutState.updateRepaintRangeFromBox(lineBox);
1064 adjustLinePositionForPagination(lineBox, adjustment);
1066 int oldLineWidth = availableLogicalWidthForLine(oldLogicalHeight, layoutState.lineInfo().isFirstLine());
1067 lineBox->adjustBlockDirectionPosition(adjustment);
1068 if (layoutState.usesRepaintBounds())
1069 layoutState.updateRepaintRangeFromBox(lineBox);
1071 if (availableLogicalWidthForLine(oldLogicalHeight + adjustment, layoutState.lineInfo().isFirstLine()) != oldLineWidth) {
1072 // We have to delete this line, remove all floats that got added, and let line layout re-run.
1073 lineBox->deleteLine(renderArena());
1074 removeFloatingObjectsBelow(lastFloatFromPreviousLine, oldLogicalHeight);
1075 setLogicalHeight(oldLogicalHeight + adjustment);
1076 resolver.setPosition(oldEnd);
1081 setLogicalHeight(lineBox->blockLogicalHeight());
1086 for (size_t i = 0; i < lineBreaker.positionedObjects().size(); ++i)
1087 setStaticPositions(this, lineBreaker.positionedObjects()[i]);
1089 layoutState.lineInfo().setFirstLine(false);
1090 newLine(lineBreaker.clear());
1093 if (m_floatingObjects && lastRootBox()) {
1094 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1095 FloatingObjectSetIterator it = floatingObjectSet.begin();
1096 FloatingObjectSetIterator end = floatingObjectSet.end();
1097 if (layoutState.lastFloat()) {
1098 FloatingObjectSetIterator lastFloatIterator = floatingObjectSet.find(layoutState.lastFloat());
1099 ASSERT(lastFloatIterator != end);
1100 ++lastFloatIterator;
1101 it = lastFloatIterator;
1103 for (; it != end; ++it) {
1104 FloatingObject* f = *it;
1105 appendFloatingObjectToLastLine(f);
1106 ASSERT(f->m_renderer == layoutState.floats()[layoutState.floatIndex()].object);
1107 // If a float's geometry has changed, give up on syncing with clean lines.
1108 if (layoutState.floats()[layoutState.floatIndex()].rect != f->frameRect())
1109 checkForEndLineMatch = false;
1110 layoutState.setFloatIndex(layoutState.floatIndex() + 1);
1112 layoutState.setLastFloat(!floatingObjectSet.isEmpty() ? floatingObjectSet.last() : 0);
1115 lineMidpointState.reset();
1116 resolver.setPosition(end);
1120 void RenderBlock::linkToEndLineIfNeeded(LineLayoutState& layoutState)
1122 if (layoutState.endLine()) {
1123 if (layoutState.endLineMatched()) {
1124 bool paginated = view()->layoutState() && view()->layoutState()->isPaginated();
1125 // Attach all the remaining lines, and then adjust their y-positions as needed.
1126 int delta = logicalHeight() - layoutState.endLineLogicalTop();
1127 for (RootInlineBox* line = layoutState.endLine(); line; line = line->nextRootBox()) {
1130 delta -= line->paginationStrut();
1131 adjustLinePositionForPagination(line, delta);
1134 layoutState.updateRepaintRangeFromBox(line, delta);
1135 line->adjustBlockDirectionPosition(delta);
1137 if (Vector<RenderBox*>* cleanLineFloats = line->floatsPtr()) {
1138 Vector<RenderBox*>::iterator end = cleanLineFloats->end();
1139 for (Vector<RenderBox*>::iterator f = cleanLineFloats->begin(); f != end; ++f) {
1140 FloatingObject* floatingObject = insertFloatingObject(*f);
1141 ASSERT(!floatingObject->m_originatingLine);
1142 floatingObject->m_originatingLine = line;
1143 setLogicalHeight(logicalTopForChild(*f) - marginBeforeForChild(*f) + delta);
1144 positionNewFloats();
1148 setLogicalHeight(lastRootBox()->blockLogicalHeight());
1150 // Delete all the remaining lines.
1151 deleteLineRange(layoutState, renderArena(), layoutState.endLine());
1155 if (m_floatingObjects && (layoutState.checkForFloatsFromLastLine() || positionNewFloats()) && lastRootBox()) {
1156 // In case we have a float on the last line, it might not be positioned up to now.
1157 // This has to be done before adding in the bottom border/padding, or the float will
1158 // include the padding incorrectly. -dwh
1159 if (layoutState.checkForFloatsFromLastLine()) {
1160 int bottomVisualOverflow = lastRootBox()->logicalBottomVisualOverflow();
1161 int bottomLayoutOverflow = lastRootBox()->logicalBottomLayoutOverflow();
1162 TrailingFloatsRootInlineBox* trailingFloatsLineBox = new (renderArena()) TrailingFloatsRootInlineBox(this);
1163 m_lineBoxes.appendLineBox(trailingFloatsLineBox);
1164 trailingFloatsLineBox->setConstructed();
1165 GlyphOverflowAndFallbackFontsMap textBoxDataMap;
1166 VerticalPositionCache verticalPositionCache;
1167 trailingFloatsLineBox->alignBoxesInBlockDirection(logicalHeight(), textBoxDataMap, verticalPositionCache);
1168 int blockLogicalHeight = logicalHeight();
1169 IntRect logicalLayoutOverflow(0, blockLogicalHeight, 1, bottomLayoutOverflow - blockLogicalHeight);
1170 IntRect logicalVisualOverflow(0, blockLogicalHeight, 1, bottomVisualOverflow - blockLogicalHeight);
1171 trailingFloatsLineBox->setOverflowFromLogicalRects(logicalLayoutOverflow, logicalVisualOverflow, trailingFloatsLineBox->lineTop(), trailingFloatsLineBox->lineBottom());
1172 trailingFloatsLineBox->setBlockLogicalHeight(logicalHeight());
1175 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1176 FloatingObjectSetIterator it = floatingObjectSet.begin();
1177 FloatingObjectSetIterator end = floatingObjectSet.end();
1178 if (layoutState.lastFloat()) {
1179 FloatingObjectSetIterator lastFloatIterator = floatingObjectSet.find(layoutState.lastFloat());
1180 ASSERT(lastFloatIterator != end);
1181 ++lastFloatIterator;
1182 it = lastFloatIterator;
1184 for (; it != end; ++it)
1185 appendFloatingObjectToLastLine(*it);
1186 layoutState.setLastFloat(!floatingObjectSet.isEmpty() ? floatingObjectSet.last() : 0);
1190 void RenderBlock::repaintDirtyFloats(Vector<FloatWithRect>& floats)
1192 size_t floatCount = floats.size();
1193 // Floats that did not have layout did not repaint when we laid them out. They would have
1194 // painted by now if they had moved, but if they stayed at (0, 0), they still need to be
1196 for (size_t i = 0; i < floatCount; ++i) {
1197 if (!floats[i].everHadLayout) {
1198 RenderBox* f = floats[i].object;
1199 if (!f->x() && !f->y() && f->checkForRepaintDuringLayout())
1205 void RenderBlock::layoutInlineChildren(bool relayoutChildren, int& repaintLogicalTop, int& repaintLogicalBottom)
1209 setLogicalHeight(borderBefore() + paddingBefore());
1211 // Figure out if we should clear out our line boxes.
1212 // FIXME: Handle resize eventually!
1213 bool isFullLayout = !firstLineBox() || selfNeedsLayout() || relayoutChildren;
1214 LineLayoutState layoutState(isFullLayout, repaintLogicalTop, repaintLogicalBottom);
1217 lineBoxes()->deleteLineBoxes(renderArena());
1219 // Text truncation only kicks in if your overflow isn't visible and your text-overflow-mode isn't
1221 // FIXME: CSS3 says that descendants that are clipped must also know how to truncate. This is insanely
1222 // difficult to figure out (especially in the middle of doing layout), and is really an esoteric pile of nonsense
1223 // anyway, so we won't worry about following the draft here.
1224 bool hasTextOverflow = style()->textOverflow() && hasOverflowClip();
1226 // Walk all the lines and delete our ellipsis line boxes if they exist.
1227 if (hasTextOverflow)
1228 deleteEllipsisLineBoxes();
1231 // layout replaced elements
1232 bool hasInlineChild = false;
1233 for (InlineWalker walker(this); !walker.atEnd(); walker.advance()) {
1234 RenderObject* o = walker.current();
1235 if (!hasInlineChild && o->isInline())
1236 hasInlineChild = true;
1238 if (o->isReplaced() || o->isFloating() || o->isPositioned()) {
1239 RenderBox* box = toRenderBox(o);
1241 if (relayoutChildren || o->style()->width().isPercent() || o->style()->height().isPercent())
1242 o->setChildNeedsLayout(true, false);
1244 // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
1245 if (relayoutChildren && box->needsPreferredWidthsRecalculation())
1246 o->setPreferredLogicalWidthsDirty(true, false);
1248 if (o->isPositioned())
1249 o->containingBlock()->insertPositionedObject(box);
1250 else if (o->isFloating())
1251 layoutState.floats().append(FloatWithRect(box));
1252 else if (layoutState.isFullLayout() || o->needsLayout()) {
1253 // Replaced elements
1254 toRenderBox(o)->dirtyLineBoxes(layoutState.isFullLayout());
1255 o->layoutIfNeeded();
1257 } else if (o->isText() || (o->isRenderInline() && !walker.atEndOfInline())) {
1259 toRenderInline(o)->updateAlwaysCreateLineBoxes(layoutState.isFullLayout());
1260 if (layoutState.isFullLayout() || o->selfNeedsLayout())
1261 dirtyLineBoxesForRenderer(o, layoutState.isFullLayout());
1262 o->setNeedsLayout(false);
1266 layoutRunsAndFloats(layoutState, hasInlineChild);
1269 // Expand the last line to accommodate Ruby and emphasis marks.
1270 int lastLineAnnotationsAdjustment = 0;
1271 if (lastRootBox()) {
1272 int lowestAllowedPosition = max(lastRootBox()->lineBottom(), logicalHeight() + paddingAfter());
1273 if (!style()->isFlippedLinesWritingMode())
1274 lastLineAnnotationsAdjustment = lastRootBox()->computeUnderAnnotationAdjustment(lowestAllowedPosition);
1276 lastLineAnnotationsAdjustment = lastRootBox()->computeOverAnnotationAdjustment(lowestAllowedPosition);
1279 // Now add in the bottom border/padding.
1280 setLogicalHeight(logicalHeight() + lastLineAnnotationsAdjustment + borderAfter() + paddingAfter() + scrollbarLogicalHeight());
1282 if (!firstLineBox() && hasLineIfEmpty())
1283 setLogicalHeight(logicalHeight() + lineHeight(true, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes));
1285 // See if we have any lines that spill out of our block. If we do, then we will possibly need to
1287 if (hasTextOverflow)
1288 checkLinesForTextOverflow();
1291 void RenderBlock::checkFloatsInCleanLine(RootInlineBox* line, Vector<FloatWithRect>& floats, size_t& floatIndex, bool& encounteredNewFloat, bool& dirtiedByFloat)
1293 Vector<RenderBox*>* cleanLineFloats = line->floatsPtr();
1294 if (!cleanLineFloats)
1297 Vector<RenderBox*>::iterator end = cleanLineFloats->end();
1298 for (Vector<RenderBox*>::iterator it = cleanLineFloats->begin(); it != end; ++it) {
1299 RenderBox* floatingBox = *it;
1300 floatingBox->layoutIfNeeded();
1301 IntSize newSize(floatingBox->width() + floatingBox->marginLeft() + floatingBox->marginRight(), floatingBox->height() + floatingBox->marginTop() + floatingBox->marginBottom());
1302 ASSERT(floatIndex < floats.size());
1303 if (floats[floatIndex].object != floatingBox) {
1304 encounteredNewFloat = true;
1308 if (floats[floatIndex].rect.size() != newSize) {
1309 int floatTop = isHorizontalWritingMode() ? floats[floatIndex].rect.y() : floats[floatIndex].rect.x();
1310 int floatHeight = isHorizontalWritingMode() ? max(floats[floatIndex].rect.height(), newSize.height())
1311 : max(floats[floatIndex].rect.width(), newSize.width());
1312 floatHeight = min(floatHeight, numeric_limits<int>::max() - floatTop);
1314 markLinesDirtyInBlockRange(line->blockLogicalHeight(), floatTop + floatHeight, line);
1315 floats[floatIndex].rect.setSize(newSize);
1316 dirtiedByFloat = true;
1322 RootInlineBox* RenderBlock::determineStartPosition(LineLayoutState& layoutState, InlineBidiResolver& resolver)
1324 RootInlineBox* curr = 0;
1325 RootInlineBox* last = 0;
1327 // FIXME: This entire float-checking block needs to be broken into a new function.
1328 bool dirtiedByFloat = false;
1329 if (!layoutState.isFullLayout()) {
1330 // Paginate all of the clean lines.
1331 bool paginated = view()->layoutState() && view()->layoutState()->isPaginated();
1332 int paginationDelta = 0;
1333 size_t floatIndex = 0;
1334 for (curr = firstRootBox(); curr && !curr->isDirty(); curr = curr->nextRootBox()) {
1336 paginationDelta -= curr->paginationStrut();
1337 adjustLinePositionForPagination(curr, paginationDelta);
1338 if (paginationDelta) {
1339 if (containsFloats() || !layoutState.floats().isEmpty()) {
1340 // FIXME: Do better eventually. For now if we ever shift because of pagination and floats are present just go to a full layout.
1341 layoutState.markForFullLayout();
1345 layoutState.updateRepaintRangeFromBox(curr, paginationDelta);
1346 curr->adjustBlockDirectionPosition(paginationDelta);
1350 // If a new float has been inserted before this line or before its last known float, just do a full layout.
1351 bool encounteredNewFloat = false;
1352 checkFloatsInCleanLine(curr, layoutState.floats(), floatIndex, encounteredNewFloat, dirtiedByFloat);
1353 if (encounteredNewFloat)
1354 layoutState.markForFullLayout();
1356 if (dirtiedByFloat || layoutState.isFullLayout())
1359 // Check if a new float has been inserted after the last known float.
1360 if (!curr && floatIndex < layoutState.floats().size())
1361 layoutState.markForFullLayout();
1364 if (layoutState.isFullLayout()) {
1365 // FIXME: This should just call deleteLineBoxTree, but that causes
1366 // crashes for fast/repaint tests.
1367 RenderArena* arena = renderArena();
1368 curr = firstRootBox();
1370 // Note: This uses nextRootBox() insted of nextLineBox() like deleteLineBoxTree does.
1371 RootInlineBox* next = curr->nextRootBox();
1372 curr->deleteLine(arena);
1375 ASSERT(!firstLineBox() && !lastLineBox());
1378 // We have a dirty line.
1379 if (RootInlineBox* prevRootBox = curr->prevRootBox()) {
1380 // We have a previous line.
1381 if (!dirtiedByFloat && (!prevRootBox->endsWithBreak() || (prevRootBox->lineBreakObj()->isText() && prevRootBox->lineBreakPos() >= toRenderText(prevRootBox->lineBreakObj())->textLength())))
1382 // The previous line didn't break cleanly or broke at a newline
1383 // that has been deleted, so treat it as dirty too.
1387 // No dirty lines were found.
1388 // If the last line didn't break cleanly, treat it as dirty.
1389 if (lastRootBox() && !lastRootBox()->endsWithBreak())
1390 curr = lastRootBox();
1393 // If we have no dirty lines, then last is just the last root box.
1394 last = curr ? curr->prevRootBox() : lastRootBox();
1397 unsigned numCleanFloats = 0;
1398 if (!layoutState.floats().isEmpty()) {
1399 int savedLogicalHeight = logicalHeight();
1400 // Restore floats from clean lines.
1401 RootInlineBox* line = firstRootBox();
1402 while (line != curr) {
1403 if (Vector<RenderBox*>* cleanLineFloats = line->floatsPtr()) {
1404 Vector<RenderBox*>::iterator end = cleanLineFloats->end();
1405 for (Vector<RenderBox*>::iterator f = cleanLineFloats->begin(); f != end; ++f) {
1406 FloatingObject* floatingObject = insertFloatingObject(*f);
1407 ASSERT(!floatingObject->m_originatingLine);
1408 floatingObject->m_originatingLine = line;
1409 setLogicalHeight(logicalTopForChild(*f) - marginBeforeForChild(*f));
1410 positionNewFloats();
1411 ASSERT(layoutState.floats()[numCleanFloats].object == *f);
1415 line = line->nextRootBox();
1417 setLogicalHeight(savedLogicalHeight);
1419 layoutState.setFloatIndex(numCleanFloats);
1421 layoutState.lineInfo().setFirstLine(!last);
1422 layoutState.lineInfo().setPreviousLineBrokeCleanly(!last || last->endsWithBreak());
1425 setLogicalHeight(last->blockLogicalHeight());
1426 resolver.setPosition(InlineIterator(this, last->lineBreakObj(), last->lineBreakPos()));
1427 resolver.setStatus(last->lineBreakBidiStatus());
1429 TextDirection direction = style()->direction();
1430 if (style()->unicodeBidi() == Plaintext)
1431 determineParagraphDirection(direction, InlineIterator(this, bidiFirstNotSkippingInlines(this), 0));
1432 resolver.setStatus(BidiStatus(direction, style()->unicodeBidi() == Override));
1433 resolver.setPosition(InlineIterator(this, bidiFirstSkippingInlines(this, &resolver), 0));
1438 void RenderBlock::determineEndPosition(LineLayoutState& layoutState, RootInlineBox* startLine, InlineIterator& cleanLineStart, BidiStatus& cleanLineBidiStatus)
1440 ASSERT(!layoutState.endLine());
1441 size_t floatIndex = layoutState.floatIndex();
1442 RootInlineBox* last = 0;
1443 for (RootInlineBox* curr = startLine->nextRootBox(); curr; curr = curr->nextRootBox()) {
1444 if (!curr->isDirty()) {
1445 bool encounteredNewFloat = false;
1446 bool dirtiedByFloat = false;
1447 checkFloatsInCleanLine(curr, layoutState.floats(), floatIndex, encounteredNewFloat, dirtiedByFloat);
1448 if (encounteredNewFloat)
1451 if (curr->isDirty())
1460 // At this point, |last| is the first line in a run of clean lines that ends with the last line
1463 RootInlineBox* prev = last->prevRootBox();
1464 cleanLineStart = InlineIterator(this, prev->lineBreakObj(), prev->lineBreakPos());
1465 cleanLineBidiStatus = prev->lineBreakBidiStatus();
1466 layoutState.setEndLineLogicalTop(prev->blockLogicalHeight());
1468 for (RootInlineBox* line = last; line; line = line->nextRootBox())
1469 line->extractLine(); // Disconnect all line boxes from their render objects while preserving
1470 // their connections to one another.
1472 layoutState.setEndLine(last);
1475 bool RenderBlock::matchedEndLine(LineLayoutState& layoutState, const InlineBidiResolver& resolver, const InlineIterator& endLineStart, const BidiStatus& endLineStatus)
1477 if (resolver.position() == endLineStart) {
1478 if (resolver.status() != endLineStatus)
1481 int delta = logicalHeight() - layoutState.endLineLogicalTop();
1482 if (!delta || !m_floatingObjects)
1485 // See if any floats end in the range along which we want to shift the lines vertically.
1486 int logicalTop = min(logicalHeight(), layoutState.endLineLogicalTop());
1488 RootInlineBox* lastLine = layoutState.endLine();
1489 while (RootInlineBox* nextLine = lastLine->nextRootBox())
1490 lastLine = nextLine;
1492 int logicalBottom = lastLine->blockLogicalHeight() + abs(delta);
1494 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1495 FloatingObjectSetIterator end = floatingObjectSet.end();
1496 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1497 FloatingObject* f = *it;
1498 if (logicalBottomForFloat(f) >= logicalTop && logicalBottomForFloat(f) < logicalBottom)
1505 // The first clean line doesn't match, but we can check a handful of following lines to try
1506 // to match back up.
1507 static int numLines = 8; // The # of lines we're willing to match against.
1508 RootInlineBox* line = layoutState.endLine();
1509 for (int i = 0; i < numLines && line; i++, line = line->nextRootBox()) {
1510 if (line->lineBreakObj() == resolver.position().m_obj && line->lineBreakPos() == resolver.position().m_pos) {
1512 if (line->lineBreakBidiStatus() != resolver.status())
1513 return false; // ...but the bidi state doesn't match.
1514 RootInlineBox* result = line->nextRootBox();
1516 // Set our logical top to be the block height of endLine.
1518 layoutState.setEndLineLogicalTop(line->blockLogicalHeight());
1520 int delta = logicalHeight() - layoutState.endLineLogicalTop();
1521 if (delta && m_floatingObjects) {
1522 // See if any floats end in the range along which we want to shift the lines vertically.
1523 int logicalTop = min(logicalHeight(), layoutState.endLineLogicalTop());
1525 RootInlineBox* lastLine = layoutState.endLine();
1526 while (RootInlineBox* nextLine = lastLine->nextRootBox())
1527 lastLine = nextLine;
1529 int logicalBottom = lastLine->blockLogicalHeight() + abs(delta);
1531 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1532 FloatingObjectSetIterator end = floatingObjectSet.end();
1533 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1534 FloatingObject* f = *it;
1535 if (logicalBottomForFloat(f) >= logicalTop && logicalBottomForFloat(f) < logicalBottom)
1540 // Now delete the lines that we failed to sync.
1541 deleteLineRange(layoutState, renderArena(), layoutState.endLine(), result);
1542 layoutState.setEndLine(result);
1550 static inline bool skipNonBreakingSpace(const InlineIterator& it, const LineInfo& lineInfo)
1552 if (it.m_obj->style()->nbspMode() != SPACE || it.current() != noBreakSpace)
1555 // FIXME: This is bad. It makes nbsp inconsistent with space and won't work correctly
1556 // with m_minWidth/m_maxWidth.
1557 // Do not skip a non-breaking space if it is the first character
1558 // on a line after a clean line break (or on the first line, since previousLineBrokeCleanly starts off
1560 if (lineInfo.isEmpty() && lineInfo.previousLineBrokeCleanly())
1566 enum WhitespacePosition { LeadingWhitespace, TrailingWhitespace };
1567 static inline bool shouldCollapseWhiteSpace(const RenderStyle* style, const LineInfo& lineInfo, WhitespacePosition whitespacePosition)
1570 // If a space (U+0020) at the beginning of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is removed.
1571 // 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.
1572 // 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.
1573 return style->collapseWhiteSpace()
1574 || (whitespacePosition == TrailingWhitespace && style->whiteSpace() == PRE_WRAP && (!lineInfo.isEmpty() || !lineInfo.previousLineBrokeCleanly()));
1577 static bool inlineFlowRequiresLineBox(RenderInline* flow)
1579 // FIXME: Right now, we only allow line boxes for inlines that are truly empty.
1580 // We need to fix this, though, because at the very least, inlines containing only
1581 // ignorable whitespace should should also have line boxes.
1582 return !flow->firstChild() && flow->hasInlineDirectionBordersPaddingOrMargin();
1585 static bool requiresLineBox(const InlineIterator& it, const LineInfo& lineInfo = LineInfo(), WhitespacePosition whitespacePosition = LeadingWhitespace)
1587 if (it.m_obj->isFloatingOrPositioned())
1590 if (it.m_obj->isRenderInline() && !inlineFlowRequiresLineBox(toRenderInline(it.m_obj)))
1593 if (!shouldCollapseWhiteSpace(it.m_obj->style(), lineInfo, whitespacePosition) || it.m_obj->isBR())
1596 UChar current = it.current();
1597 return current != ' ' && current != '\t' && current != softHyphen && (current != '\n' || it.m_obj->preservesNewline())
1598 && !skipNonBreakingSpace(it, lineInfo);
1601 bool RenderBlock::generatesLineBoxesForInlineChild(RenderObject* inlineObj)
1603 ASSERT(inlineObj->parent() == this);
1605 InlineIterator it(this, inlineObj, 0);
1606 // FIXME: We should pass correct value for WhitespacePosition.
1607 while (!it.atEnd() && !requiresLineBox(it))
1613 // FIXME: The entire concept of the skipTrailingWhitespace function is flawed, since we really need to be building
1614 // line boxes even for containers that may ultimately collapse away. Otherwise we'll never get positioned
1615 // elements quite right. In other words, we need to build this function's work into the normal line
1616 // object iteration process.
1617 // NB. this function will insert any floating elements that would otherwise
1618 // be skipped but it will not position them.
1619 void RenderBlock::LineBreaker::skipTrailingWhitespace(InlineIterator& iterator, const LineInfo& lineInfo)
1621 while (!iterator.atEnd() && !requiresLineBox(iterator, lineInfo, TrailingWhitespace)) {
1622 RenderObject* object = iterator.m_obj;
1623 if (object->isFloating()) {
1624 m_block->insertFloatingObject(toRenderBox(object));
1625 } else if (object->isPositioned())
1626 setStaticPositions(m_block, toRenderBox(object));
1627 iterator.increment();
1631 void RenderBlock::LineBreaker::skipLeadingWhitespace(InlineBidiResolver& resolver, const LineInfo& lineInfo,
1632 FloatingObject* lastFloatFromPreviousLine, LineWidth& width)
1634 while (!resolver.position().atEnd() && !requiresLineBox(resolver.position(), lineInfo, LeadingWhitespace)) {
1635 RenderObject* object = resolver.position().m_obj;
1636 if (object->isFloating())
1637 m_block->positionNewFloatOnLine(m_block->insertFloatingObject(toRenderBox(object)), lastFloatFromPreviousLine, width);
1638 else if (object->isPositioned())
1639 setStaticPositions(m_block, toRenderBox(object));
1640 resolver.increment();
1642 resolver.commitExplicitEmbedding();
1645 // This is currently just used for list markers and inline flows that have line boxes. Neither should
1646 // have an effect on whitespace at the start of the line.
1647 static bool shouldSkipWhitespaceAfterStartObject(RenderBlock* block, RenderObject* o, LineMidpointState& lineMidpointState)
1649 RenderObject* next = bidiNext(block, o);
1650 if (next && !next->isBR() && next->isText() && toRenderText(next)->textLength() > 0) {
1651 RenderText* nextText = toRenderText(next);
1652 UChar nextChar = nextText->characters()[0];
1653 if (nextText->style()->isCollapsibleWhiteSpace(nextChar)) {
1654 addMidpoint(lineMidpointState, InlineIterator(0, o, 0));
1662 static inline float textWidth(RenderText* text, unsigned from, unsigned len, const Font& font, float xPos, bool isFixedPitch, bool collapseWhiteSpace)
1664 if (isFixedPitch || (!from && len == text->textLength()) || text->style()->hasTextCombine())
1665 return text->width(from, len, font, xPos);
1667 TextRun run = RenderBlock::constructTextRun(text, font, text->characters() + from, len, text->style());
1668 run.setCharactersLength(text->textLength() - from);
1669 ASSERT(run.charactersLength() >= run.length());
1671 run.setAllowTabs(!collapseWhiteSpace);
1673 return font.width(run);
1676 static void tryHyphenating(RenderText* text, const Font& font, const AtomicString& localeIdentifier, int minimumPrefixLength, int minimumSuffixLength, int lastSpace, int pos, float xPos, int availableWidth, bool isFixedPitch, bool collapseWhiteSpace, int lastSpaceWordSpacing, InlineIterator& lineBreak, int nextBreakable, bool& hyphenated)
1678 // Map 'hyphenate-limit-{before,after}: auto;' to 2.
1679 if (minimumPrefixLength < 0)
1680 minimumPrefixLength = 2;
1682 if (minimumSuffixLength < 0)
1683 minimumSuffixLength = 2;
1685 if (pos - lastSpace <= minimumSuffixLength)
1688 const AtomicString& hyphenString = text->style()->hyphenString();
1689 int hyphenWidth = font.width(RenderBlock::constructTextRun(text, font, hyphenString.string(), text->style()));
1691 float maxPrefixWidth = availableWidth - xPos - hyphenWidth - lastSpaceWordSpacing;
1692 // If the maximum width available for the prefix before the hyphen is small, then it is very unlikely
1693 // that an hyphenation opportunity exists, so do not bother to look for it.
1694 if (maxPrefixWidth <= font.pixelSize() * 5 / 4)
1697 TextRun run = RenderBlock::constructTextRun(text, font, text->characters() + lastSpace, pos - lastSpace, text->style());
1698 run.setCharactersLength(text->textLength() - lastSpace);
1699 ASSERT(run.charactersLength() >= run.length());
1701 run.setAllowTabs(!collapseWhiteSpace);
1702 run.setXPos(xPos + lastSpaceWordSpacing);
1704 unsigned prefixLength = font.offsetForPosition(run, maxPrefixWidth, false);
1705 if (prefixLength < static_cast<unsigned>(minimumPrefixLength))
1708 prefixLength = lastHyphenLocation(text->characters() + lastSpace, pos - lastSpace, min(prefixLength, static_cast<unsigned>(pos - lastSpace - minimumSuffixLength)) + 1, localeIdentifier);
1709 // FIXME: The following assumes that the character at lastSpace is a space (and therefore should not factor
1710 // into hyphenate-limit-before) unless lastSpace is 0. This is wrong in the rare case of hyphenating
1711 // the first word in a text node which has leading whitespace.
1712 if (!prefixLength || prefixLength - (lastSpace ? 1 : 0) < static_cast<unsigned>(minimumPrefixLength))
1715 ASSERT(pos - lastSpace - prefixLength >= static_cast<unsigned>(minimumSuffixLength));
1717 #if !ASSERT_DISABLED
1718 float prefixWidth = hyphenWidth + textWidth(text, lastSpace, prefixLength, font, xPos, isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing;
1719 ASSERT(xPos + prefixWidth <= availableWidth);
1721 UNUSED_PARAM(isFixedPitch);
1724 lineBreak.moveTo(text, lastSpace + prefixLength, nextBreakable);
1730 LineWidth(RenderBlock* block, bool isFirstLine)
1732 , m_uncommittedWidth(0)
1733 , m_committedWidth(0)
1734 , m_overhangWidth(0)
1737 , m_availableWidth(0)
1738 , m_isFirstLine(isFirstLine)
1741 updateAvailableWidth();
1743 bool fitsOnLine() const { return currentWidth() <= m_availableWidth; }
1744 bool fitsOnLine(float extra) const { return currentWidth() + extra <= m_availableWidth; }
1745 float currentWidth() const { return m_committedWidth + m_uncommittedWidth; }
1747 // FIXME: We should eventually replace these three functions by ones that work on a higher abstraction.
1748 float uncommittedWidth() const { return m_uncommittedWidth; }
1749 float committedWidth() const { return m_committedWidth; }
1750 float availableWidth() const { return m_availableWidth; }
1752 void updateAvailableWidth();
1753 void shrinkAvailableWidthForNewFloatIfNeeded(RenderBlock::FloatingObject*);
1754 void addUncommittedWidth(float delta) { m_uncommittedWidth += delta; }
1757 m_committedWidth += m_uncommittedWidth;
1758 m_uncommittedWidth = 0;
1760 void applyOverhang(RenderRubyRun*, RenderObject* startRenderer, RenderObject* endRenderer);
1761 void fitBelowFloats();
1764 void computeAvailableWidthFromLeftAndRight()
1766 m_availableWidth = max(0, m_right - m_left) + m_overhangWidth;
1770 RenderBlock* m_block;
1771 float m_uncommittedWidth;
1772 float m_committedWidth;
1773 float m_overhangWidth; // The amount by which |m_availableWidth| has been inflated to account for possible contraction due to ruby overhang.
1776 float m_availableWidth;
1780 inline void LineWidth::updateAvailableWidth()
1782 int height = m_block->logicalHeight();
1783 m_left = m_block->logicalLeftOffsetForLine(height, m_isFirstLine);
1784 m_right = m_block->logicalRightOffsetForLine(height, m_isFirstLine);
1786 computeAvailableWidthFromLeftAndRight();
1789 inline void LineWidth::shrinkAvailableWidthForNewFloatIfNeeded(RenderBlock::FloatingObject* newFloat)
1791 int height = m_block->logicalHeight();
1792 if (height < m_block->logicalTopForFloat(newFloat) || height >= m_block->logicalBottomForFloat(newFloat))
1795 if (newFloat->type() == RenderBlock::FloatingObject::FloatLeft)
1796 m_left = m_block->logicalRightForFloat(newFloat);
1798 m_right = m_block->logicalLeftForFloat(newFloat);
1800 computeAvailableWidthFromLeftAndRight();
1803 void LineWidth::applyOverhang(RenderRubyRun* rubyRun, RenderObject* startRenderer, RenderObject* endRenderer)
1807 rubyRun->getOverhang(m_isFirstLine, startRenderer, endRenderer, startOverhang, endOverhang);
1809 startOverhang = min<int>(startOverhang, m_committedWidth);
1810 m_availableWidth += startOverhang;
1812 endOverhang = max(min<int>(endOverhang, m_availableWidth - currentWidth()), 0);
1813 m_availableWidth += endOverhang;
1814 m_overhangWidth += startOverhang + endOverhang;
1817 void LineWidth::fitBelowFloats()
1819 ASSERT(!m_committedWidth);
1820 ASSERT(!fitsOnLine());
1822 int floatLogicalBottom;
1823 int lastFloatLogicalBottom = m_block->logicalHeight();
1824 float newLineWidth = m_availableWidth;
1826 floatLogicalBottom = m_block->nextFloatLogicalBottomBelow(lastFloatLogicalBottom);
1827 if (!floatLogicalBottom)
1830 newLineWidth = m_block->availableLogicalWidthForLine(floatLogicalBottom, m_isFirstLine);
1831 lastFloatLogicalBottom = floatLogicalBottom;
1832 if (newLineWidth >= m_uncommittedWidth)
1836 if (newLineWidth > m_availableWidth) {
1837 m_block->setLogicalHeight(lastFloatLogicalBottom);
1838 m_availableWidth = newLineWidth + m_overhangWidth;
1842 class TrailingObjects {
1845 void setTrailingWhitespace(RenderText*);
1847 void appendBoxIfNeeded(RenderBox*);
1849 enum CollapseFirstSpaceOrNot { DoNotCollapseFirstSpace, CollapseFirstSpace };
1851 void updateMidpointsForTrailingBoxes(LineMidpointState&, const InlineIterator& lBreak, CollapseFirstSpaceOrNot);
1854 RenderText* m_whitespace;
1855 Vector<RenderBox*, 4> m_boxes;
1858 TrailingObjects::TrailingObjects()
1863 inline void TrailingObjects::setTrailingWhitespace(RenderText* whitespace)
1866 m_whitespace = whitespace;
1869 inline void TrailingObjects::clear()
1875 inline void TrailingObjects::appendBoxIfNeeded(RenderBox* box)
1878 m_boxes.append(box);
1881 void TrailingObjects::updateMidpointsForTrailingBoxes(LineMidpointState& lineMidpointState, const InlineIterator& lBreak, CollapseFirstSpaceOrNot collapseFirstSpace)
1886 // This object is either going to be part of the last midpoint, or it is going to be the actual endpoint.
1887 // In both cases we just decrease our pos by 1 level to exclude the space, allowing it to - in effect - collapse into the newline.
1888 if (lineMidpointState.numMidpoints % 2) {
1889 // Find the trailing space object's midpoint.
1890 int trailingSpaceMidpoint = lineMidpointState.numMidpoints - 1;
1891 for ( ; trailingSpaceMidpoint > 0 && lineMidpointState.midpoints[trailingSpaceMidpoint].m_obj != m_whitespace; --trailingSpaceMidpoint) { }
1892 ASSERT(trailingSpaceMidpoint >= 0);
1893 if (collapseFirstSpace == CollapseFirstSpace)
1894 lineMidpointState.midpoints[trailingSpaceMidpoint].m_pos--;
1896 // Now make sure every single trailingPositionedBox following the trailingSpaceMidpoint properly stops and starts
1898 size_t currentMidpoint = trailingSpaceMidpoint + 1;
1899 for (size_t i = 0; i < m_boxes.size(); ++i) {
1900 if (currentMidpoint >= lineMidpointState.numMidpoints) {
1901 // We don't have a midpoint for this box yet.
1902 InlineIterator ignoreStart(0, m_boxes[i], 0);
1903 addMidpoint(lineMidpointState, ignoreStart); // Stop ignoring.
1904 addMidpoint(lineMidpointState, ignoreStart); // Start ignoring again.
1906 ASSERT(lineMidpointState.midpoints[currentMidpoint].m_obj == m_boxes[i]);
1907 ASSERT(lineMidpointState.midpoints[currentMidpoint + 1].m_obj == m_boxes[i]);
1909 currentMidpoint += 2;
1911 } else if (!lBreak.m_obj) {
1912 ASSERT(m_whitespace->isText());
1913 ASSERT(collapseFirstSpace == CollapseFirstSpace);
1914 // Add a new end midpoint that stops right at the very end.
1915 unsigned length = m_whitespace->textLength();
1916 unsigned pos = length >= 2 ? length - 2 : UINT_MAX;
1917 InlineIterator endMid(0, m_whitespace, pos);
1918 addMidpoint(lineMidpointState, endMid);
1919 for (size_t i = 0; i < m_boxes.size(); ++i) {
1920 InlineIterator ignoreStart(0, m_boxes[i], 0);
1921 addMidpoint(lineMidpointState, ignoreStart); // Stop ignoring spaces.
1922 addMidpoint(lineMidpointState, ignoreStart); // Start ignoring again.
1927 void RenderBlock::LineBreaker::reset()
1929 m_positionedObjects.clear();
1930 m_hyphenated = false;
1934 InlineIterator RenderBlock::LineBreaker::nextLineBreak(InlineBidiResolver& resolver, LineInfo& lineInfo,
1935 LineBreakIteratorInfo& lineBreakIteratorInfo, FloatingObject* lastFloatFromPreviousLine)
1939 ASSERT(resolver.position().root() == m_block);
1941 bool appliedStartWidth = resolver.position().m_pos > 0;
1942 bool includeEndWidth = true;
1943 LineMidpointState& lineMidpointState = resolver.midpointState();
1945 LineWidth width(m_block, lineInfo.isFirstLine());
1947 skipLeadingWhitespace(resolver, lineInfo, lastFloatFromPreviousLine, width);
1949 if (resolver.position().atEnd())
1950 return resolver.position();
1952 // This variable is used only if whitespace isn't set to PRE, and it tells us whether
1953 // or not we are currently ignoring whitespace.
1954 bool ignoringSpaces = false;
1955 InlineIterator ignoreStart;
1957 // This variable tracks whether the very last character we saw was a space. We use
1958 // this to detect when we encounter a second space so we know we have to terminate
1960 bool currentCharacterIsSpace = false;
1961 bool currentCharacterIsWS = false;
1962 TrailingObjects trailingObjects;
1964 InlineIterator lBreak = resolver.position();
1966 // FIXME: It is error-prone to split the position object out like this.
1967 // Teach this code to work with objects instead of this split tuple.
1968 InlineIterator current = resolver.position();
1969 RenderObject* last = current.m_obj;
1970 bool atStart = true;
1972 bool startingNewParagraph = lineInfo.previousLineBrokeCleanly();
1973 lineInfo.setPreviousLineBrokeCleanly(false);
1975 bool autoWrapWasEverTrueOnLine = false;
1976 bool floatsFitOnLine = true;
1978 // Firefox and Opera will allow a table cell to grow to fit an image inside it under
1979 // very specific circumstances (in order to match common WinIE renderings).
1980 // Not supporting the quirk has caused us to mis-render some real sites. (See Bugzilla 10517.)
1981 bool allowImagesToBreak = !m_block->document()->inQuirksMode() || !m_block->isTableCell() || !m_block->style()->logicalWidth().isIntrinsicOrAuto();
1983 EWhiteSpace currWS = m_block->style()->whiteSpace();
1984 EWhiteSpace lastWS = currWS;
1985 while (current.m_obj) {
1986 RenderObject* next = bidiNext(m_block, current.m_obj);
1987 if (next && next->parent() && !next->parent()->isDescendantOf(current.m_obj->parent()))
1988 includeEndWidth = true;
1990 currWS = current.m_obj->isReplaced() ? current.m_obj->parent()->style()->whiteSpace() : current.m_obj->style()->whiteSpace();
1991 lastWS = last->isReplaced() ? last->parent()->style()->whiteSpace() : last->style()->whiteSpace();
1993 bool autoWrap = RenderStyle::autoWrap(currWS);
1994 autoWrapWasEverTrueOnLine = autoWrapWasEverTrueOnLine || autoWrap;
1997 bool preserveNewline = current.m_obj->isSVGInlineText() ? false : RenderStyle::preserveNewline(currWS);
1999 bool preserveNewline = RenderStyle::preserveNewline(currWS);
2002 bool collapseWhiteSpace = RenderStyle::collapseWhiteSpace(currWS);
2004 if (current.m_obj->isBR()) {
2005 if (width.fitsOnLine()) {
2006 lBreak.moveToStartOf(current.m_obj);
2009 // A <br> always breaks a line, so don't let the line be collapsed
2010 // away. Also, the space at the end of a line with a <br> does not
2011 // get collapsed away. It only does this if the previous line broke
2012 // cleanly. Otherwise the <br> has no effect on whether the line is
2014 if (startingNewParagraph)
2015 lineInfo.setEmpty(false);
2016 trailingObjects.clear();
2017 lineInfo.setPreviousLineBrokeCleanly(true);
2019 if (!lineInfo.isEmpty())
2020 m_clear = current.m_obj->style()->clear();
2025 if (current.m_obj->isFloating()) {
2026 RenderBox* floatBox = toRenderBox(current.m_obj);
2027 FloatingObject* f = m_block->insertFloatingObject(floatBox);
2028 // check if it fits in the current line.
2029 // If it does, position it now, otherwise, position
2030 // it after moving to next line (in newLine() func)
2031 if (floatsFitOnLine && width.fitsOnLine(m_block->logicalWidthForFloat(f))) {
2032 m_block->positionNewFloatOnLine(f, lastFloatFromPreviousLine, width);
2033 if (lBreak.m_obj == current.m_obj) {
2034 ASSERT(!lBreak.m_pos);
2038 floatsFitOnLine = false;
2039 } else if (current.m_obj->isPositioned()) {
2040 // If our original display wasn't an inline type, then we can
2041 // go ahead and determine our static inline position now.
2042 RenderBox* box = toRenderBox(current.m_obj);
2043 bool isInlineType = box->style()->isOriginalDisplayInlineType();
2045 box->layer()->setStaticInlinePosition(m_block->borderAndPaddingStart());
2047 // If our original display was an INLINE type, then we can go ahead
2048 // and determine our static y position now.
2049 box->layer()->setStaticBlockPosition(m_block->logicalHeight());
2052 // If we're ignoring spaces, we have to stop and include this object and
2053 // then start ignoring spaces again.
2054 if (isInlineType || current.m_obj->container()->isRenderInline()) {
2055 if (ignoringSpaces) {
2056 ignoreStart.m_obj = current.m_obj;
2057 ignoreStart.m_pos = 0;
2058 addMidpoint(lineMidpointState, ignoreStart); // Stop ignoring spaces.
2059 addMidpoint(lineMidpointState, ignoreStart); // Start ignoring again.
2061 trailingObjects.appendBoxIfNeeded(box);
2063 m_positionedObjects.append(box);
2064 } else if (current.m_obj->isRenderInline()) {
2065 // Right now, we should only encounter empty inlines here.
2066 ASSERT(!current.m_obj->firstChild());
2068 RenderInline* flowBox = toRenderInline(current.m_obj);
2070 // Now that some inline flows have line boxes, if we are already ignoring spaces, we need
2071 // to make sure that we stop to include this object and then start ignoring spaces again.
2072 // If this object is at the start of the line, we need to behave like list markers and
2073 // start ignoring spaces.
2074 if (inlineFlowRequiresLineBox(flowBox)) {
2075 lineInfo.setEmpty(false);
2076 if (ignoringSpaces) {
2077 trailingObjects.clear();
2078 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, 0)); // Stop ignoring spaces.
2079 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, 0)); // Start ignoring again.
2080 } else if (m_block->style()->collapseWhiteSpace() && resolver.position().m_obj == current.m_obj
2081 && shouldSkipWhitespaceAfterStartObject(m_block, current.m_obj, lineMidpointState)) {
2082 // Like with list markers, we start ignoring spaces to make sure that any
2083 // additional spaces we see will be discarded.
2084 currentCharacterIsSpace = true;
2085 currentCharacterIsWS = true;
2086 ignoringSpaces = true;
2090 width.addUncommittedWidth(borderPaddingMarginStart(flowBox) + borderPaddingMarginEnd(flowBox));
2091 } else if (current.m_obj->isReplaced()) {
2092 RenderBox* replacedBox = toRenderBox(current.m_obj);
2094 // Break on replaced elements if either has normal white-space.
2095 if ((autoWrap || RenderStyle::autoWrap(lastWS)) && (!current.m_obj->isImage() || allowImagesToBreak)) {
2097 lBreak.moveToStartOf(current.m_obj);
2101 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, 0));
2103 lineInfo.setEmpty(false);
2104 ignoringSpaces = false;
2105 currentCharacterIsSpace = false;
2106 currentCharacterIsWS = false;
2107 trailingObjects.clear();
2109 // Optimize for a common case. If we can't find whitespace after the list
2110 // item, then this is all moot.
2111 int replacedLogicalWidth = m_block->logicalWidthForChild(replacedBox) + m_block->marginStartForChild(replacedBox) + m_block->marginEndForChild(replacedBox) + inlineLogicalWidth(current.m_obj);
2112 if (current.m_obj->isListMarker()) {
2113 if (m_block->style()->collapseWhiteSpace() && shouldSkipWhitespaceAfterStartObject(m_block, current.m_obj, lineMidpointState)) {
2114 // Like with inline flows, we start ignoring spaces to make sure that any
2115 // additional spaces we see will be discarded.
2116 currentCharacterIsSpace = true;
2117 currentCharacterIsWS = true;
2118 ignoringSpaces = true;
2120 if (toRenderListMarker(current.m_obj)->isInside())
2121 width.addUncommittedWidth(replacedLogicalWidth);
2123 width.addUncommittedWidth(replacedLogicalWidth);
2124 if (current.m_obj->isRubyRun())
2125 width.applyOverhang(toRenderRubyRun(current.m_obj), last, next);
2126 } else if (current.m_obj->isText()) {
2128 appliedStartWidth = false;
2130 RenderText* t = toRenderText(current.m_obj);
2133 bool isSVGText = t->isSVGInlineText();
2136 RenderStyle* style = t->style(lineInfo.isFirstLine());
2137 if (style->hasTextCombine() && current.m_obj->isCombineText())
2138 toRenderCombineText(current.m_obj)->combineText();
2140 const Font& f = style->font();
2141 bool isFixedPitch = f.isFixedPitch();
2142 bool canHyphenate = style->hyphens() == HyphensAuto && WebCore::canHyphenate(style->locale());
2144 int lastSpace = current.m_pos;
2145 float wordSpacing = current.m_obj->style()->wordSpacing();
2146 float lastSpaceWordSpacing = 0;
2148 // Non-zero only when kerning is enabled, in which case we measure words with their trailing
2149 // space, then subtract its width.
2150 float wordTrailingSpaceWidth = f.typesettingFeatures() & Kerning ? f.width(constructTextRun(t, f, &space, 1, style)) + wordSpacing : 0;
2152 float wrapW = width.uncommittedWidth() + inlineLogicalWidth(current.m_obj, !appliedStartWidth, true);
2153 float charWidth = 0;
2154 bool breakNBSP = autoWrap && current.m_obj->style()->nbspMode() == SPACE;
2155 // Auto-wrapping text should wrap in the middle of a word only if it could not wrap before the word,
2156 // which is only possible if the word is the first thing on the line, that is, if |w| is zero.
2157 bool breakWords = current.m_obj->style()->breakWords() && ((autoWrap && !width.committedWidth()) || currWS == PRE);
2158 bool midWordBreak = false;
2159 bool breakAll = current.m_obj->style()->wordBreak() == BreakAllWordBreak && autoWrap;
2160 float hyphenWidth = 0;
2162 if (t->isWordBreak()) {
2164 lBreak.moveToStartOf(current.m_obj);
2165 ASSERT(current.m_pos == t->textLength());
2168 for (; current.m_pos < t->textLength(); current.fastIncrementInTextNode()) {
2169 bool previousCharacterIsSpace = currentCharacterIsSpace;
2170 bool previousCharacterIsWS = currentCharacterIsWS;
2171 UChar c = current.current();
2172 currentCharacterIsSpace = c == ' ' || c == '\t' || (!preserveNewline && (c == '\n'));
2174 if (!collapseWhiteSpace || !currentCharacterIsSpace)
2175 lineInfo.setEmpty(false);
2177 if (c == softHyphen && autoWrap && !hyphenWidth && style->hyphens() != HyphensNone) {
2178 const AtomicString& hyphenString = style->hyphenString();
2179 hyphenWidth = f.width(constructTextRun(t, f, hyphenString.string(), current.m_obj->style()));
2180 width.addUncommittedWidth(hyphenWidth);
2183 bool applyWordSpacing = false;
2185 currentCharacterIsWS = currentCharacterIsSpace || (breakNBSP && c == noBreakSpace);
2187 bool midWordBreakIsBeforeSurrogatePair = false;
2188 if ((breakAll || breakWords) && !midWordBreak) {
2190 midWordBreakIsBeforeSurrogatePair = U16_IS_LEAD(c) && current.m_pos + 1 < t->textLength() && U16_IS_TRAIL(t->characters()[current.m_pos + 1]);
2191 charWidth = textWidth(t, current.m_pos, midWordBreakIsBeforeSurrogatePair ? 2 : 1, f, width.committedWidth() + wrapW, isFixedPitch, collapseWhiteSpace);
2192 midWordBreak = width.committedWidth() + wrapW + charWidth > width.availableWidth();
2195 if (lineBreakIteratorInfo.first != t) {
2196 lineBreakIteratorInfo.first = t;
2197 lineBreakIteratorInfo.second.reset(t->characters(), t->textLength(), style->locale());
2200 bool betweenWords = c == '\n' || (currWS != PRE && !atStart && isBreakable(lineBreakIteratorInfo.second, current.m_pos, current.m_nextBreakablePosition, breakNBSP)
2201 && (style->hyphens() != HyphensNone || (current.previousInSameNode() != softHyphen)));
2203 if (betweenWords || midWordBreak) {
2204 bool stoppedIgnoringSpaces = false;
2205 if (ignoringSpaces) {
2206 if (!currentCharacterIsSpace) {
2207 // Stop ignoring spaces and begin at this
2209 ignoringSpaces = false;
2210 lastSpaceWordSpacing = 0;
2211 lastSpace = current.m_pos; // e.g., "Foo goo", don't add in any of the ignored spaces.
2212 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos));
2213 stoppedIgnoringSpaces = true;
2215 // Just keep ignoring these spaces.
2220 float additionalTmpW;
2221 if (wordTrailingSpaceWidth && currentCharacterIsSpace)
2222 additionalTmpW = textWidth(t, lastSpace, current.m_pos + 1 - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) - wordTrailingSpaceWidth + lastSpaceWordSpacing;
2224 additionalTmpW = textWidth(t, lastSpace, current.m_pos - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing;
2225 width.addUncommittedWidth(additionalTmpW);
2226 if (!appliedStartWidth) {
2227 width.addUncommittedWidth(inlineLogicalWidth(current.m_obj, true, false));
2228 appliedStartWidth = true;
2231 applyWordSpacing = wordSpacing && currentCharacterIsSpace && !previousCharacterIsSpace;
2233 if (!width.committedWidth() && autoWrap && !width.fitsOnLine())
2234 width.fitBelowFloats();
2236 if (autoWrap || breakWords) {
2237 // If we break only after white-space, consider the current character
2238 // as candidate width for this line.
2239 bool lineWasTooWide = false;
2240 if (width.fitsOnLine() && currentCharacterIsWS && current.m_obj->style()->breakOnlyAfterWhiteSpace() && !midWordBreak) {
2241 float charWidth = textWidth(t, current.m_pos, 1, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) + (applyWordSpacing ? wordSpacing : 0);
2242 // Check if line is too big even without the extra space
2243 // at the end of the line. If it is not, do nothing.
2244 // If the line needs the extra whitespace to be too long,
2245 // then move the line break to the space and skip all
2246 // additional whitespace.
2247 if (!width.fitsOnLine(charWidth)) {
2248 lineWasTooWide = true;
2249 lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2250 skipTrailingWhitespace(lBreak, lineInfo);
2253 if (lineWasTooWide || !width.fitsOnLine()) {
2254 if (canHyphenate && !width.fitsOnLine()) {
2255 tryHyphenating(t, f, style->locale(), style->hyphenationLimitBefore(), style->hyphenationLimitAfter(), lastSpace, current.m_pos, width.currentWidth() - additionalTmpW, width.availableWidth(), isFixedPitch, collapseWhiteSpace, lastSpaceWordSpacing, lBreak, current.m_nextBreakablePosition, m_hyphenated);
2259 if (lBreak.atTextParagraphSeparator()) {
2260 if (!stoppedIgnoringSpaces && current.m_pos > 0) {
2261 // We need to stop right before the newline and then start up again.
2262 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos - 1)); // Stop
2263 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos)); // Start
2266 lineInfo.setPreviousLineBrokeCleanly(true);
2268 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)
2269 m_hyphenated = true;
2270 goto end; // Didn't fit. Jump to the end.
2272 if (!betweenWords || (midWordBreak && !autoWrap))
2273 width.addUncommittedWidth(-additionalTmpW);
2275 // Subtract the width of the soft hyphen out since we fit on a line.
2276 width.addUncommittedWidth(-hyphenWidth);
2282 if (c == '\n' && preserveNewline) {
2283 if (!stoppedIgnoringSpaces && current.m_pos > 0) {
2284 // We need to stop right before the newline and then start up again.
2285 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos - 1)); // Stop
2286 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos)); // Start
2288 lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2290 lineInfo.setPreviousLineBrokeCleanly(true);
2294 if (autoWrap && betweenWords) {
2297 lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2298 // Auto-wrapping text should not wrap in the middle of a word once it has had an
2299 // opportunity to break after a word.
2304 // Remember this as a breakable position in case
2305 // adding the end width forces a break.
2306 lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2307 midWordBreak &= (breakWords || breakAll);
2308 if (midWordBreakIsBeforeSurrogatePair)
2309 current.fastIncrementInTextNode();
2313 lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
2314 lastSpace = current.m_pos;
2317 if (!ignoringSpaces && current.m_obj->style()->collapseWhiteSpace()) {
2318 // If we encounter a newline, or if we encounter a
2319 // second space, we need to go ahead and break up this
2320 // run and enter a mode where we start collapsing spaces.
2321 if (currentCharacterIsSpace && previousCharacterIsSpace) {
2322 ignoringSpaces = true;
2324 // We just entered a mode where we are ignoring
2325 // spaces. Create a midpoint to terminate the run
2326 // before the second space.
2327 addMidpoint(lineMidpointState, ignoreStart);
2328 trailingObjects.updateMidpointsForTrailingBoxes(lineMidpointState, InlineIterator(), TrailingObjects::DoNotCollapseFirstSpace);
2331 } else if (ignoringSpaces) {
2332 // Stop ignoring spaces and begin at this
2334 ignoringSpaces = false;
2335 lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
2336 lastSpace = current.m_pos; // e.g., "Foo goo", don't add in any of the ignored spaces.
2337 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos));
2341 if (isSVGText && current.m_pos > 0) {
2342 // Force creation of new InlineBoxes for each absolute positioned character (those that start new text chunks).
2343 if (toRenderSVGInlineText(t)->characterStartsNewTextChunk(current.m_pos)) {
2344 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos - 1));
2345 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos));
2350 if (currentCharacterIsSpace && !previousCharacterIsSpace) {
2351 ignoreStart.m_obj = current.m_obj;
2352 ignoreStart.m_pos = current.m_pos;
2355 if (!currentCharacterIsWS && previousCharacterIsWS) {
2356 if (autoWrap && current.m_obj->style()->breakOnlyAfterWhiteSpace())
2357 lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2360 if (collapseWhiteSpace && currentCharacterIsSpace && !ignoringSpaces)
2361 trailingObjects.setTrailingWhitespace(toRenderText(current.m_obj));
2362 else if (!current.m_obj->style()->collapseWhiteSpace() || !currentCharacterIsSpace)
2363 trailingObjects.clear();
2368 // IMPORTANT: current.m_pos is > length here!
2369 float additionalTmpW = ignoringSpaces ? 0 : textWidth(t, lastSpace, current.m_pos - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing;
2370 width.addUncommittedWidth(additionalTmpW + inlineLogicalWidth(current.m_obj, !appliedStartWidth, includeEndWidth));
2371 includeEndWidth = false;
2373 if (!width.fitsOnLine()) {
2375 tryHyphenating(t, f, style->locale(), style->hyphenationLimitBefore(), style->hyphenationLimitAfter(), lastSpace, current.m_pos, width.currentWidth() - additionalTmpW, width.availableWidth(), isFixedPitch, collapseWhiteSpace, lastSpaceWordSpacing, lBreak, current.m_nextBreakablePosition, m_hyphenated);
2377 if (!m_hyphenated && lBreak.previousInSameNode() == softHyphen && style->hyphens() != HyphensNone)
2378 m_hyphenated = true;
2384 ASSERT_NOT_REACHED();
2386 bool checkForBreak = autoWrap;
2387 if (width.committedWidth() && !width.fitsOnLine() && lBreak.m_obj && currWS == NOWRAP)
2388 checkForBreak = true;
2389 else if (next && current.m_obj->isText() && next->isText() && !next->isBR() && (autoWrap || (next->style()->autoWrap()))) {
2390 if (currentCharacterIsSpace)
2391 checkForBreak = true;
2393 RenderText* nextText = toRenderText(next);
2394 if (nextText->textLength()) {
2395 UChar c = nextText->characters()[0];
2396 checkForBreak = (c == ' ' || c == '\t' || (c == '\n' && !next->preservesNewline()));
2397 // If the next item on the line is text, and if we did not end with
2398 // a space, then the next text run continues our word (and so it needs to
2399 // keep adding to |tmpW|. Just update and continue.
2400 } else if (nextText->isWordBreak())
2401 checkForBreak = true;
2403 if (!width.fitsOnLine() && !width.committedWidth())
2404 width.fitBelowFloats();
2406 bool canPlaceOnLine = width.fitsOnLine() || !autoWrapWasEverTrueOnLine;
2407 if (canPlaceOnLine && checkForBreak) {
2409 lBreak.moveToStartOf(next);
2414 if (checkForBreak && !width.fitsOnLine()) {
2415 // if we have floats, try to get below them.
2416 if (currentCharacterIsSpace && !ignoringSpaces && current.m_obj->style()->collapseWhiteSpace())
2417 trailingObjects.clear();
2419 if (width.committedWidth())
2422 width.fitBelowFloats();
2424 // |width| may have been adjusted because we got shoved down past a float (thus
2425 // giving us more room), so we need to retest, and only jump to
2426 // the end label if we still don't fit on the line. -dwh
2427 if (!width.fitsOnLine())
2431 if (!current.m_obj->isFloatingOrPositioned()) {
2432 last = current.m_obj;
2433 if (last->isReplaced() && autoWrap && (!last->isImage() || allowImagesToBreak) && (!last->isListMarker() || toRenderListMarker(last)->isInside())) {
2435 lBreak.moveToStartOf(next);
2439 // Clear out our character space bool, since inline <pre>s don't collapse whitespace
2440 // with adjacent inline normal/nowrap spans.
2441 if (!collapseWhiteSpace)
2442 currentCharacterIsSpace = false;
2444 current.moveToStartOf(next);
2448 if (width.fitsOnLine() || lastWS == NOWRAP)
2452 if (lBreak == resolver.position() && (!lBreak.m_obj || !lBreak.m_obj->isBR())) {
2453 // we just add as much as possible
2454 if (m_block->style()->whiteSpace() == PRE) {
2455 // FIXME: Don't really understand this case.
2456 if (current.m_pos) {
2457 // FIXME: This should call moveTo which would clear m_nextBreakablePosition
2458 // this code as-is is likely wrong.
2459 lBreak.m_obj = current.m_obj;
2460 lBreak.m_pos = current.m_pos - 1;
2462 lBreak.moveTo(last, last->isText() ? last->length() : 0);
2463 } else if (lBreak.m_obj) {
2464 // Don't ever break in the middle of a word if we can help it.
2465 // There's no room at all. We just have to be on this line,
2466 // even though we'll spill out.
2467 lBreak.moveTo(current.m_obj, current.m_pos);
2471 // make sure we consume at least one char/object.
2472 if (lBreak == resolver.position())
2475 // Sanity check our midpoints.
2476 checkMidpoints(lineMidpointState, lBreak);
2478 trailingObjects.updateMidpointsForTrailingBoxes(lineMidpointState, lBreak, TrailingObjects::CollapseFirstSpace);
2480 // We might have made lBreak an iterator that points past the end
2481 // of the object. Do this adjustment to make it point to the start
2482 // of the next object instead to avoid confusing the rest of the
2484 if (lBreak.m_pos > 0) {
2492 void RenderBlock::addOverflowFromInlineChildren()
2494 int endPadding = hasOverflowClip() ? paddingEnd() : 0;
2495 // FIXME: Need to find another way to do this, since scrollbars could show when we don't want them to.
2496 if (hasOverflowClip() && !endPadding && node() && node()->rendererIsEditable() && node() == node()->rootEditableElement() && style()->isLeftToRightDirection())
2498 for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
2499 addLayoutOverflow(curr->paddedLayoutOverflowRect(endPadding));
2500 if (!hasOverflowClip())
2501 addVisualOverflow(curr->visualOverflowRect(curr->lineTop(), curr->lineBottom()));
2505 void RenderBlock::deleteEllipsisLineBoxes()
2507 for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox())
2508 curr->clearTruncation();
2511 void RenderBlock::checkLinesForTextOverflow()
2513 // Determine the width of the ellipsis using the current font.
2514 // FIXME: CSS3 says this is configurable, also need to use 0x002E (FULL STOP) if horizontal ellipsis is "not renderable"
2515 const Font& font = style()->font();
2516 DEFINE_STATIC_LOCAL(AtomicString, ellipsisStr, (&horizontalEllipsis, 1));
2517 const Font& firstLineFont = firstLineStyle()->font();
2518 int firstLineEllipsisWidth = firstLineFont.width(constructTextRun(this, firstLineFont, &horizontalEllipsis, 1, firstLineStyle()));
2519 int ellipsisWidth = (font == firstLineFont) ? firstLineEllipsisWidth : font.width(constructTextRun(this, font, &horizontalEllipsis, 1, style()));
2521 // For LTR text truncation, we want to get the right edge of our padding box, and then we want to see
2522 // if the right edge of a line box exceeds that. For RTL, we use the left edge of the padding box and
2523 // check the left edge of the line box to see if it is less
2524 // Include the scrollbar for overflow blocks, which means we want to use "contentWidth()"
2525 bool ltr = style()->isLeftToRightDirection();
2526 for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
2527 int blockRightEdge = logicalRightOffsetForLine(curr->y(), curr == firstRootBox());
2528 int blockLeftEdge = logicalLeftOffsetForLine(curr->y(), curr == firstRootBox());
2529 int lineBoxEdge = ltr ? curr->x() + curr->logicalWidth() : curr->x();
2530 if ((ltr && lineBoxEdge > blockRightEdge) || (!ltr && lineBoxEdge < blockLeftEdge)) {
2531 // This line spills out of our box in the appropriate direction. Now we need to see if the line
2532 // can be truncated. In order for truncation to be possible, the line must have sufficient space to
2533 // accommodate our truncation string, and no replaced elements (images, tables) can overlap the ellipsis
2535 int width = curr == firstRootBox() ? firstLineEllipsisWidth : ellipsisWidth;
2536 int blockEdge = ltr ? blockRightEdge : blockLeftEdge;
2537 if (curr->lineCanAccommodateEllipsis(ltr, blockEdge, lineBoxEdge, width))
2538 curr->placeEllipsis(ellipsisStr, ltr, blockLeftEdge, blockRightEdge, width);
2543 bool RenderBlock::positionNewFloatOnLine(FloatingObject* newFloat, FloatingObject* lastFloatFromPreviousLine, LineWidth& width)
2545 if (!positionNewFloats())
2548 width.shrinkAvailableWidthForNewFloatIfNeeded(newFloat);
2550 if (!newFloat->m_paginationStrut)
2553 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2554 ASSERT(floatingObjectSet.last() == newFloat);
2556 int floatLogicalTop = logicalTopForFloat(newFloat);
2557 int paginationStrut = newFloat->m_paginationStrut;
2559 if (floatLogicalTop - paginationStrut != logicalHeight())
2562 FloatingObjectSetIterator it = floatingObjectSet.end();
2563 --it; // Last float is newFloat, skip that one.
2564 FloatingObjectSetIterator begin = floatingObjectSet.begin();
2565 while (it != begin) {
2567 FloatingObject* f = *it;
2568 if (f == lastFloatFromPreviousLine)
2570 if (logicalTopForFloat(f) == logicalHeight()) {
2571 ASSERT(!f->m_paginationStrut);
2572 f->m_paginationStrut = paginationStrut;
2573 RenderBox* o = f->m_renderer;
2574 setLogicalTopForChild(o, logicalTopForChild(o) + marginBeforeForChild(o) + paginationStrut);
2575 if (o->isRenderBlock())
2576 toRenderBlock(o)->setChildNeedsLayout(true, false);
2577 o->layoutIfNeeded();
2578 // Save the old logical top before calling removePlacedObject which will set
2579 // isPlaced to false. Otherwise it will trigger an assert in logicalTopForFloat.
2580 LayoutUnit oldLogicalTop = logicalTopForFloat(f);
2581 m_floatingObjects->removePlacedObject(f);
2582 setLogicalTopForFloat(f, oldLogicalTop + f->m_paginationStrut);
2583 m_floatingObjects->addPlacedObject(f);
2587 setLogicalHeight(logicalHeight() + paginationStrut);
2588 width.updateAvailableWidth();