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 "RenderFlowThread.h"
33 #include "RenderInline.h"
34 #include "RenderLayer.h"
35 #include "RenderListMarker.h"
36 #include "RenderRubyRun.h"
37 #include "RenderView.h"
39 #include "TextBreakIterator.h"
40 #include "TrailingFloatsRootInlineBox.h"
41 #include "VerticalPositionCache.h"
42 #include "break_lines.h"
43 #include <wtf/AlwaysInline.h>
44 #include <wtf/RefCountedLeakCounter.h>
45 #include <wtf/StdLibExtras.h>
46 #include <wtf/Vector.h>
47 #include <wtf/unicode/CharacterNames.h>
50 #include "RenderSVGInlineText.h"
51 #include "SVGRootInlineBox.h"
56 using namespace Unicode;
60 // We don't let our line box tree for a single line get any deeper than this.
61 const unsigned cMaxLineDepth = 200;
65 LineWidth(RenderBlock* block, bool isFirstLine)
67 , m_uncommittedWidth(0)
73 , m_isFirstLine(isFirstLine)
76 updateAvailableWidth();
78 bool fitsOnLine() const { return currentWidth() <= m_availableWidth; }
79 bool fitsOnLine(float extra) const { return currentWidth() + extra <= m_availableWidth; }
80 float currentWidth() const { return m_committedWidth + m_uncommittedWidth; }
82 // FIXME: We should eventually replace these three functions by ones that work on a higher abstraction.
83 float uncommittedWidth() const { return m_uncommittedWidth; }
84 float committedWidth() const { return m_committedWidth; }
85 float availableWidth() const { return m_availableWidth; }
87 void updateAvailableWidth();
88 void shrinkAvailableWidthForNewFloatIfNeeded(RenderBlock::FloatingObject*);
89 void addUncommittedWidth(float delta) { m_uncommittedWidth += delta; }
92 m_committedWidth += m_uncommittedWidth;
93 m_uncommittedWidth = 0;
95 void applyOverhang(RenderRubyRun*, RenderObject* startRenderer, RenderObject* endRenderer);
96 void fitBelowFloats();
99 void computeAvailableWidthFromLeftAndRight()
101 m_availableWidth = max(0.0f, m_right - m_left) + m_overhangWidth;
105 RenderBlock* m_block;
106 float m_uncommittedWidth;
107 float m_committedWidth;
108 float m_overhangWidth; // The amount by which |m_availableWidth| has been inflated to account for possible contraction due to ruby overhang.
111 float m_availableWidth;
115 static LayoutUnit logicalHeightForLine(RenderBlock* block)
117 InlineFlowBox* lineBox = block->firstRootBox();
118 LayoutUnit logicalHeight = 0;
120 return logicalHeight;
122 if (lineBox->firstChild() && lineBox->firstChild()->renderer() && lineBox->firstChild()->renderer()->isRenderBlock())
123 logicalHeight = toRenderBlock(lineBox->firstChild()->renderer())->logicalHeight();
125 logicalHeight = lineBox->height();
126 return logicalHeight;
129 inline void LineWidth::updateAvailableWidth()
131 LayoutUnit height = m_block->logicalHeight();
132 LayoutUnit logicalHeight = logicalHeightForLine(m_block);
133 m_left = m_block->logicalLeftOffsetForLine(height, m_isFirstLine, logicalHeight);
134 m_right = m_block->logicalRightOffsetForLine(height, m_isFirstLine, logicalHeight);
136 computeAvailableWidthFromLeftAndRight();
139 inline void LineWidth::shrinkAvailableWidthForNewFloatIfNeeded(RenderBlock::FloatingObject* newFloat)
141 LayoutUnit height = m_block->logicalHeight();
142 if (height < m_block->logicalTopForFloat(newFloat) || height >= m_block->logicalBottomForFloat(newFloat))
145 if (newFloat->type() == RenderBlock::FloatingObject::FloatLeft) {
146 m_left = m_block->pixelSnappedLogicalRightForFloat(newFloat);
147 if (m_isFirstLine && m_block->style()->isLeftToRightDirection())
148 m_left += floorToInt(m_block->textIndentOffset());
150 m_right = m_block->pixelSnappedLogicalLeftForFloat(newFloat);
151 if (m_isFirstLine && !m_block->style()->isLeftToRightDirection())
152 m_right -= floorToInt(m_block->textIndentOffset());
155 computeAvailableWidthFromLeftAndRight();
158 void LineWidth::applyOverhang(RenderRubyRun* rubyRun, RenderObject* startRenderer, RenderObject* endRenderer)
162 rubyRun->getOverhang(m_isFirstLine, startRenderer, endRenderer, startOverhang, endOverhang);
164 startOverhang = min<int>(startOverhang, m_committedWidth);
165 m_availableWidth += startOverhang;
167 endOverhang = max(min<int>(endOverhang, m_availableWidth - currentWidth()), 0);
168 m_availableWidth += endOverhang;
169 m_overhangWidth += startOverhang + endOverhang;
172 void LineWidth::fitBelowFloats()
174 ASSERT(!m_committedWidth);
175 ASSERT(!fitsOnLine());
177 LayoutUnit floatLogicalBottom;
178 LayoutUnit lastFloatLogicalBottom = m_block->logicalHeight();
179 float newLineWidth = m_availableWidth;
180 float newLineLeft = m_left;
181 float newLineRight = m_right;
183 floatLogicalBottom = m_block->nextFloatLogicalBottomBelow(lastFloatLogicalBottom);
184 if (floatLogicalBottom <= lastFloatLogicalBottom)
187 newLineLeft = m_block->logicalLeftOffsetForLine(floatLogicalBottom, m_isFirstLine);
188 newLineRight = m_block->logicalRightOffsetForLine(floatLogicalBottom, m_isFirstLine);
189 newLineWidth = max(0.0f, newLineRight - newLineLeft);
190 lastFloatLogicalBottom = floatLogicalBottom;
191 if (newLineWidth >= m_uncommittedWidth)
195 if (newLineWidth > m_availableWidth) {
196 m_block->setLogicalHeight(lastFloatLogicalBottom);
197 m_availableWidth = newLineWidth + m_overhangWidth;
198 m_left = newLineLeft;
199 m_right = newLineRight;
206 : m_isFirstLine(true)
207 , m_isLastLine(false)
209 , m_previousLineBrokeCleanly(true)
210 , m_floatPaginationStrut(0)
211 , m_runsFromLeadingWhitespace(0)
214 bool isFirstLine() const { return m_isFirstLine; }
215 bool isLastLine() const { return m_isLastLine; }
216 bool isEmpty() const { return m_isEmpty; }
217 bool previousLineBrokeCleanly() const { return m_previousLineBrokeCleanly; }
218 LayoutUnit floatPaginationStrut() const { return m_floatPaginationStrut; }
219 unsigned runsFromLeadingWhitespace() const { return m_runsFromLeadingWhitespace; }
220 void resetRunsFromLeadingWhitespace() { m_runsFromLeadingWhitespace = 0; }
221 void incrementRunsFromLeadingWhitespace() { m_runsFromLeadingWhitespace++; }
223 void setFirstLine(bool firstLine) { m_isFirstLine = firstLine; }
224 void setLastLine(bool lastLine) { m_isLastLine = lastLine; }
225 void setEmpty(bool empty, RenderBlock* block = 0, LineWidth* lineWidth = 0)
227 if (m_isEmpty == empty)
230 if (!empty && block && floatPaginationStrut()) {
231 block->setLogicalHeight(block->logicalHeight() + floatPaginationStrut());
232 setFloatPaginationStrut(0);
233 lineWidth->updateAvailableWidth();
237 void setPreviousLineBrokeCleanly(bool previousLineBrokeCleanly) { m_previousLineBrokeCleanly = previousLineBrokeCleanly; }
238 void setFloatPaginationStrut(LayoutUnit strut) { m_floatPaginationStrut = strut; }
244 bool m_previousLineBrokeCleanly;
245 LayoutUnit m_floatPaginationStrut;
246 unsigned m_runsFromLeadingWhitespace;
249 static inline LayoutUnit borderPaddingMarginStart(RenderInline* child)
251 return child->marginStart() + child->paddingStart() + child->borderStart();
254 static inline LayoutUnit borderPaddingMarginEnd(RenderInline* child)
256 return child->marginEnd() + child->paddingEnd() + child->borderEnd();
259 static LayoutUnit inlineLogicalWidth(RenderObject* child, bool start = true, bool end = true)
261 unsigned lineDepth = 1;
262 LayoutUnit extraWidth = 0;
263 RenderObject* parent = child->parent();
264 while (parent->isRenderInline() && lineDepth++ < cMaxLineDepth) {
265 RenderInline* parentAsRenderInline = toRenderInline(parent);
266 if (start && !child->previousSibling())
267 extraWidth += borderPaddingMarginStart(parentAsRenderInline);
268 if (end && !child->nextSibling())
269 extraWidth += borderPaddingMarginEnd(parentAsRenderInline);
271 parent = child->parent();
276 static void determineDirectionality(TextDirection& dir, InlineIterator iter)
278 while (!iter.atEnd()) {
279 if (iter.atParagraphSeparator())
281 if (UChar current = iter.current()) {
282 Direction charDirection = direction(current);
283 if (charDirection == LeftToRight) {
287 if (charDirection == RightToLeft || charDirection == RightToLeftArabic) {
296 static void checkMidpoints(LineMidpointState& lineMidpointState, InlineIterator& lBreak)
298 // Check to see if our last midpoint is a start point beyond the line break. If so,
299 // shave it off the list, and shave off a trailing space if the previous end point doesn't
300 // preserve whitespace.
301 if (lBreak.m_obj && lineMidpointState.numMidpoints && !(lineMidpointState.numMidpoints % 2)) {
302 InlineIterator* midpoints = lineMidpointState.midpoints.data();
303 InlineIterator& endpoint = midpoints[lineMidpointState.numMidpoints - 2];
304 const InlineIterator& startpoint = midpoints[lineMidpointState.numMidpoints - 1];
305 InlineIterator currpoint = endpoint;
306 while (!currpoint.atEnd() && currpoint != startpoint && currpoint != lBreak)
307 currpoint.increment();
308 if (currpoint == lBreak) {
309 // We hit the line break before the start point. Shave off the start point.
310 lineMidpointState.numMidpoints--;
311 if (endpoint.m_obj->style()->collapseWhiteSpace())
317 static void addMidpoint(LineMidpointState& lineMidpointState, const InlineIterator& midpoint)
319 if (lineMidpointState.midpoints.size() <= lineMidpointState.numMidpoints)
320 lineMidpointState.midpoints.grow(lineMidpointState.numMidpoints + 10);
322 InlineIterator* midpoints = lineMidpointState.midpoints.data();
323 midpoints[lineMidpointState.numMidpoints++] = midpoint;
326 static inline BidiRun* createRun(int start, int end, RenderObject* obj, InlineBidiResolver& resolver)
328 return new (obj->renderArena()) BidiRun(start, end, obj, resolver.context(), resolver.dir());
331 void RenderBlock::appendRunsForObject(BidiRunList<BidiRun>& runs, int start, int end, RenderObject* obj, InlineBidiResolver& resolver)
333 if (start > end || shouldSkipCreatingRunsForObject(obj))
336 LineMidpointState& lineMidpointState = resolver.midpointState();
337 bool haveNextMidpoint = (lineMidpointState.currentMidpoint < lineMidpointState.numMidpoints);
338 InlineIterator nextMidpoint;
339 if (haveNextMidpoint)
340 nextMidpoint = lineMidpointState.midpoints[lineMidpointState.currentMidpoint];
341 if (lineMidpointState.betweenMidpoints) {
342 if (!(haveNextMidpoint && nextMidpoint.m_obj == obj))
344 // This is a new start point. Stop ignoring objects and
346 lineMidpointState.betweenMidpoints = false;
347 start = nextMidpoint.m_pos;
348 lineMidpointState.currentMidpoint++;
350 return appendRunsForObject(runs, start, end, obj, resolver);
352 if (!haveNextMidpoint || (obj != nextMidpoint.m_obj)) {
353 runs.addRun(createRun(start, end, obj, resolver));
357 // An end midpoint has been encountered within our object. We
358 // need to go ahead and append a run with our endpoint.
359 if (static_cast<int>(nextMidpoint.m_pos + 1) <= end) {
360 lineMidpointState.betweenMidpoints = true;
361 lineMidpointState.currentMidpoint++;
362 if (nextMidpoint.m_pos != UINT_MAX) { // UINT_MAX means stop at the object and don't include any of it.
363 if (static_cast<int>(nextMidpoint.m_pos + 1) > start)
364 runs.addRun(createRun(start, nextMidpoint.m_pos + 1, obj, resolver));
365 return appendRunsForObject(runs, nextMidpoint.m_pos + 1, end, obj, resolver);
368 runs.addRun(createRun(start, end, obj, resolver));
372 static inline InlineBox* createInlineBoxForRenderer(RenderObject* obj, bool isRootLineBox, bool isOnlyRun = false)
375 return toRenderBlock(obj)->createAndAppendRootInlineBox();
378 InlineTextBox* textBox = toRenderText(obj)->createInlineTextBox();
379 // We only treat a box as text for a <br> if we are on a line by ourself or in strict mode
380 // (Note the use of strict mode. In "almost strict" mode, we don't treat the box for <br> as text.)
382 textBox->setIsText(isOnlyRun || obj->document()->inNoQuirksMode());
387 return toRenderBox(obj)->createInlineBox();
389 return toRenderInline(obj)->createAndAppendInlineFlowBox();
392 static inline void dirtyLineBoxesForRenderer(RenderObject* o, bool fullLayout)
395 if (o->preferredLogicalWidthsDirty() && (o->isCounter() || o->isQuote()))
396 toRenderText(o)->computePreferredLogicalWidths(0); // FIXME: Counters depend on this hack. No clue why. Should be investigated and removed.
397 toRenderText(o)->dirtyLineBoxes(fullLayout);
399 toRenderInline(o)->dirtyLineBoxes(fullLayout);
402 static bool parentIsConstructedOrHaveNext(InlineFlowBox* parentBox)
405 if (parentBox->isConstructed() || parentBox->nextOnLine())
407 parentBox = parentBox->parent();
412 InlineFlowBox* RenderBlock::createLineBoxes(RenderObject* obj, const LineInfo& lineInfo, InlineBox* childBox)
414 // See if we have an unconstructed line box for this object that is also
415 // the last item on the line.
416 unsigned lineDepth = 1;
417 InlineFlowBox* parentBox = 0;
418 InlineFlowBox* result = 0;
419 bool hasDefaultLineBoxContain = style()->lineBoxContain() == RenderStyle::initialLineBoxContain();
421 ASSERT(obj->isRenderInline() || obj == this);
423 RenderInline* inlineFlow = (obj != this) ? toRenderInline(obj) : 0;
425 // Get the last box we made for this render object.
426 parentBox = inlineFlow ? inlineFlow->lastLineBox() : toRenderBlock(obj)->lastLineBox();
428 // If this box or its ancestor is constructed then it is from a previous line, and we need
429 // to make a new box for our line. If this box or its ancestor is unconstructed but it has
430 // something following it on the line, then we know we have to make a new box
431 // as well. In this situation our inline has actually been split in two on
432 // the same line (this can happen with very fancy language mixtures).
433 bool constructedNewBox = false;
434 bool allowedToConstructNewBox = !hasDefaultLineBoxContain || !inlineFlow || inlineFlow->alwaysCreateLineBoxes();
435 bool canUseExistingParentBox = parentBox && !parentIsConstructedOrHaveNext(parentBox);
436 if (allowedToConstructNewBox && !canUseExistingParentBox) {
437 // We need to make a new box for this render object. Once
438 // made, we need to place it at the end of the current line.
439 InlineBox* newBox = createInlineBoxForRenderer(obj, obj == this);
440 ASSERT(newBox->isInlineFlowBox());
441 parentBox = toInlineFlowBox(newBox);
442 parentBox->setFirstLineStyleBit(lineInfo.isFirstLine());
443 parentBox->setIsHorizontal(isHorizontalWritingMode());
444 if (!hasDefaultLineBoxContain)
445 parentBox->clearDescendantsHaveSameLineHeightAndBaseline();
446 constructedNewBox = true;
449 if (constructedNewBox || canUseExistingParentBox) {
453 // If we have hit the block itself, then |box| represents the root
454 // inline box for the line, and it doesn't have to be appended to any parent
457 parentBox->addToLine(childBox);
459 if (!constructedNewBox || obj == this)
462 childBox = parentBox;
465 // If we've exceeded our line depth, then jump straight to the root and skip all the remaining
466 // intermediate inline flows.
467 obj = (++lineDepth >= cMaxLineDepth) ? this : obj->parent();
474 static bool reachedEndOfTextRenderer(const BidiRunList<BidiRun>& bidiRuns)
476 BidiRun* run = bidiRuns.logicallyLastRun();
479 unsigned int pos = run->stop();
480 RenderObject* r = run->m_object;
481 if (!r->isText() || r->isBR())
483 RenderText* renderText = toRenderText(r);
484 if (pos >= renderText->textLength())
487 while (isASCIISpace(renderText->characters()[pos])) {
489 if (pos >= renderText->textLength())
495 RootInlineBox* RenderBlock::constructLine(BidiRunList<BidiRun>& bidiRuns, const LineInfo& lineInfo)
497 ASSERT(bidiRuns.firstRun());
499 bool rootHasSelectedChildren = false;
500 InlineFlowBox* parentBox = 0;
501 int runCount = bidiRuns.runCount() - lineInfo.runsFromLeadingWhitespace();
502 for (BidiRun* r = bidiRuns.firstRun(); r; r = r->next()) {
503 // Create a box for our object.
504 bool isOnlyRun = (runCount == 1);
505 if (runCount == 2 && !r->m_object->isListMarker())
506 isOnlyRun = (!style()->isLeftToRightDirection() ? bidiRuns.lastRun() : bidiRuns.firstRun())->m_object->isListMarker();
508 if (lineInfo.isEmpty())
511 InlineBox* box = createInlineBoxForRenderer(r->m_object, false, isOnlyRun);
518 if (!rootHasSelectedChildren && box->renderer()->selectionState() != RenderObject::SelectionNone)
519 rootHasSelectedChildren = true;
521 // If we have no parent box yet, or if the run is not simply a sibling,
522 // then we need to construct inline boxes as necessary to properly enclose the
524 if (!parentBox || parentBox->renderer() != r->m_object->parent())
525 // Create new inline boxes all the way back to the appropriate insertion point.
526 parentBox = createLineBoxes(r->m_object->parent(), lineInfo, box);
528 // Append the inline box to this line.
529 parentBox->addToLine(box);
532 bool visuallyOrdered = r->m_object->style()->rtlOrdering() == VisualOrder;
533 box->setBidiLevel(r->level());
535 if (box->isInlineTextBox()) {
536 InlineTextBox* text = toInlineTextBox(box);
537 text->setStart(r->m_start);
538 text->setLen(r->m_stop - r->m_start);
539 text->setDirOverride(r->dirOverride(visuallyOrdered));
541 text->setHasHyphen(true);
545 // We should have a root inline box. It should be unconstructed and
546 // be the last continuation of our line list.
547 ASSERT(lastLineBox() && !lastLineBox()->isConstructed());
549 // Set the m_selectedChildren flag on the root inline box if one of the leaf inline box
550 // from the bidi runs walk above has a selection state.
551 if (rootHasSelectedChildren)
552 lastLineBox()->root()->setHasSelectedChildren(true);
554 // Set bits on our inline flow boxes that indicate which sides should
555 // paint borders/margins/padding. This knowledge will ultimately be used when
556 // we determine the horizontal positions and widths of all the inline boxes on
558 bool isLogicallyLastRunWrapped = bidiRuns.logicallyLastRun()->m_object && bidiRuns.logicallyLastRun()->m_object->isText() ? !reachedEndOfTextRenderer(bidiRuns) : true;
559 lastLineBox()->determineSpacingForFlowBoxes(lineInfo.isLastLine(), isLogicallyLastRunWrapped, bidiRuns.logicallyLastRun()->m_object);
561 // Now mark the line boxes as being constructed.
562 lastLineBox()->setConstructed();
564 // Return the last line.
565 return lastRootBox();
568 ETextAlign RenderBlock::textAlignmentForLine(bool endsWithSoftBreak) const
570 ETextAlign alignment = style()->textAlign();
571 #if ENABLE(TIZEN_CSS3_TEXT)
572 ETextAlignLast alignmentLast = style()->textAlignLast();
574 if (!endsWithSoftBreak) {
575 switch (alignmentLast) {
576 case TextAlignLastStart:
578 case TextAlignLastEnd:
580 case TextAlignLastLeft:
582 case TextAlignLastRight:
584 case TextAlignLastCenter:
586 case TextAlignLastJustify:
588 case TextAlignLastAuto: {
589 if (alignment == JUSTIFY)
597 if (!endsWithSoftBreak && alignment == JUSTIFY)
599 #endif // TIZEN_CSS3_TEXT
604 static void updateLogicalWidthForLeftAlignedBlock(bool isLeftToRightDirection, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float availableLogicalWidth)
606 // The direction of the block should determine what happens with wide lines.
607 // In particular with RTL blocks, wide lines should still spill out to the left.
608 if (isLeftToRightDirection) {
609 if (totalLogicalWidth > availableLogicalWidth && trailingSpaceRun)
610 trailingSpaceRun->m_box->setLogicalWidth(max<float>(0, trailingSpaceRun->m_box->logicalWidth() - totalLogicalWidth + availableLogicalWidth));
614 if (trailingSpaceRun)
615 trailingSpaceRun->m_box->setLogicalWidth(0);
616 else if (totalLogicalWidth > availableLogicalWidth)
617 logicalLeft -= (totalLogicalWidth - availableLogicalWidth);
620 static void updateLogicalWidthForRightAlignedBlock(bool isLeftToRightDirection, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float availableLogicalWidth)
622 // Wide lines spill out of the block based off direction.
623 // So even if text-align is right, if direction is LTR, wide lines should overflow out of the right
624 // side of the block.
625 if (isLeftToRightDirection) {
626 if (trailingSpaceRun) {
627 totalLogicalWidth -= trailingSpaceRun->m_box->logicalWidth();
628 trailingSpaceRun->m_box->setLogicalWidth(0);
630 if (totalLogicalWidth < availableLogicalWidth)
631 logicalLeft += availableLogicalWidth - totalLogicalWidth;
635 if (totalLogicalWidth > availableLogicalWidth && trailingSpaceRun) {
636 trailingSpaceRun->m_box->setLogicalWidth(max<float>(0, trailingSpaceRun->m_box->logicalWidth() - totalLogicalWidth + availableLogicalWidth));
637 totalLogicalWidth -= trailingSpaceRun->m_box->logicalWidth();
639 logicalLeft += availableLogicalWidth - totalLogicalWidth;
642 static void updateLogicalWidthForCenterAlignedBlock(bool isLeftToRightDirection, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float availableLogicalWidth)
644 float trailingSpaceWidth = 0;
645 if (trailingSpaceRun) {
646 totalLogicalWidth -= trailingSpaceRun->m_box->logicalWidth();
647 trailingSpaceWidth = min(trailingSpaceRun->m_box->logicalWidth(), (availableLogicalWidth - totalLogicalWidth + 1) / 2);
648 trailingSpaceRun->m_box->setLogicalWidth(max<float>(0, trailingSpaceWidth));
650 if (isLeftToRightDirection)
651 logicalLeft += max<float>((availableLogicalWidth - totalLogicalWidth) / 2, 0);
653 logicalLeft += totalLogicalWidth > availableLogicalWidth ? (availableLogicalWidth - totalLogicalWidth) : (availableLogicalWidth - totalLogicalWidth) / 2 - trailingSpaceWidth;
656 void RenderBlock::setMarginsForRubyRun(BidiRun* run, RenderRubyRun* renderer, RenderObject* previousObject, const LineInfo& lineInfo)
660 RenderObject* nextObject = 0;
661 for (BidiRun* runWithNextObject = run->next(); runWithNextObject; runWithNextObject = runWithNextObject->next()) {
662 if (!runWithNextObject->m_object->isOutOfFlowPositioned() && !runWithNextObject->m_box->isLineBreak()) {
663 nextObject = runWithNextObject->m_object;
667 renderer->getOverhang(lineInfo.isFirstLine(), renderer->style()->isLeftToRightDirection() ? previousObject : nextObject, renderer->style()->isLeftToRightDirection() ? nextObject : previousObject, startOverhang, endOverhang);
668 setMarginStartForChild(renderer, -startOverhang);
669 setMarginEndForChild(renderer, -endOverhang);
672 static inline float measureHyphenWidth(RenderText* renderer, const Font& font)
674 RenderStyle* style = renderer->style();
675 return font.width(RenderBlock::constructTextRun(renderer, font, style->hyphenString().string(), style));
678 static inline void setLogicalWidthForTextRun(RootInlineBox* lineBox, BidiRun* run, RenderText* renderer, float xPos, const LineInfo& lineInfo,
679 GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache)
681 HashSet<const SimpleFontData*> fallbackFonts;
682 GlyphOverflow glyphOverflow;
684 // Always compute glyph overflow if the block's line-box-contain value is "glyphs".
685 if (lineBox->fitsToGlyphs()) {
686 // If we don't stick out of the root line's font box, then don't bother computing our glyph overflow. This optimization
687 // will keep us from computing glyph bounds in nearly all cases.
688 bool includeRootLine = lineBox->includesRootLineBoxFontOrLeading();
689 int baselineShift = lineBox->verticalPositionForBox(run->m_box, verticalPositionCache);
690 int rootDescent = includeRootLine ? lineBox->renderer()->style(lineInfo.isFirstLine())->font().fontMetrics().descent() : 0;
691 int rootAscent = includeRootLine ? lineBox->renderer()->style(lineInfo.isFirstLine())->font().fontMetrics().ascent() : 0;
692 int boxAscent = renderer->style(lineInfo.isFirstLine())->font().fontMetrics().ascent() - baselineShift;
693 int boxDescent = renderer->style(lineInfo.isFirstLine())->font().fontMetrics().descent() + baselineShift;
694 if (boxAscent > rootDescent || boxDescent > rootAscent)
695 glyphOverflow.computeBounds = true;
698 LayoutUnit hyphenWidth = 0;
699 if (toInlineTextBox(run->m_box)->hasHyphen()) {
700 const Font& font = renderer->style(lineInfo.isFirstLine())->font();
701 hyphenWidth = measureHyphenWidth(renderer, font);
703 run->m_box->setLogicalWidth(renderer->width(run->m_start, run->m_stop - run->m_start, xPos, lineInfo.isFirstLine(), &fallbackFonts, &glyphOverflow) + hyphenWidth);
704 if (!fallbackFonts.isEmpty()) {
705 ASSERT(run->m_box->isText());
706 GlyphOverflowAndFallbackFontsMap::iterator it = textBoxDataMap.add(toInlineTextBox(run->m_box), make_pair(Vector<const SimpleFontData*>(), GlyphOverflow())).iterator;
707 ASSERT(it->second.first.isEmpty());
708 copyToVector(fallbackFonts, it->second.first);
709 run->m_box->parent()->clearDescendantsHaveSameLineHeightAndBaseline();
711 if ((glyphOverflow.top || glyphOverflow.bottom || glyphOverflow.left || glyphOverflow.right)) {
712 ASSERT(run->m_box->isText());
713 GlyphOverflowAndFallbackFontsMap::iterator it = textBoxDataMap.add(toInlineTextBox(run->m_box), make_pair(Vector<const SimpleFontData*>(), GlyphOverflow())).iterator;
714 it->second.second = glyphOverflow;
715 run->m_box->clearKnownToHaveNoOverflow();
719 static inline void computeExpansionForJustifiedText(BidiRun* firstRun, BidiRun* trailingSpaceRun, Vector<unsigned, 16>& expansionOpportunities, unsigned expansionOpportunityCount, float& totalLogicalWidth, float availableLogicalWidth)
721 if (!expansionOpportunityCount || availableLogicalWidth <= totalLogicalWidth)
725 for (BidiRun* r = firstRun; r; r = r->next()) {
726 if (!r->m_box || r == trailingSpaceRun)
729 if (r->m_object->isText()) {
730 unsigned opportunitiesInRun = expansionOpportunities[i++];
732 ASSERT(opportunitiesInRun <= expansionOpportunityCount);
734 // Only justify text if whitespace is collapsed.
735 if (r->m_object->style()->collapseWhiteSpace()) {
736 InlineTextBox* textBox = toInlineTextBox(r->m_box);
737 int expansion = (availableLogicalWidth - totalLogicalWidth) * opportunitiesInRun / expansionOpportunityCount;
738 textBox->setExpansion(expansion);
739 totalLogicalWidth += expansion;
741 expansionOpportunityCount -= opportunitiesInRun;
742 if (!expansionOpportunityCount)
748 void RenderBlock::updateLogicalWidthForAlignment(const ETextAlign& textAlign, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float& availableLogicalWidth, int expansionOpportunityCount)
750 // Armed with the total width of the line (without justification),
751 // we now examine our text-align property in order to determine where to position the
752 // objects horizontally. The total width of the line can be increased if we end up
757 updateLogicalWidthForLeftAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
761 updateLogicalWidthForRightAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
765 updateLogicalWidthForCenterAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
768 adjustInlineDirectionLineBounds(expansionOpportunityCount, logicalLeft, availableLogicalWidth);
769 if (expansionOpportunityCount) {
770 if (trailingSpaceRun) {
771 totalLogicalWidth -= trailingSpaceRun->m_box->logicalWidth();
772 trailingSpaceRun->m_box->setLogicalWidth(0);
778 if (style()->isLeftToRightDirection())
779 updateLogicalWidthForLeftAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
781 updateLogicalWidthForRightAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
784 if (style()->isLeftToRightDirection())
785 updateLogicalWidthForRightAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
787 updateLogicalWidthForLeftAlignedBlock(style()->isLeftToRightDirection(), trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth);
792 void RenderBlock::computeInlineDirectionPositionsForLine(RootInlineBox* lineBox, const LineInfo& lineInfo, BidiRun* firstRun, BidiRun* trailingSpaceRun, bool reachedEnd,
793 GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache)
795 ETextAlign textAlign = textAlignmentForLine(!reachedEnd && !lineBox->endsWithBreak());
797 LayoutUnit lineLogicalHeight = logicalHeightForLine(this);
798 float logicalLeft = pixelSnappedLogicalLeftOffsetForLine(logicalHeight(), lineInfo.isFirstLine(), lineLogicalHeight);
799 float availableLogicalWidth = pixelSnappedLogicalRightOffsetForLine(logicalHeight(), lineInfo.isFirstLine(), lineLogicalHeight) - logicalLeft;
801 bool needsWordSpacing = false;
802 float totalLogicalWidth = lineBox->getFlowSpacingLogicalWidth();
803 unsigned expansionOpportunityCount = 0;
804 bool isAfterExpansion = true;
805 Vector<unsigned, 16> expansionOpportunities;
806 RenderObject* previousObject = 0;
808 for (BidiRun* r = firstRun; r; r = r->next()) {
809 if (!r->m_box || r->m_object->isOutOfFlowPositioned() || r->m_box->isLineBreak())
810 continue; // Positioned objects are only participating to figure out their
811 // correct static x position. They have no effect on the width.
812 // Similarly, line break boxes have no effect on the width.
813 if (r->m_object->isText()) {
814 RenderText* rt = toRenderText(r->m_object);
815 if (textAlign == JUSTIFY && r != trailingSpaceRun) {
816 if (!isAfterExpansion)
817 toInlineTextBox(r->m_box)->setCanHaveLeadingExpansion(true);
818 unsigned opportunitiesInRun = Font::expansionOpportunityCount(rt->characters() + r->m_start, r->m_stop - r->m_start, r->m_box->direction(), isAfterExpansion);
819 expansionOpportunities.append(opportunitiesInRun);
820 expansionOpportunityCount += opportunitiesInRun;
823 if (int length = rt->textLength()) {
824 if (!r->m_start && needsWordSpacing && isSpaceOrNewline(rt->characters()[r->m_start]))
825 totalLogicalWidth += rt->style(lineInfo.isFirstLine())->font().wordSpacing();
826 needsWordSpacing = !isSpaceOrNewline(rt->characters()[r->m_stop - 1]) && r->m_stop == length;
829 setLogicalWidthForTextRun(lineBox, r, rt, totalLogicalWidth, lineInfo, textBoxDataMap, verticalPositionCache);
831 isAfterExpansion = false;
832 if (!r->m_object->isRenderInline()) {
833 RenderBox* renderBox = toRenderBox(r->m_object);
834 if (renderBox->isRubyRun())
835 setMarginsForRubyRun(r, toRenderRubyRun(renderBox), previousObject, lineInfo);
836 r->m_box->setLogicalWidth(logicalWidthForChild(renderBox));
837 totalLogicalWidth += marginStartForChild(renderBox) + marginEndForChild(renderBox);
841 totalLogicalWidth += r->m_box->logicalWidth();
842 previousObject = r->m_object;
845 if (isAfterExpansion && !expansionOpportunities.isEmpty()) {
846 expansionOpportunities.last()--;
847 expansionOpportunityCount--;
850 updateLogicalWidthForAlignment(textAlign, trailingSpaceRun, logicalLeft, totalLogicalWidth, availableLogicalWidth, expansionOpportunityCount);
852 computeExpansionForJustifiedText(firstRun, trailingSpaceRun, expansionOpportunities, expansionOpportunityCount, totalLogicalWidth, availableLogicalWidth);
854 // The widths of all runs are now known. We can now place every inline box (and
855 // compute accurate widths for the inline flow boxes).
856 needsWordSpacing = false;
857 lineBox->placeBoxesInInlineDirection(logicalLeft, needsWordSpacing, textBoxDataMap);
860 void RenderBlock::computeBlockDirectionPositionsForLine(RootInlineBox* lineBox, BidiRun* firstRun, GlyphOverflowAndFallbackFontsMap& textBoxDataMap,
861 VerticalPositionCache& verticalPositionCache)
863 setLogicalHeight(lineBox->alignBoxesInBlockDirection(logicalHeight(), textBoxDataMap, verticalPositionCache));
865 // Now make sure we place replaced render objects correctly.
866 for (BidiRun* r = firstRun; r; r = r->next()) {
869 continue; // Skip runs with no line boxes.
871 // Align positioned boxes with the top of the line box. This is
872 // a reasonable approximation of an appropriate y position.
873 if (r->m_object->isOutOfFlowPositioned())
874 r->m_box->setLogicalTop(logicalHeight());
876 // Position is used to properly position both replaced elements and
877 // to update the static normal flow x/y of positioned elements.
878 if (r->m_object->isText())
879 toRenderText(r->m_object)->positionLineBox(r->m_box);
880 else if (r->m_object->isBox())
881 toRenderBox(r->m_object)->positionLineBox(r->m_box);
883 // Positioned objects and zero-length text nodes destroy their boxes in
884 // position(), which unnecessarily dirties the line.
885 lineBox->markDirty(false);
888 static inline bool isCollapsibleSpace(UChar character, RenderText* renderer)
890 if (character == ' ' || character == '\t' || character == softHyphen)
892 if (character == '\n')
893 return !renderer->style()->preserveNewline();
894 if (character == noBreakSpace)
895 return renderer->style()->nbspMode() == SPACE;
900 static void setStaticPositions(RenderBlock* block, RenderBox* child)
902 // FIXME: The math here is actually not really right. It's a best-guess approximation that
903 // will work for the common cases
904 RenderObject* containerBlock = child->container();
905 LayoutUnit blockHeight = block->logicalHeight();
906 if (containerBlock->isRenderInline()) {
907 // A relative positioned inline encloses us. In this case, we also have to determine our
908 // position as though we were an inline. Set |staticInlinePosition| and |staticBlockPosition| on the relative positioned
909 // inline so that we can obtain the value later.
910 toRenderInline(containerBlock)->layer()->setStaticInlinePosition(block->startAlignedOffsetForLine(blockHeight, false));
911 toRenderInline(containerBlock)->layer()->setStaticBlockPosition(blockHeight);
914 if (child->style()->isOriginalDisplayInlineType())
915 block->setStaticInlinePositionForChild(child, blockHeight, block->startAlignedOffsetForLine(blockHeight, false));
917 block->setStaticInlinePositionForChild(child, blockHeight, block->startOffsetForContent(blockHeight));
918 child->layer()->setStaticBlockPosition(blockHeight);
921 inline BidiRun* RenderBlock::handleTrailingSpaces(BidiRunList<BidiRun>& bidiRuns, BidiContext* currentContext)
923 if (!bidiRuns.runCount()
924 || !bidiRuns.logicallyLastRun()->m_object->style()->breakOnlyAfterWhiteSpace()
925 || !bidiRuns.logicallyLastRun()->m_object->style()->autoWrap())
928 BidiRun* trailingSpaceRun = bidiRuns.logicallyLastRun();
929 RenderObject* lastObject = trailingSpaceRun->m_object;
930 if (!lastObject->isText())
933 RenderText* lastText = toRenderText(lastObject);
934 const UChar* characters = lastText->characters();
935 int firstSpace = trailingSpaceRun->stop();
936 while (firstSpace > trailingSpaceRun->start()) {
937 UChar current = characters[firstSpace - 1];
938 if (!isCollapsibleSpace(current, lastText))
942 if (firstSpace == trailingSpaceRun->stop())
945 TextDirection direction = style()->direction();
946 bool shouldReorder = trailingSpaceRun != (direction == LTR ? bidiRuns.lastRun() : bidiRuns.firstRun());
947 if (firstSpace != trailingSpaceRun->start()) {
948 BidiContext* baseContext = currentContext;
949 while (BidiContext* parent = baseContext->parent())
950 baseContext = parent;
952 BidiRun* newTrailingRun = new (renderArena()) BidiRun(firstSpace, trailingSpaceRun->m_stop, trailingSpaceRun->m_object, baseContext, OtherNeutral);
953 trailingSpaceRun->m_stop = firstSpace;
954 if (direction == LTR)
955 bidiRuns.addRun(newTrailingRun);
957 bidiRuns.prependRun(newTrailingRun);
958 trailingSpaceRun = newTrailingRun;
959 return trailingSpaceRun;
962 return trailingSpaceRun;
964 if (direction == LTR) {
965 bidiRuns.moveRunToEnd(trailingSpaceRun);
966 trailingSpaceRun->m_level = 0;
968 bidiRuns.moveRunToBeginning(trailingSpaceRun);
969 trailingSpaceRun->m_level = 1;
971 return trailingSpaceRun;
974 void RenderBlock::appendFloatingObjectToLastLine(FloatingObject* floatingObject)
976 ASSERT(!floatingObject->m_originatingLine);
977 floatingObject->m_originatingLine = lastRootBox();
978 lastRootBox()->appendFloat(floatingObject->renderer());
981 // FIXME: This should be a BidiStatus constructor or create method.
982 static inline BidiStatus statusWithDirection(TextDirection textDirection, bool isOverride)
984 WTF::Unicode::Direction direction = textDirection == LTR ? LeftToRight : RightToLeft;
985 RefPtr<BidiContext> context = BidiContext::create(textDirection == LTR ? 0 : 1, direction, isOverride, FromStyleOrDOM);
987 // This copies BidiStatus and may churn the ref on BidiContext. I doubt it matters.
988 return BidiStatus(direction, direction, direction, context.release());
991 // FIXME: BidiResolver should have this logic.
992 static inline void constructBidiRuns(InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfLine, VisualDirectionOverride override, bool previousLineBrokeCleanly)
994 // FIXME: We should pass a BidiRunList into createBidiRunsForLine instead
995 // of the resolver owning the runs.
996 ASSERT(&topResolver.runs() == &bidiRuns);
997 RenderObject* currentRoot = topResolver.position().root();
998 topResolver.createBidiRunsForLine(endOfLine, override, previousLineBrokeCleanly);
1000 while (!topResolver.isolatedRuns().isEmpty()) {
1001 // It does not matter which order we resolve the runs as long as we resolve them all.
1002 BidiRun* isolatedRun = topResolver.isolatedRuns().last();
1003 topResolver.isolatedRuns().removeLast();
1005 RenderObject* startObj = isolatedRun->object();
1007 // Only inlines make sense with unicode-bidi: isolate (blocks are already isolated).
1008 // FIXME: Because enterIsolate is not passed a RenderObject, we have to crawl up the
1009 // tree to see which parent inline is the isolate. We could change enterIsolate
1010 // to take a RenderObject and do this logic there, but that would be a layering
1011 // violation for BidiResolver (which knows nothing about RenderObject).
1012 RenderInline* isolatedInline = toRenderInline(containingIsolate(startObj, currentRoot));
1013 InlineBidiResolver isolatedResolver;
1014 EUnicodeBidi unicodeBidi = isolatedInline->style()->unicodeBidi();
1015 TextDirection direction;
1016 if (unicodeBidi == Plaintext)
1017 determineDirectionality(direction, InlineIterator(isolatedInline, isolatedRun->object(), 0));
1019 ASSERT(unicodeBidi == Isolate || unicodeBidi == OverrideIsolate);
1020 direction = isolatedInline->style()->direction();
1022 isolatedResolver.setStatus(statusWithDirection(direction, isOverride(unicodeBidi)));
1024 // FIXME: The fact that we have to construct an Iterator here
1025 // currently prevents this code from moving into BidiResolver.
1026 if (!bidiFirstSkippingEmptyInlines(isolatedInline, &isolatedResolver))
1029 // The starting position is the beginning of the first run within the isolate that was identified
1030 // during the earlier call to createBidiRunsForLine. This can be but is not necessarily the
1031 // first run within the isolate.
1032 InlineIterator iter = InlineIterator(isolatedInline, startObj, isolatedRun->m_start);
1033 isolatedResolver.setPositionIgnoringNestedIsolates(iter);
1035 // We stop at the next end of line; we may re-enter this isolate in the next call to constructBidiRuns().
1036 // FIXME: What should end and previousLineBrokeCleanly be?
1037 // rniwa says previousLineBrokeCleanly is just a WinIE hack and could always be false here?
1038 isolatedResolver.createBidiRunsForLine(endOfLine, NoVisualOverride, previousLineBrokeCleanly);
1039 // Note that we do not delete the runs from the resolver.
1040 // We're not guaranteed to get any BidiRuns in the previous step. If we don't, we allow the placeholder
1041 // itself to be turned into an InlineBox. We can't remove it here without potentially losing track of
1042 // the logically last run.
1043 if (isolatedResolver.runs().runCount())
1044 bidiRuns.replaceRunWithRuns(isolatedRun, isolatedResolver.runs());
1046 // If we encountered any nested isolate runs, just move them
1047 // to the top resolver's list for later processing.
1048 if (!isolatedResolver.isolatedRuns().isEmpty()) {
1049 topResolver.isolatedRuns().append(isolatedResolver.isolatedRuns());
1050 isolatedResolver.isolatedRuns().clear();
1055 // This function constructs line boxes for all of the text runs in the resolver and computes their position.
1056 RootInlineBox* RenderBlock::createLineBoxesFromBidiRuns(BidiRunList<BidiRun>& bidiRuns, const InlineIterator& end, LineInfo& lineInfo, VerticalPositionCache& verticalPositionCache, BidiRun* trailingSpaceRun)
1058 if (!bidiRuns.runCount())
1061 // FIXME: Why is this only done when we had runs?
1062 lineInfo.setLastLine(!end.m_obj);
1064 RootInlineBox* lineBox = constructLine(bidiRuns, lineInfo);
1068 lineBox->setEndsWithBreak(lineInfo.previousLineBrokeCleanly());
1071 bool isSVGRootInlineBox = lineBox->isSVGRootInlineBox();
1073 bool isSVGRootInlineBox = false;
1076 GlyphOverflowAndFallbackFontsMap textBoxDataMap;
1078 // Now we position all of our text runs horizontally.
1079 if (!isSVGRootInlineBox)
1080 computeInlineDirectionPositionsForLine(lineBox, lineInfo, bidiRuns.firstRun(), trailingSpaceRun, end.atEnd(), textBoxDataMap, verticalPositionCache);
1082 // Now position our text runs vertically.
1083 computeBlockDirectionPositionsForLine(lineBox, bidiRuns.firstRun(), textBoxDataMap, verticalPositionCache);
1086 // SVG text layout code computes vertical & horizontal positions on its own.
1087 // Note that we still need to execute computeVerticalPositionsForLine() as
1088 // it calls InlineTextBox::positionLineBox(), which tracks whether the box
1089 // contains reversed text or not. If we wouldn't do that editing and thus
1090 // text selection in RTL boxes would not work as expected.
1091 if (isSVGRootInlineBox) {
1092 ASSERT(isSVGText());
1093 static_cast<SVGRootInlineBox*>(lineBox)->computePerCharacterLayoutInformation();
1097 // Compute our overflow now.
1098 lineBox->computeOverflow(lineBox->lineTop(), lineBox->lineBottom(), textBoxDataMap);
1101 // Highlight acts as an overflow inflation.
1102 if (style()->highlight() != nullAtom)
1103 lineBox->addHighlightOverflow();
1108 // Like LayoutState for layout(), LineLayoutState keeps track of global information
1109 // during an entire linebox tree layout pass (aka layoutInlineChildren).
1110 class LineLayoutState {
1112 LineLayoutState(bool fullLayout, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom)
1116 , m_endLineLogicalTop(0)
1117 , m_endLineMatched(false)
1118 , m_checkForFloatsFromLastLine(false)
1119 , m_isFullLayout(fullLayout)
1120 , m_repaintLogicalTop(repaintLogicalTop)
1121 , m_repaintLogicalBottom(repaintLogicalBottom)
1122 , m_usesRepaintBounds(false)
1125 void markForFullLayout() { m_isFullLayout = true; }
1126 bool isFullLayout() const { return m_isFullLayout; }
1128 bool usesRepaintBounds() const { return m_usesRepaintBounds; }
1130 void setRepaintRange(LayoutUnit logicalHeight)
1132 m_usesRepaintBounds = true;
1133 m_repaintLogicalTop = m_repaintLogicalBottom = logicalHeight;
1136 void updateRepaintRangeFromBox(RootInlineBox* box, LayoutUnit paginationDelta = 0)
1138 m_usesRepaintBounds = true;
1139 m_repaintLogicalTop = min(m_repaintLogicalTop, box->logicalTopVisualOverflow() + min(paginationDelta, ZERO_LAYOUT_UNIT));
1140 m_repaintLogicalBottom = max(m_repaintLogicalBottom, box->logicalBottomVisualOverflow() + max(paginationDelta, ZERO_LAYOUT_UNIT));
1143 bool endLineMatched() const { return m_endLineMatched; }
1144 void setEndLineMatched(bool endLineMatched) { m_endLineMatched = endLineMatched; }
1146 bool checkForFloatsFromLastLine() const { return m_checkForFloatsFromLastLine; }
1147 void setCheckForFloatsFromLastLine(bool check) { m_checkForFloatsFromLastLine = check; }
1149 LineInfo& lineInfo() { return m_lineInfo; }
1150 const LineInfo& lineInfo() const { return m_lineInfo; }
1152 LayoutUnit endLineLogicalTop() const { return m_endLineLogicalTop; }
1153 void setEndLineLogicalTop(LayoutUnit logicalTop) { m_endLineLogicalTop = logicalTop; }
1155 RootInlineBox* endLine() const { return m_endLine; }
1156 void setEndLine(RootInlineBox* line) { m_endLine = line; }
1158 RenderBlock::FloatingObject* lastFloat() const { return m_lastFloat; }
1159 void setLastFloat(RenderBlock::FloatingObject* lastFloat) { m_lastFloat = lastFloat; }
1161 Vector<RenderBlock::FloatWithRect>& floats() { return m_floats; }
1163 unsigned floatIndex() const { return m_floatIndex; }
1164 void setFloatIndex(unsigned floatIndex) { m_floatIndex = floatIndex; }
1167 Vector<RenderBlock::FloatWithRect> m_floats;
1168 RenderBlock::FloatingObject* m_lastFloat;
1169 RootInlineBox* m_endLine;
1170 LineInfo m_lineInfo;
1171 unsigned m_floatIndex;
1172 LayoutUnit m_endLineLogicalTop;
1173 bool m_endLineMatched;
1174 bool m_checkForFloatsFromLastLine;
1176 bool m_isFullLayout;
1178 // FIXME: Should this be a range object instead of two ints?
1179 LayoutUnit& m_repaintLogicalTop;
1180 LayoutUnit& m_repaintLogicalBottom;
1182 bool m_usesRepaintBounds;
1185 static void deleteLineRange(LineLayoutState& layoutState, RenderArena* arena, RootInlineBox* startLine, RootInlineBox* stopLine = 0)
1187 RootInlineBox* boxToDelete = startLine;
1188 while (boxToDelete && boxToDelete != stopLine) {
1189 layoutState.updateRepaintRangeFromBox(boxToDelete);
1190 // Note: deleteLineRange(renderArena(), firstRootBox()) is not identical to deleteLineBoxTree().
1191 // deleteLineBoxTree uses nextLineBox() instead of nextRootBox() when traversing.
1192 RootInlineBox* next = boxToDelete->nextRootBox();
1193 boxToDelete->deleteLine(arena);
1198 void RenderBlock::layoutRunsAndFloats(LineLayoutState& layoutState, bool hasInlineChild)
1200 // We want to skip ahead to the first dirty line
1201 InlineBidiResolver resolver;
1202 RootInlineBox* startLine = determineStartPosition(layoutState, resolver);
1204 unsigned consecutiveHyphenatedLines = 0;
1206 for (RootInlineBox* line = startLine->prevRootBox(); line && line->isHyphenated(); line = line->prevRootBox())
1207 consecutiveHyphenatedLines++;
1210 // FIXME: This would make more sense outside of this function, but since
1211 // determineStartPosition can change the fullLayout flag we have to do this here. Failure to call
1212 // determineStartPosition first will break fast/repaint/line-flow-with-floats-9.html.
1213 if (layoutState.isFullLayout() && hasInlineChild && !selfNeedsLayout()) {
1214 setNeedsLayout(true, MarkOnlyThis); // Mark as needing a full layout to force us to repaint.
1215 RenderView* v = view();
1216 if (v && !v->doingFullRepaint() && hasLayer()) {
1217 // Because we waited until we were already inside layout to discover
1218 // that the block really needed a full layout, we missed our chance to repaint the layer
1219 // before layout started. Luckily the layer has cached the repaint rect for its original
1220 // position and size, and so we can use that to make a repaint happen now.
1221 repaintUsingContainer(containerForRepaint(), layer()->repaintRect());
1225 if (m_floatingObjects && !m_floatingObjects->set().isEmpty())
1226 layoutState.setLastFloat(m_floatingObjects->set().last());
1228 // We also find the first clean line and extract these lines. We will add them back
1229 // if we determine that we're able to synchronize after handling all our dirty lines.
1230 InlineIterator cleanLineStart;
1231 BidiStatus cleanLineBidiStatus;
1232 if (!layoutState.isFullLayout() && startLine)
1233 determineEndPosition(layoutState, startLine, cleanLineStart, cleanLineBidiStatus);
1236 if (!layoutState.usesRepaintBounds())
1237 layoutState.setRepaintRange(logicalHeight());
1238 deleteLineRange(layoutState, renderArena(), startLine);
1241 if (!layoutState.isFullLayout() && lastRootBox() && lastRootBox()->endsWithBreak()) {
1242 // If the last line before the start line ends with a line break that clear floats,
1243 // adjust the height accordingly.
1244 // A line break can be either the first or the last object on a line, depending on its direction.
1245 if (InlineBox* lastLeafChild = lastRootBox()->lastLeafChild()) {
1246 RenderObject* lastObject = lastLeafChild->renderer();
1247 if (!lastObject->isBR())
1248 lastObject = lastRootBox()->firstLeafChild()->renderer();
1249 if (lastObject->isBR()) {
1250 EClear clear = lastObject->style()->clear();
1257 layoutRunsAndFloatsInRange(layoutState, resolver, cleanLineStart, cleanLineBidiStatus, consecutiveHyphenatedLines);
1258 linkToEndLineIfNeeded(layoutState);
1259 repaintDirtyFloats(layoutState.floats());
1262 void RenderBlock::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, InlineBidiResolver& resolver, const InlineIterator& cleanLineStart, const BidiStatus& cleanLineBidiStatus, unsigned consecutiveHyphenatedLines)
1264 RenderStyle* styleToUse = style();
1265 bool paginated = view()->layoutState() && view()->layoutState()->isPaginated();
1266 LineMidpointState& lineMidpointState = resolver.midpointState();
1267 InlineIterator end = resolver.position();
1268 bool checkForEndLineMatch = layoutState.endLine();
1269 LineBreakIteratorInfo lineBreakIteratorInfo;
1270 VerticalPositionCache verticalPositionCache;
1272 LineBreaker lineBreaker(this);
1274 while (!end.atEnd()) {
1275 // FIXME: Is this check necessary before the first iteration or can it be moved to the end?
1276 if (checkForEndLineMatch) {
1277 layoutState.setEndLineMatched(matchedEndLine(layoutState, resolver, cleanLineStart, cleanLineBidiStatus));
1278 if (layoutState.endLineMatched()) {
1279 resolver.setPosition(InlineIterator(resolver.position().root(), 0, 0), 0);
1284 lineMidpointState.reset();
1286 layoutState.lineInfo().setEmpty(true);
1287 layoutState.lineInfo().resetRunsFromLeadingWhitespace();
1289 const InlineIterator oldEnd = end;
1290 bool isNewUBAParagraph = layoutState.lineInfo().previousLineBrokeCleanly();
1291 FloatingObject* lastFloatFromPreviousLine = (m_floatingObjects && !m_floatingObjects->set().isEmpty()) ? m_floatingObjects->set().last() : 0;
1292 end = lineBreaker.nextLineBreak(resolver, layoutState.lineInfo(), lineBreakIteratorInfo, lastFloatFromPreviousLine, consecutiveHyphenatedLines);
1293 if (resolver.position().atEnd()) {
1294 // FIXME: We shouldn't be creating any runs in nextLineBreak to begin with!
1295 // Once BidiRunList is separated from BidiResolver this will not be needed.
1296 resolver.runs().deleteRuns();
1297 resolver.markCurrentRunEmpty(); // FIXME: This can probably be replaced by an ASSERT (or just removed).
1298 layoutState.setCheckForFloatsFromLastLine(true);
1299 resolver.setPosition(InlineIterator(resolver.position().root(), 0, 0), 0);
1302 ASSERT(end != resolver.position());
1304 // This is a short-cut for empty lines.
1305 if (layoutState.lineInfo().isEmpty()) {
1307 lastRootBox()->setLineBreakInfo(end.m_obj, end.m_pos, resolver.status());
1309 VisualDirectionOverride override = (styleToUse->rtlOrdering() == VisualOrder ? (styleToUse->direction() == LTR ? VisualLeftToRightOverride : VisualRightToLeftOverride) : NoVisualOverride);
1311 if (isNewUBAParagraph && styleToUse->unicodeBidi() == Plaintext && !resolver.context()->parent()) {
1312 TextDirection direction = styleToUse->direction();
1313 determineDirectionality(direction, resolver.position());
1314 resolver.setStatus(BidiStatus(direction, isOverride(styleToUse->unicodeBidi())));
1316 // FIXME: This ownership is reversed. We should own the BidiRunList and pass it to createBidiRunsForLine.
1317 BidiRunList<BidiRun>& bidiRuns = resolver.runs();
1318 constructBidiRuns(resolver, bidiRuns, end, override, layoutState.lineInfo().previousLineBrokeCleanly());
1319 ASSERT(resolver.position() == end);
1321 BidiRun* trailingSpaceRun = !layoutState.lineInfo().previousLineBrokeCleanly() ? handleTrailingSpaces(bidiRuns, resolver.context()) : 0;
1323 if (bidiRuns.runCount() && lineBreaker.lineWasHyphenated()) {
1324 bidiRuns.logicallyLastRun()->m_hasHyphen = true;
1325 consecutiveHyphenatedLines++;
1327 consecutiveHyphenatedLines = 0;
1329 // Now that the runs have been ordered, we create the line boxes.
1330 // At the same time we figure out where border/padding/margin should be applied for
1331 // inline flow boxes.
1333 LayoutUnit oldLogicalHeight = logicalHeight();
1334 RootInlineBox* lineBox = createLineBoxesFromBidiRuns(bidiRuns, end, layoutState.lineInfo(), verticalPositionCache, trailingSpaceRun);
1336 bidiRuns.deleteRuns();
1337 resolver.markCurrentRunEmpty(); // FIXME: This can probably be replaced by an ASSERT (or just removed).
1340 lineBox->setLineBreakInfo(end.m_obj, end.m_pos, resolver.status());
1341 if (layoutState.usesRepaintBounds())
1342 layoutState.updateRepaintRangeFromBox(lineBox);
1345 LayoutUnit adjustment = 0;
1346 adjustLinePositionForPagination(lineBox, adjustment);
1348 LayoutUnit oldLineWidth = availableLogicalWidthForLine(oldLogicalHeight, layoutState.lineInfo().isFirstLine());
1349 lineBox->adjustBlockDirectionPosition(adjustment);
1350 if (layoutState.usesRepaintBounds())
1351 layoutState.updateRepaintRangeFromBox(lineBox);
1353 if (availableLogicalWidthForLine(oldLogicalHeight + adjustment, layoutState.lineInfo().isFirstLine()) != oldLineWidth) {
1354 // We have to delete this line, remove all floats that got added, and let line layout re-run.
1355 lineBox->deleteLine(renderArena());
1356 removeFloatingObjectsBelow(lastFloatFromPreviousLine, oldLogicalHeight);
1357 setLogicalHeight(oldLogicalHeight + adjustment);
1358 resolver.setPositionIgnoringNestedIsolates(oldEnd);
1363 setLogicalHeight(lineBox->lineBottomWithLeading());
1368 for (size_t i = 0; i < lineBreaker.positionedObjects().size(); ++i)
1369 setStaticPositions(this, lineBreaker.positionedObjects()[i]);
1371 layoutState.lineInfo().setFirstLine(false);
1372 newLine(lineBreaker.clear());
1375 if (m_floatingObjects && lastRootBox()) {
1376 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1377 FloatingObjectSetIterator it = floatingObjectSet.begin();
1378 FloatingObjectSetIterator end = floatingObjectSet.end();
1379 if (layoutState.lastFloat()) {
1380 FloatingObjectSetIterator lastFloatIterator = floatingObjectSet.find(layoutState.lastFloat());
1381 ASSERT(lastFloatIterator != end);
1382 ++lastFloatIterator;
1383 it = lastFloatIterator;
1385 for (; it != end; ++it) {
1386 FloatingObject* f = *it;
1387 appendFloatingObjectToLastLine(f);
1388 ASSERT(f->m_renderer == layoutState.floats()[layoutState.floatIndex()].object);
1389 // If a float's geometry has changed, give up on syncing with clean lines.
1390 if (layoutState.floats()[layoutState.floatIndex()].rect != f->frameRect())
1391 checkForEndLineMatch = false;
1392 layoutState.setFloatIndex(layoutState.floatIndex() + 1);
1394 layoutState.setLastFloat(!floatingObjectSet.isEmpty() ? floatingObjectSet.last() : 0);
1397 lineMidpointState.reset();
1398 resolver.setPosition(end, numberOfIsolateAncestors(end));
1402 void RenderBlock::linkToEndLineIfNeeded(LineLayoutState& layoutState)
1404 if (layoutState.endLine()) {
1405 if (layoutState.endLineMatched()) {
1406 bool paginated = view()->layoutState() && view()->layoutState()->isPaginated();
1407 // Attach all the remaining lines, and then adjust their y-positions as needed.
1408 LayoutUnit delta = logicalHeight() - layoutState.endLineLogicalTop();
1409 for (RootInlineBox* line = layoutState.endLine(); line; line = line->nextRootBox()) {
1412 delta -= line->paginationStrut();
1413 adjustLinePositionForPagination(line, delta);
1416 layoutState.updateRepaintRangeFromBox(line, delta);
1417 line->adjustBlockDirectionPosition(delta);
1419 if (Vector<RenderBox*>* cleanLineFloats = line->floatsPtr()) {
1420 Vector<RenderBox*>::iterator end = cleanLineFloats->end();
1421 for (Vector<RenderBox*>::iterator f = cleanLineFloats->begin(); f != end; ++f) {
1422 FloatingObject* floatingObject = insertFloatingObject(*f);
1423 ASSERT(!floatingObject->m_originatingLine);
1424 floatingObject->m_originatingLine = line;
1425 setLogicalHeight(logicalTopForChild(*f) - marginBeforeForChild(*f) + delta);
1426 positionNewFloats();
1430 setLogicalHeight(lastRootBox()->lineBottomWithLeading());
1432 // Delete all the remaining lines.
1433 deleteLineRange(layoutState, renderArena(), layoutState.endLine());
1437 if (m_floatingObjects && (layoutState.checkForFloatsFromLastLine() || positionNewFloats()) && lastRootBox()) {
1438 // In case we have a float on the last line, it might not be positioned up to now.
1439 // This has to be done before adding in the bottom border/padding, or the float will
1440 // include the padding incorrectly. -dwh
1441 if (layoutState.checkForFloatsFromLastLine()) {
1442 LayoutUnit bottomVisualOverflow = lastRootBox()->logicalBottomVisualOverflow();
1443 LayoutUnit bottomLayoutOverflow = lastRootBox()->logicalBottomLayoutOverflow();
1444 TrailingFloatsRootInlineBox* trailingFloatsLineBox = new (renderArena()) TrailingFloatsRootInlineBox(this);
1445 m_lineBoxes.appendLineBox(trailingFloatsLineBox);
1446 trailingFloatsLineBox->setConstructed();
1447 GlyphOverflowAndFallbackFontsMap textBoxDataMap;
1448 VerticalPositionCache verticalPositionCache;
1449 LayoutUnit blockLogicalHeight = logicalHeight();
1450 trailingFloatsLineBox->alignBoxesInBlockDirection(blockLogicalHeight, textBoxDataMap, verticalPositionCache);
1451 trailingFloatsLineBox->setLineTopBottomPositions(blockLogicalHeight, blockLogicalHeight, blockLogicalHeight, blockLogicalHeight);
1452 trailingFloatsLineBox->setPaginatedLineWidth(availableLogicalWidthForContent(blockLogicalHeight));
1453 LayoutRect logicalLayoutOverflow(0, blockLogicalHeight, 1, bottomLayoutOverflow - blockLogicalHeight);
1454 LayoutRect logicalVisualOverflow(0, blockLogicalHeight, 1, bottomVisualOverflow - blockLogicalHeight);
1455 trailingFloatsLineBox->setOverflowFromLogicalRects(logicalLayoutOverflow, logicalVisualOverflow, trailingFloatsLineBox->lineTop(), trailingFloatsLineBox->lineBottom());
1458 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1459 FloatingObjectSetIterator it = floatingObjectSet.begin();
1460 FloatingObjectSetIterator end = floatingObjectSet.end();
1461 if (layoutState.lastFloat()) {
1462 FloatingObjectSetIterator lastFloatIterator = floatingObjectSet.find(layoutState.lastFloat());
1463 ASSERT(lastFloatIterator != end);
1464 ++lastFloatIterator;
1465 it = lastFloatIterator;
1467 for (; it != end; ++it)
1468 appendFloatingObjectToLastLine(*it);
1469 layoutState.setLastFloat(!floatingObjectSet.isEmpty() ? floatingObjectSet.last() : 0);
1473 void RenderBlock::repaintDirtyFloats(Vector<FloatWithRect>& floats)
1475 size_t floatCount = floats.size();
1476 // Floats that did not have layout did not repaint when we laid them out. They would have
1477 // painted by now if they had moved, but if they stayed at (0, 0), they still need to be
1479 for (size_t i = 0; i < floatCount; ++i) {
1480 if (!floats[i].everHadLayout) {
1481 RenderBox* f = floats[i].object;
1482 if (!f->x() && !f->y() && f->checkForRepaintDuringLayout())
1488 void RenderBlock::layoutInlineChildren(bool relayoutChildren, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom)
1492 setLogicalHeight(borderBefore() + paddingBefore());
1494 // Lay out our hypothetical grid line as though it occurs at the top of the block.
1495 if (view()->layoutState() && view()->layoutState()->lineGrid() == this)
1496 layoutLineGridBox();
1498 // Figure out if we should clear out our line boxes.
1499 // FIXME: Handle resize eventually!
1500 bool isFullLayout = !firstLineBox() || selfNeedsLayout() || relayoutChildren;
1501 LineLayoutState layoutState(isFullLayout, repaintLogicalTop, repaintLogicalBottom);
1504 lineBoxes()->deleteLineBoxes(renderArena());
1506 // Text truncation only kicks in if your overflow isn't visible and your text-overflow-mode isn't
1508 // FIXME: CSS3 says that descendants that are clipped must also know how to truncate. This is insanely
1509 // difficult to figure out (especially in the middle of doing layout), and is really an esoteric pile of nonsense
1510 // anyway, so we won't worry about following the draft here.
1511 bool hasTextOverflow = style()->textOverflow() && hasOverflowClip();
1513 // Walk all the lines and delete our ellipsis line boxes if they exist.
1514 if (hasTextOverflow)
1515 deleteEllipsisLineBoxes();
1518 // layout replaced elements
1519 bool hasInlineChild = false;
1520 for (InlineWalker walker(this); !walker.atEnd(); walker.advance()) {
1521 RenderObject* o = walker.current();
1522 if (!hasInlineChild && o->isInline())
1523 hasInlineChild = true;
1525 if (o->isReplaced() || o->isFloating() || o->isOutOfFlowPositioned()) {
1526 RenderBox* box = toRenderBox(o);
1528 if (relayoutChildren || box->hasRelativeDimensions())
1529 o->setChildNeedsLayout(true, MarkOnlyThis);
1531 // If relayoutChildren is set and the child has percentage padding or an embedded content box, we also need to invalidate the childs pref widths.
1532 if (relayoutChildren && box->needsPreferredWidthsRecalculation())
1533 o->setPreferredLogicalWidthsDirty(true, MarkOnlyThis);
1535 if (o->isOutOfFlowPositioned())
1536 o->containingBlock()->insertPositionedObject(box);
1537 else if (o->isFloating())
1538 layoutState.floats().append(FloatWithRect(box));
1539 else if (layoutState.isFullLayout() || o->needsLayout()) {
1540 // Replaced elements
1541 toRenderBox(o)->dirtyLineBoxes(layoutState.isFullLayout());
1543 } else if (o->isText() || (o->isRenderInline() && !walker.atEndOfInline())) {
1545 toRenderInline(o)->updateAlwaysCreateLineBoxes(layoutState.isFullLayout());
1546 if (layoutState.isFullLayout() || o->selfNeedsLayout())
1547 dirtyLineBoxesForRenderer(o, layoutState.isFullLayout());
1548 o->setNeedsLayout(false);
1552 layoutRunsAndFloats(layoutState, hasInlineChild);
1555 // Expand the last line to accommodate Ruby and emphasis marks.
1556 int lastLineAnnotationsAdjustment = 0;
1557 if (lastRootBox()) {
1558 LayoutUnit lowestAllowedPosition = max(lastRootBox()->lineBottom(), logicalHeight() + paddingAfter());
1559 if (!style()->isFlippedLinesWritingMode())
1560 lastLineAnnotationsAdjustment = lastRootBox()->computeUnderAnnotationAdjustment(lowestAllowedPosition);
1562 lastLineAnnotationsAdjustment = lastRootBox()->computeOverAnnotationAdjustment(lowestAllowedPosition);
1565 // Now add in the bottom border/padding.
1566 setLogicalHeight(logicalHeight() + lastLineAnnotationsAdjustment + borderAfter() + paddingAfter() + scrollbarLogicalHeight());
1568 if (!firstLineBox() && hasLineIfEmpty())
1569 setLogicalHeight(logicalHeight() + lineHeight(true, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes));
1571 // See if we have any lines that spill out of our block. If we do, then we will possibly need to
1573 if (hasTextOverflow)
1574 checkLinesForTextOverflow();
1577 void RenderBlock::checkFloatsInCleanLine(RootInlineBox* line, Vector<FloatWithRect>& floats, size_t& floatIndex, bool& encounteredNewFloat, bool& dirtiedByFloat)
1579 Vector<RenderBox*>* cleanLineFloats = line->floatsPtr();
1580 if (!cleanLineFloats)
1583 Vector<RenderBox*>::iterator end = cleanLineFloats->end();
1584 for (Vector<RenderBox*>::iterator it = cleanLineFloats->begin(); it != end; ++it) {
1585 RenderBox* floatingBox = *it;
1586 floatingBox->layoutIfNeeded();
1587 LayoutSize newSize(floatingBox->width() + floatingBox->marginWidth(), floatingBox->height() + floatingBox->marginHeight());
1588 ASSERT(floatIndex < floats.size());
1589 if (floats[floatIndex].object != floatingBox) {
1590 encounteredNewFloat = true;
1594 if (floats[floatIndex].rect.size() != newSize) {
1595 LayoutUnit floatTop = isHorizontalWritingMode() ? floats[floatIndex].rect.y() : floats[floatIndex].rect.x();
1596 LayoutUnit floatHeight = isHorizontalWritingMode() ? max(floats[floatIndex].rect.height(), newSize.height())
1597 : max(floats[floatIndex].rect.width(), newSize.width());
1598 floatHeight = min(floatHeight, MAX_LAYOUT_UNIT - floatTop);
1600 markLinesDirtyInBlockRange(line->lineBottomWithLeading(), floatTop + floatHeight, line);
1601 floats[floatIndex].rect.setSize(newSize);
1602 dirtiedByFloat = true;
1608 RootInlineBox* RenderBlock::determineStartPosition(LineLayoutState& layoutState, InlineBidiResolver& resolver)
1610 RootInlineBox* curr = 0;
1611 RootInlineBox* last = 0;
1613 // FIXME: This entire float-checking block needs to be broken into a new function.
1614 bool dirtiedByFloat = false;
1615 if (!layoutState.isFullLayout()) {
1616 // Paginate all of the clean lines.
1617 bool paginated = view()->layoutState() && view()->layoutState()->isPaginated();
1618 LayoutUnit paginationDelta = 0;
1619 size_t floatIndex = 0;
1620 for (curr = firstRootBox(); curr && !curr->isDirty(); curr = curr->nextRootBox()) {
1622 if (lineWidthForPaginatedLineChanged(curr)) {
1626 paginationDelta -= curr->paginationStrut();
1627 adjustLinePositionForPagination(curr, paginationDelta);
1628 if (paginationDelta) {
1629 if (containsFloats() || !layoutState.floats().isEmpty()) {
1630 // FIXME: Do better eventually. For now if we ever shift because of pagination and floats are present just go to a full layout.
1631 layoutState.markForFullLayout();
1635 layoutState.updateRepaintRangeFromBox(curr, paginationDelta);
1636 curr->adjustBlockDirectionPosition(paginationDelta);
1640 // If a new float has been inserted before this line or before its last known float, just do a full layout.
1641 bool encounteredNewFloat = false;
1642 checkFloatsInCleanLine(curr, layoutState.floats(), floatIndex, encounteredNewFloat, dirtiedByFloat);
1643 if (encounteredNewFloat)
1644 layoutState.markForFullLayout();
1646 if (dirtiedByFloat || layoutState.isFullLayout())
1649 // Check if a new float has been inserted after the last known float.
1650 if (!curr && floatIndex < layoutState.floats().size())
1651 layoutState.markForFullLayout();
1654 if (layoutState.isFullLayout()) {
1655 // FIXME: This should just call deleteLineBoxTree, but that causes
1656 // crashes for fast/repaint tests.
1657 RenderArena* arena = renderArena();
1658 curr = firstRootBox();
1660 // Note: This uses nextRootBox() insted of nextLineBox() like deleteLineBoxTree does.
1661 RootInlineBox* next = curr->nextRootBox();
1662 curr->deleteLine(arena);
1665 ASSERT(!firstLineBox() && !lastLineBox());
1668 // We have a dirty line.
1669 if (RootInlineBox* prevRootBox = curr->prevRootBox()) {
1670 // We have a previous line.
1671 if (!dirtiedByFloat && (!prevRootBox->endsWithBreak() || (prevRootBox->lineBreakObj()->isText() && prevRootBox->lineBreakPos() >= toRenderText(prevRootBox->lineBreakObj())->textLength())))
1672 // The previous line didn't break cleanly or broke at a newline
1673 // that has been deleted, so treat it as dirty too.
1677 // No dirty lines were found.
1678 // If the last line didn't break cleanly, treat it as dirty.
1679 if (lastRootBox() && !lastRootBox()->endsWithBreak())
1680 curr = lastRootBox();
1683 // If we have no dirty lines, then last is just the last root box.
1684 last = curr ? curr->prevRootBox() : lastRootBox();
1687 unsigned numCleanFloats = 0;
1688 if (!layoutState.floats().isEmpty()) {
1689 LayoutUnit savedLogicalHeight = logicalHeight();
1690 // Restore floats from clean lines.
1691 RootInlineBox* line = firstRootBox();
1692 while (line != curr) {
1693 if (Vector<RenderBox*>* cleanLineFloats = line->floatsPtr()) {
1694 Vector<RenderBox*>::iterator end = cleanLineFloats->end();
1695 for (Vector<RenderBox*>::iterator f = cleanLineFloats->begin(); f != end; ++f) {
1696 FloatingObject* floatingObject = insertFloatingObject(*f);
1697 ASSERT(!floatingObject->m_originatingLine);
1698 floatingObject->m_originatingLine = line;
1699 setLogicalHeight(logicalTopForChild(*f) - marginBeforeForChild(*f));
1700 positionNewFloats();
1701 ASSERT(layoutState.floats()[numCleanFloats].object == *f);
1705 line = line->nextRootBox();
1707 setLogicalHeight(savedLogicalHeight);
1709 layoutState.setFloatIndex(numCleanFloats);
1711 layoutState.lineInfo().setFirstLine(!last);
1712 layoutState.lineInfo().setPreviousLineBrokeCleanly(!last || last->endsWithBreak());
1715 setLogicalHeight(last->lineBottomWithLeading());
1716 InlineIterator iter = InlineIterator(this, last->lineBreakObj(), last->lineBreakPos());
1717 resolver.setPosition(iter, numberOfIsolateAncestors(iter));
1718 resolver.setStatus(last->lineBreakBidiStatus());
1720 TextDirection direction = style()->direction();
1721 if (style()->unicodeBidi() == Plaintext)
1722 determineDirectionality(direction, InlineIterator(this, bidiFirstSkippingEmptyInlines(this), 0));
1723 resolver.setStatus(BidiStatus(direction, isOverride(style()->unicodeBidi())));
1724 InlineIterator iter = InlineIterator(this, bidiFirstSkippingEmptyInlines(this, &resolver), 0);
1725 resolver.setPosition(iter, numberOfIsolateAncestors(iter));
1730 void RenderBlock::determineEndPosition(LineLayoutState& layoutState, RootInlineBox* startLine, InlineIterator& cleanLineStart, BidiStatus& cleanLineBidiStatus)
1732 ASSERT(!layoutState.endLine());
1733 size_t floatIndex = layoutState.floatIndex();
1734 RootInlineBox* last = 0;
1735 for (RootInlineBox* curr = startLine->nextRootBox(); curr; curr = curr->nextRootBox()) {
1736 if (!curr->isDirty()) {
1737 bool encounteredNewFloat = false;
1738 bool dirtiedByFloat = false;
1739 checkFloatsInCleanLine(curr, layoutState.floats(), floatIndex, encounteredNewFloat, dirtiedByFloat);
1740 if (encounteredNewFloat)
1743 if (curr->isDirty())
1752 // At this point, |last| is the first line in a run of clean lines that ends with the last line
1755 RootInlineBox* prev = last->prevRootBox();
1756 cleanLineStart = InlineIterator(this, prev->lineBreakObj(), prev->lineBreakPos());
1757 cleanLineBidiStatus = prev->lineBreakBidiStatus();
1758 layoutState.setEndLineLogicalTop(prev->lineBottomWithLeading());
1760 for (RootInlineBox* line = last; line; line = line->nextRootBox())
1761 line->extractLine(); // Disconnect all line boxes from their render objects while preserving
1762 // their connections to one another.
1764 layoutState.setEndLine(last);
1767 bool RenderBlock::checkPaginationAndFloatsAtEndLine(LineLayoutState& layoutState)
1769 LayoutUnit lineDelta = logicalHeight() - layoutState.endLineLogicalTop();
1771 bool paginated = view()->layoutState() && view()->layoutState()->isPaginated();
1772 if (paginated && inRenderFlowThread()) {
1773 // Check all lines from here to the end, and see if the hypothetical new position for the lines will result
1774 // in a different available line width.
1775 for (RootInlineBox* lineBox = layoutState.endLine(); lineBox; lineBox = lineBox->nextRootBox()) {
1777 // This isn't the real move we're going to do, so don't update the line box's pagination
1779 LayoutUnit oldPaginationStrut = lineBox->paginationStrut();
1780 lineDelta -= oldPaginationStrut;
1781 adjustLinePositionForPagination(lineBox, lineDelta);
1782 lineBox->setPaginationStrut(oldPaginationStrut);
1784 if (lineWidthForPaginatedLineChanged(lineBox, lineDelta))
1789 if (!lineDelta || !m_floatingObjects)
1792 // See if any floats end in the range along which we want to shift the lines vertically.
1793 LayoutUnit logicalTop = min(logicalHeight(), layoutState.endLineLogicalTop());
1795 RootInlineBox* lastLine = layoutState.endLine();
1796 while (RootInlineBox* nextLine = lastLine->nextRootBox())
1797 lastLine = nextLine;
1799 LayoutUnit logicalBottom = lastLine->lineBottomWithLeading() + absoluteValue(lineDelta);
1801 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
1802 FloatingObjectSetIterator end = floatingObjectSet.end();
1803 for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
1804 FloatingObject* f = *it;
1805 if (logicalBottomForFloat(f) >= logicalTop && logicalBottomForFloat(f) < logicalBottom)
1812 bool RenderBlock::matchedEndLine(LineLayoutState& layoutState, const InlineBidiResolver& resolver, const InlineIterator& endLineStart, const BidiStatus& endLineStatus)
1814 if (resolver.position() == endLineStart) {
1815 if (resolver.status() != endLineStatus)
1817 return checkPaginationAndFloatsAtEndLine(layoutState);
1820 // The first clean line doesn't match, but we can check a handful of following lines to try
1821 // to match back up.
1822 static int numLines = 8; // The # of lines we're willing to match against.
1823 RootInlineBox* originalEndLine = layoutState.endLine();
1824 RootInlineBox* line = originalEndLine;
1825 for (int i = 0; i < numLines && line; i++, line = line->nextRootBox()) {
1826 if (line->lineBreakObj() == resolver.position().m_obj && line->lineBreakPos() == resolver.position().m_pos) {
1828 if (line->lineBreakBidiStatus() != resolver.status())
1829 return false; // ...but the bidi state doesn't match.
1831 bool matched = false;
1832 RootInlineBox* result = line->nextRootBox();
1833 layoutState.setEndLine(result);
1835 layoutState.setEndLineLogicalTop(line->lineBottomWithLeading());
1836 matched = checkPaginationAndFloatsAtEndLine(layoutState);
1839 // Now delete the lines that we failed to sync.
1840 deleteLineRange(layoutState, renderArena(), originalEndLine, result);
1848 static inline bool skipNonBreakingSpace(const InlineIterator& it, const LineInfo& lineInfo)
1850 if (it.m_obj->style()->nbspMode() != SPACE || it.current() != noBreakSpace)
1853 // FIXME: This is bad. It makes nbsp inconsistent with space and won't work correctly
1854 // with m_minWidth/m_maxWidth.
1855 // Do not skip a non-breaking space if it is the first character
1856 // on a line after a clean line break (or on the first line, since previousLineBrokeCleanly starts off
1858 if (lineInfo.isEmpty() && lineInfo.previousLineBrokeCleanly())
1864 enum WhitespacePosition { LeadingWhitespace, TrailingWhitespace };
1865 static inline bool shouldCollapseWhiteSpace(const RenderStyle* style, const LineInfo& lineInfo, WhitespacePosition whitespacePosition)
1868 // If a space (U+0020) at the beginning of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is removed.
1869 // 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.
1870 // 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.
1871 return style->collapseWhiteSpace()
1872 || (whitespacePosition == TrailingWhitespace && style->whiteSpace() == PRE_WRAP && (!lineInfo.isEmpty() || !lineInfo.previousLineBrokeCleanly()));
1875 static bool requiresLineBoxForContent(RenderInline* flow, const LineInfo& lineInfo)
1877 RenderObject* parent = flow->parent();
1878 if (flow->document()->inNoQuirksMode()
1879 && (flow->style(lineInfo.isFirstLine())->lineHeight() != parent->style(lineInfo.isFirstLine())->lineHeight()
1880 || flow->style()->verticalAlign() != parent->style()->verticalAlign()
1881 || !parent->style()->font().fontMetrics().hasIdenticalAscentDescentAndLineGap(flow->style()->font().fontMetrics())))
1886 static bool alwaysRequiresLineBox(RenderInline* flow)
1888 // FIXME: Right now, we only allow line boxes for inlines that are truly empty.
1889 // We need to fix this, though, because at the very least, inlines containing only
1890 // ignorable whitespace should should also have line boxes.
1891 return !flow->firstChild() && flow->hasInlineDirectionBordersPaddingOrMargin();
1894 static bool requiresLineBox(const InlineIterator& it, const LineInfo& lineInfo = LineInfo(), WhitespacePosition whitespacePosition = LeadingWhitespace)
1896 if (it.m_obj->isFloatingOrOutOfFlowPositioned())
1899 if (it.m_obj->isRenderInline() && !alwaysRequiresLineBox(toRenderInline(it.m_obj)) && !requiresLineBoxForContent(toRenderInline(it.m_obj), lineInfo))
1902 if (!shouldCollapseWhiteSpace(it.m_obj->style(), lineInfo, whitespacePosition) || it.m_obj->isBR())
1905 UChar current = it.current();
1906 return current != ' ' && current != '\t' && current != softHyphen && (current != '\n' || it.m_obj->preservesNewline())
1907 && !skipNonBreakingSpace(it, lineInfo);
1910 bool RenderBlock::generatesLineBoxesForInlineChild(RenderObject* inlineObj)
1912 ASSERT(inlineObj->parent() == this);
1914 InlineIterator it(this, inlineObj, 0);
1915 // FIXME: We should pass correct value for WhitespacePosition.
1916 while (!it.atEnd() && !requiresLineBox(it))
1922 // FIXME: The entire concept of the skipTrailingWhitespace function is flawed, since we really need to be building
1923 // line boxes even for containers that may ultimately collapse away. Otherwise we'll never get positioned
1924 // elements quite right. In other words, we need to build this function's work into the normal line
1925 // object iteration process.
1926 // NB. this function will insert any floating elements that would otherwise
1927 // be skipped but it will not position them.
1928 void RenderBlock::LineBreaker::skipTrailingWhitespace(InlineIterator& iterator, const LineInfo& lineInfo)
1930 while (!iterator.atEnd() && !requiresLineBox(iterator, lineInfo, TrailingWhitespace)) {
1931 RenderObject* object = iterator.m_obj;
1932 if (object->isOutOfFlowPositioned())
1933 setStaticPositions(m_block, toRenderBox(object));
1934 else if (object->isFloating())
1935 m_block->insertFloatingObject(toRenderBox(object));
1936 iterator.increment();
1940 void RenderBlock::LineBreaker::skipLeadingWhitespace(InlineBidiResolver& resolver, LineInfo& lineInfo,
1941 FloatingObject* lastFloatFromPreviousLine, LineWidth& width)
1943 while (!resolver.position().atEnd() && !requiresLineBox(resolver.position(), lineInfo, LeadingWhitespace)) {
1944 RenderObject* object = resolver.position().m_obj;
1945 if (object->isOutOfFlowPositioned()) {
1946 setStaticPositions(m_block, toRenderBox(object));
1947 if (object->style()->isOriginalDisplayInlineType()) {
1948 resolver.runs().addRun(createRun(0, 1, object, resolver));
1949 lineInfo.incrementRunsFromLeadingWhitespace();
1951 } else if (object->isFloating())
1952 m_block->positionNewFloatOnLine(m_block->insertFloatingObject(toRenderBox(object)), lastFloatFromPreviousLine, lineInfo, width);
1953 else if (object->isText() && object->style()->hasTextCombine() && object->isCombineText() && !toRenderCombineText(object)->isCombined()) {
1954 toRenderCombineText(object)->combineText();
1955 if (toRenderCombineText(object)->isCombined())
1958 resolver.increment();
1960 resolver.commitExplicitEmbedding();
1963 // This is currently just used for list markers and inline flows that have line boxes. Neither should
1964 // have an effect on whitespace at the start of the line.
1965 static bool shouldSkipWhitespaceAfterStartObject(RenderBlock* block, RenderObject* o, LineMidpointState& lineMidpointState)
1967 RenderObject* next = bidiNextSkippingEmptyInlines(block, o);
1968 if (next && !next->isBR() && next->isText() && toRenderText(next)->textLength() > 0) {
1969 RenderText* nextText = toRenderText(next);
1970 UChar nextChar = nextText->characters()[0];
1971 if (nextText->style()->isCollapsibleWhiteSpace(nextChar)) {
1972 addMidpoint(lineMidpointState, InlineIterator(0, o, 0));
1980 static inline float textWidth(RenderText* text, unsigned from, unsigned len, const Font& font, float xPos, bool isFixedPitch, bool collapseWhiteSpace)
1982 if (isFixedPitch || (!from && len == text->textLength()) || text->style()->hasTextCombine())
1983 return text->width(from, len, font, xPos);
1985 TextRun run = RenderBlock::constructTextRun(text, font, text->characters() + from, len, text->style());
1986 run.setCharactersLength(text->textLength() - from);
1987 ASSERT(run.charactersLength() >= run.length());
1989 run.setCharacterScanForCodePath(!text->canUseSimpleFontCodePath());
1990 run.setTabSize(!collapseWhiteSpace, text->style()->tabSize());
1992 return font.width(run);
1995 static void tryHyphenating(RenderText* text, const Font& font, const AtomicString& localeIdentifier, unsigned consecutiveHyphenatedLines, int consecutiveHyphenatedLinesLimit, int minimumPrefixLength, int minimumSuffixLength, int lastSpace, int pos, float xPos, int availableWidth, bool isFixedPitch, bool collapseWhiteSpace, int lastSpaceWordSpacing, InlineIterator& lineBreak, int nextBreakable, bool& hyphenated)
1997 // Map 'hyphenate-limit-{before,after}: auto;' to 2.
1998 if (minimumPrefixLength < 0)
1999 minimumPrefixLength = 2;
2001 if (minimumSuffixLength < 0)
2002 minimumSuffixLength = 2;
2004 if (pos - lastSpace <= minimumSuffixLength)
2007 if (consecutiveHyphenatedLinesLimit >= 0 && consecutiveHyphenatedLines >= static_cast<unsigned>(consecutiveHyphenatedLinesLimit))
2010 int hyphenWidth = measureHyphenWidth(text, font);
2012 float maxPrefixWidth = availableWidth - xPos - hyphenWidth - lastSpaceWordSpacing;
2013 // If the maximum width available for the prefix before the hyphen is small, then it is very unlikely
2014 // that an hyphenation opportunity exists, so do not bother to look for it.
2015 if (maxPrefixWidth <= font.pixelSize() * 5 / 4)
2018 TextRun run = RenderBlock::constructTextRun(text, font, text->characters() + lastSpace, pos - lastSpace, text->style());
2019 run.setCharactersLength(text->textLength() - lastSpace);
2020 ASSERT(run.charactersLength() >= run.length());
2022 run.setTabSize(!collapseWhiteSpace, text->style()->tabSize());
2023 run.setXPos(xPos + lastSpaceWordSpacing);
2025 unsigned prefixLength = font.offsetForPosition(run, maxPrefixWidth, false);
2026 if (prefixLength < static_cast<unsigned>(minimumPrefixLength))
2029 prefixLength = lastHyphenLocation(text->characters() + lastSpace, pos - lastSpace, min(prefixLength, static_cast<unsigned>(pos - lastSpace - minimumSuffixLength)) + 1, localeIdentifier);
2030 if (!prefixLength || prefixLength < static_cast<unsigned>(minimumPrefixLength))
2033 // When lastSapce is a space, which it always is except sometimes at the beginning of a line or after collapsed
2034 // space, it should not count towards hyphenate-limit-before.
2035 if (prefixLength == static_cast<unsigned>(minimumPrefixLength)) {
2036 UChar characterAtLastSpace = text->characters()[lastSpace];
2037 if (characterAtLastSpace == ' ' || characterAtLastSpace == '\n' || characterAtLastSpace == '\t' || characterAtLastSpace == noBreakSpace)
2041 ASSERT(pos - lastSpace - prefixLength >= static_cast<unsigned>(minimumSuffixLength));
2043 #if !ASSERT_DISABLED
2044 float prefixWidth = hyphenWidth + textWidth(text, lastSpace, prefixLength, font, xPos, isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing;
2045 ASSERT(xPos + prefixWidth <= availableWidth);
2047 UNUSED_PARAM(isFixedPitch);
2050 lineBreak.moveTo(text, lastSpace + prefixLength, nextBreakable);
2054 class TrailingObjects {
2057 void setTrailingWhitespace(RenderText*);
2059 void appendBoxIfNeeded(RenderBox*);
2061 enum CollapseFirstSpaceOrNot { DoNotCollapseFirstSpace, CollapseFirstSpace };
2063 void updateMidpointsForTrailingBoxes(LineMidpointState&, const InlineIterator& lBreak, CollapseFirstSpaceOrNot);
2066 RenderText* m_whitespace;
2067 Vector<RenderBox*, 4> m_boxes;
2070 TrailingObjects::TrailingObjects()
2075 inline void TrailingObjects::setTrailingWhitespace(RenderText* whitespace)
2078 m_whitespace = whitespace;
2081 inline void TrailingObjects::clear()
2087 inline void TrailingObjects::appendBoxIfNeeded(RenderBox* box)
2090 m_boxes.append(box);
2093 void TrailingObjects::updateMidpointsForTrailingBoxes(LineMidpointState& lineMidpointState, const InlineIterator& lBreak, CollapseFirstSpaceOrNot collapseFirstSpace)
2098 // This object is either going to be part of the last midpoint, or it is going to be the actual endpoint.
2099 // In both cases we just decrease our pos by 1 level to exclude the space, allowing it to - in effect - collapse into the newline.
2100 if (lineMidpointState.numMidpoints % 2) {
2101 // Find the trailing space object's midpoint.
2102 int trailingSpaceMidpoint = lineMidpointState.numMidpoints - 1;
2103 for ( ; trailingSpaceMidpoint > 0 && lineMidpointState.midpoints[trailingSpaceMidpoint].m_obj != m_whitespace; --trailingSpaceMidpoint) { }
2104 ASSERT(trailingSpaceMidpoint >= 0);
2105 if (collapseFirstSpace == CollapseFirstSpace)
2106 lineMidpointState.midpoints[trailingSpaceMidpoint].m_pos--;
2108 // Now make sure every single trailingPositionedBox following the trailingSpaceMidpoint properly stops and starts
2110 size_t currentMidpoint = trailingSpaceMidpoint + 1;
2111 for (size_t i = 0; i < m_boxes.size(); ++i) {
2112 if (currentMidpoint >= lineMidpointState.numMidpoints) {
2113 // We don't have a midpoint for this box yet.
2114 InlineIterator ignoreStart(0, m_boxes[i], 0);
2115 addMidpoint(lineMidpointState, ignoreStart); // Stop ignoring.
2116 addMidpoint(lineMidpointState, ignoreStart); // Start ignoring again.
2118 ASSERT(lineMidpointState.midpoints[currentMidpoint].m_obj == m_boxes[i]);
2119 ASSERT(lineMidpointState.midpoints[currentMidpoint + 1].m_obj == m_boxes[i]);
2121 currentMidpoint += 2;
2123 } else if (!lBreak.m_obj) {
2124 ASSERT(m_whitespace->isText());
2125 ASSERT(collapseFirstSpace == CollapseFirstSpace);
2126 // Add a new end midpoint that stops right at the very end.
2127 unsigned length = m_whitespace->textLength();
2128 unsigned pos = length >= 2 ? length - 2 : UINT_MAX;
2129 InlineIterator endMid(0, m_whitespace, pos);
2130 addMidpoint(lineMidpointState, endMid);
2131 for (size_t i = 0; i < m_boxes.size(); ++i) {
2132 InlineIterator ignoreStart(0, m_boxes[i], 0);
2133 addMidpoint(lineMidpointState, ignoreStart); // Stop ignoring spaces.
2134 addMidpoint(lineMidpointState, ignoreStart); // Start ignoring again.
2139 void RenderBlock::LineBreaker::reset()
2141 m_positionedObjects.clear();
2142 m_hyphenated = false;
2146 InlineIterator RenderBlock::LineBreaker::nextLineBreak(InlineBidiResolver& resolver, LineInfo& lineInfo,
2147 LineBreakIteratorInfo& lineBreakIteratorInfo, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines)
2151 ASSERT(resolver.position().root() == m_block);
2153 bool appliedStartWidth = resolver.position().m_pos > 0;
2154 bool includeEndWidth = true;
2155 LineMidpointState& lineMidpointState = resolver.midpointState();
2157 LineWidth width(m_block, lineInfo.isFirstLine());
2159 skipLeadingWhitespace(resolver, lineInfo, lastFloatFromPreviousLine, width);
2161 if (resolver.position().atEnd())
2162 return resolver.position();
2164 // This variable is used only if whitespace isn't set to PRE, and it tells us whether
2165 // or not we are currently ignoring whitespace.
2166 bool ignoringSpaces = false;
2167 InlineIterator ignoreStart;
2169 // This variable tracks whether the very last character we saw was a space. We use
2170 // this to detect when we encounter a second space so we know we have to terminate
2172 bool currentCharacterIsSpace = false;
2173 bool currentCharacterIsWS = false;
2174 TrailingObjects trailingObjects;
2176 InlineIterator lBreak = resolver.position();
2178 // FIXME: It is error-prone to split the position object out like this.
2179 // Teach this code to work with objects instead of this split tuple.
2180 InlineIterator current = resolver.position();
2181 RenderObject* last = current.m_obj;
2182 bool atStart = true;
2184 bool startingNewParagraph = lineInfo.previousLineBrokeCleanly();
2185 lineInfo.setPreviousLineBrokeCleanly(false);
2187 bool autoWrapWasEverTrueOnLine = false;
2188 bool floatsFitOnLine = true;
2190 // Firefox and Opera will allow a table cell to grow to fit an image inside it under
2191 // very specific circumstances (in order to match common WinIE renderings).
2192 // Not supporting the quirk has caused us to mis-render some real sites. (See Bugzilla 10517.)
2193 RenderStyle* blockStyle = m_block->style();
2194 bool allowImagesToBreak = !m_block->document()->inQuirksMode() || !m_block->isTableCell() || !blockStyle->logicalWidth().isIntrinsicOrAuto();
2196 EWhiteSpace currWS = blockStyle->whiteSpace();
2197 EWhiteSpace lastWS = currWS;
2198 while (current.m_obj) {
2199 RenderStyle* currentStyle = current.m_obj->style();
2200 RenderObject* next = bidiNextSkippingEmptyInlines(m_block, current.m_obj);
2201 if (next && next->parent() && !next->parent()->isDescendantOf(current.m_obj->parent()))
2202 includeEndWidth = true;
2204 currWS = current.m_obj->isReplaced() ? current.m_obj->parent()->style()->whiteSpace() : currentStyle->whiteSpace();
2205 lastWS = last->isReplaced() ? last->parent()->style()->whiteSpace() : last->style()->whiteSpace();
2207 bool autoWrap = RenderStyle::autoWrap(currWS);
2208 autoWrapWasEverTrueOnLine = autoWrapWasEverTrueOnLine || autoWrap;
2211 bool preserveNewline = current.m_obj->isSVGInlineText() ? false : RenderStyle::preserveNewline(currWS);
2213 bool preserveNewline = RenderStyle::preserveNewline(currWS);
2216 bool collapseWhiteSpace = RenderStyle::collapseWhiteSpace(currWS);
2218 if (current.m_obj->isBR()) {
2219 if (width.fitsOnLine()) {
2220 lBreak.moveToStartOf(current.m_obj);
2223 // A <br> always breaks a line, so don't let the line be collapsed
2224 // away. Also, the space at the end of a line with a <br> does not
2225 // get collapsed away. It only does this if the previous line broke
2226 // cleanly. Otherwise the <br> has no effect on whether the line is
2228 if (startingNewParagraph)
2229 lineInfo.setEmpty(false, m_block, &width);
2230 trailingObjects.clear();
2231 lineInfo.setPreviousLineBrokeCleanly(true);
2233 if (!lineInfo.isEmpty())
2234 m_clear = currentStyle->clear();
2239 if (current.m_obj->isOutOfFlowPositioned()) {
2240 // If our original display wasn't an inline type, then we can
2241 // go ahead and determine our static inline position now.
2242 RenderBox* box = toRenderBox(current.m_obj);
2243 bool isInlineType = box->style()->isOriginalDisplayInlineType();
2245 m_block->setStaticInlinePositionForChild(box, m_block->logicalHeight(), m_block->startOffsetForContent(m_block->logicalHeight()));
2247 // If our original display was an INLINE type, then we can go ahead
2248 // and determine our static y position now.
2249 box->layer()->setStaticBlockPosition(m_block->logicalHeight());
2252 // If we're ignoring spaces, we have to stop and include this object and
2253 // then start ignoring spaces again.
2254 if (isInlineType || current.m_obj->container()->isRenderInline()) {
2255 if (ignoringSpaces) {
2256 ignoreStart.m_obj = current.m_obj;
2257 ignoreStart.m_pos = 0;
2258 addMidpoint(lineMidpointState, ignoreStart); // Stop ignoring spaces.
2259 addMidpoint(lineMidpointState, ignoreStart); // Start ignoring again.
2261 trailingObjects.appendBoxIfNeeded(box);
2263 m_positionedObjects.append(box);
2264 } else if (current.m_obj->isFloating()) {
2265 RenderBox* floatBox = toRenderBox(current.m_obj);
2266 FloatingObject* f = m_block->insertFloatingObject(floatBox);
2267 // check if it fits in the current line.
2268 // If it does, position it now, otherwise, position
2269 // it after moving to next line (in newLine() func)
2270 if (floatsFitOnLine && width.fitsOnLine(m_block->logicalWidthForFloat(f))) {
2271 m_block->positionNewFloatOnLine(f, lastFloatFromPreviousLine, lineInfo, width);
2272 if (lBreak.m_obj == current.m_obj) {
2273 ASSERT(!lBreak.m_pos);
2277 floatsFitOnLine = false;
2278 } else if (current.m_obj->isRenderInline()) {
2279 // Right now, we should only encounter empty inlines here.
2280 ASSERT(!current.m_obj->firstChild());
2282 RenderInline* flowBox = toRenderInline(current.m_obj);
2284 // Now that some inline flows have line boxes, if we are already ignoring spaces, we need
2285 // to make sure that we stop to include this object and then start ignoring spaces again.
2286 // If this object is at the start of the line, we need to behave like list markers and
2287 // start ignoring spaces.
2288 bool requiresLineBox = alwaysRequiresLineBox(flowBox);
2289 if (requiresLineBox || requiresLineBoxForContent(flowBox, lineInfo)) {
2290 // An empty inline that only has line-height, vertical-align or font-metrics will only get a
2291 // line box to affect the height of the line if the rest of the line is not empty.
2292 if (requiresLineBox)
2293 lineInfo.setEmpty(false, m_block, &width);
2294 if (ignoringSpaces) {
2295 trailingObjects.clear();
2296 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, 0)); // Stop ignoring spaces.
2297 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, 0)); // Start ignoring again.
2298 } else if (blockStyle->collapseWhiteSpace() && resolver.position().m_obj == current.m_obj
2299 && shouldSkipWhitespaceAfterStartObject(m_block, current.m_obj, lineMidpointState)) {
2300 // Like with list markers, we start ignoring spaces to make sure that any
2301 // additional spaces we see will be discarded.
2302 currentCharacterIsSpace = true;
2303 currentCharacterIsWS = true;
2304 ignoringSpaces = true;
2308 width.addUncommittedWidth(borderPaddingMarginStart(flowBox) + borderPaddingMarginEnd(flowBox));
2309 } else if (current.m_obj->isReplaced()) {
2310 RenderBox* replacedBox = toRenderBox(current.m_obj);
2311 replacedBox->layoutIfNeeded();
2313 // Break on replaced elements if either has normal white-space.
2314 if ((autoWrap || RenderStyle::autoWrap(lastWS)) && (!current.m_obj->isImage() || allowImagesToBreak)) {
2316 lBreak.moveToStartOf(current.m_obj);
2320 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, 0));
2322 lineInfo.setEmpty(false, m_block, &width);
2323 ignoringSpaces = false;
2324 currentCharacterIsSpace = false;
2325 currentCharacterIsWS = false;
2326 trailingObjects.clear();
2328 // Optimize for a common case. If we can't find whitespace after the list
2329 // item, then this is all moot.
2330 LayoutUnit replacedLogicalWidth = m_block->logicalWidthForChild(replacedBox) + m_block->marginStartForChild(replacedBox) + m_block->marginEndForChild(replacedBox) + inlineLogicalWidth(current.m_obj);
2331 if (current.m_obj->isListMarker()) {
2332 if (blockStyle->collapseWhiteSpace() && shouldSkipWhitespaceAfterStartObject(m_block, current.m_obj, lineMidpointState)) {
2333 // Like with inline flows, we start ignoring spaces to make sure that any
2334 // additional spaces we see will be discarded.
2335 currentCharacterIsSpace = true;
2336 currentCharacterIsWS = true;
2337 ignoringSpaces = true;
2339 if (toRenderListMarker(current.m_obj)->isInside())
2340 width.addUncommittedWidth(replacedLogicalWidth);
2342 width.addUncommittedWidth(replacedLogicalWidth);
2343 if (current.m_obj->isRubyRun())
2344 width.applyOverhang(toRenderRubyRun(current.m_obj), last, next);
2345 } else if (current.m_obj->isText()) {
2347 appliedStartWidth = false;
2349 RenderText* t = toRenderText(current.m_obj);
2352 bool isSVGText = t->isSVGInlineText();
2355 RenderStyle* style = t->style(lineInfo.isFirstLine());
2356 if (style->hasTextCombine() && current.m_obj->isCombineText() && !toRenderCombineText(current.m_obj)->isCombined())
2357 toRenderCombineText(current.m_obj)->combineText();
2359 const Font& f = style->font();
2360 bool isFixedPitch = f.isFixedPitch();
2361 bool canHyphenate = style->hyphens() == HyphensAuto && WebCore::canHyphenate(style->locale());
2363 int lastSpace = current.m_pos;
2364 float wordSpacing = currentStyle->wordSpacing();
2365 float lastSpaceWordSpacing = 0;
2367 // Non-zero only when kerning is enabled, in which case we measure words with their trailing
2368 // space, then subtract its width.
2369 float wordTrailingSpaceWidth = f.typesettingFeatures() & Kerning ? f.width(constructTextRun(t, f, &space, 1, style)) + wordSpacing : 0;
2371 float wrapW = width.uncommittedWidth() + inlineLogicalWidth(current.m_obj, !appliedStartWidth, true);
2372 float charWidth = 0;
2373 bool breakNBSP = autoWrap && currentStyle->nbspMode() == SPACE;
2374 // Auto-wrapping text should wrap in the middle of a word only if it could not wrap before the word,
2375 // which is only possible if the word is the first thing on the line, that is, if |w| is zero.
2376 bool breakWords = currentStyle->breakWords() && ((autoWrap && !width.committedWidth()) || currWS == PRE);
2377 bool midWordBreak = false;
2378 bool breakAll = currentStyle->wordBreak() == BreakAllWordBreak && autoWrap;
2379 float hyphenWidth = 0;
2381 if (t->isWordBreak()) {
2383 lBreak.moveToStartOf(current.m_obj);
2384 ASSERT(current.m_pos == t->textLength());
2387 for (; current.m_pos < t->textLength(); current.fastIncrementInTextNode()) {
2388 bool previousCharacterIsSpace = currentCharacterIsSpace;
2389 bool previousCharacterIsWS = currentCharacterIsWS;
2390 UChar c = current.current();
2391 currentCharacterIsSpace = c == ' ' || c == '\t' || (!preserveNewline && (c == '\n'));
2393 if (!collapseWhiteSpace || !currentCharacterIsSpace)
2394 lineInfo.setEmpty(false, m_block, &width);
2396 if (c == softHyphen && autoWrap && !hyphenWidth && style->hyphens() != HyphensNone) {
2397 hyphenWidth = measureHyphenWidth(t, f);
2398 width.addUncommittedWidth(hyphenWidth);
2401 bool applyWordSpacing = false;
2403 currentCharacterIsWS = currentCharacterIsSpace || (breakNBSP && c == noBreakSpace);
2405 if ((breakAll || breakWords) && !midWordBreak) {
2407 bool midWordBreakIsBeforeSurrogatePair = U16_IS_LEAD(c) && current.m_pos + 1 < t->textLength() && U16_IS_TRAIL(t->characters()[current.m_pos + 1]);
2408 charWidth = textWidth(t, current.m_pos, midWordBreakIsBeforeSurrogatePair ? 2 : 1, f, width.committedWidth() + wrapW, isFixedPitch, collapseWhiteSpace);
2409 midWordBreak = width.committedWidth() + wrapW + charWidth > width.availableWidth();
2412 if ((lineBreakIteratorInfo.first != t) || (lineBreakIteratorInfo.second.string() != t->characters())) {
2413 lineBreakIteratorInfo.first = t;
2414 lineBreakIteratorInfo.second.reset(t->characters(), t->textLength(), style->locale());
2417 bool betweenWords = c == '\n' || (currWS != PRE && !atStart && isBreakable(lineBreakIteratorInfo.second, current.m_pos, current.m_nextBreakablePosition, breakNBSP)
2418 && (style->hyphens() != HyphensNone || (current.previousInSameNode() != softHyphen)));
2420 if (betweenWords || midWordBreak) {
2421 bool stoppedIgnoringSpaces = false;
2422 if (ignoringSpaces) {
2423 if (!currentCharacterIsSpace) {
2424 // Stop ignoring spaces and begin at this
2426 ignoringSpaces = false;
2427 lastSpaceWordSpacing = 0;
2428 lastSpace = current.m_pos; // e.g., "Foo goo", don't add in any of the ignored spaces.
2429 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos));
2430 stoppedIgnoringSpaces = true;
2432 // Just keep ignoring these spaces.
2437 float additionalTmpW;
2438 if (wordTrailingSpaceWidth && currentCharacterIsSpace)
2439 additionalTmpW = textWidth(t, lastSpace, current.m_pos + 1 - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) - wordTrailingSpaceWidth + lastSpaceWordSpacing;
2441 additionalTmpW = textWidth(t, lastSpace, current.m_pos - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing;
2442 width.addUncommittedWidth(additionalTmpW);
2443 if (!appliedStartWidth) {
2444 width.addUncommittedWidth(inlineLogicalWidth(current.m_obj, true, false));
2445 appliedStartWidth = true;
2448 applyWordSpacing = wordSpacing && currentCharacterIsSpace && !previousCharacterIsSpace;
2450 if (!width.committedWidth() && autoWrap && !width.fitsOnLine())
2451 width.fitBelowFloats();
2453 if (autoWrap || breakWords) {
2454 // If we break only after white-space, consider the current character
2455 // as candidate width for this line.
2456 bool lineWasTooWide = false;
2457 if (width.fitsOnLine() && currentCharacterIsWS && currentStyle->breakOnlyAfterWhiteSpace() && !midWordBreak) {
2458 float charWidth = textWidth(t, current.m_pos, 1, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) + (applyWordSpacing ? wordSpacing : 0);
2459 // Check if line is too big even without the extra space
2460 // at the end of the line. If it is not, do nothing.
2461 // If the line needs the extra whitespace to be too long,
2462 // then move the line break to the space and skip all
2463 // additional whitespace.
2464 if (!width.fitsOnLine(charWidth)) {
2465 lineWasTooWide = true;
2466 lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2467 skipTrailingWhitespace(lBreak, lineInfo);
2470 if (lineWasTooWide || !width.fitsOnLine()) {
2471 if (canHyphenate && !width.fitsOnLine()) {
2472 tryHyphenating(t, f, style->locale(), consecutiveHyphenatedLines, blockStyle->hyphenationLimitLines(), style->hyphenationLimitBefore(), style->hyphenationLimitAfter(), lastSpace, current.m_pos, width.currentWidth() - additionalTmpW, width.availableWidth(), isFixedPitch, collapseWhiteSpace, lastSpaceWordSpacing, lBreak, current.m_nextBreakablePosition, m_hyphenated);
2476 if (lBreak.atTextParagraphSeparator()) {
2477 if (!stoppedIgnoringSpaces && current.m_pos > 0) {
2478 // We need to stop right before the newline and then start up again.
2479 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos - 1)); // Stop
2480 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos)); // Start
2483 lineInfo.setPreviousLineBrokeCleanly(true);
2485 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)
2486 m_hyphenated = true;
2487 goto end; // Didn't fit. Jump to the end.
2489 if (!betweenWords || (midWordBreak && !autoWrap))
2490 width.addUncommittedWidth(-additionalTmpW);
2492 // Subtract the width of the soft hyphen out since we fit on a line.
2493 width.addUncommittedWidth(-hyphenWidth);
2499 if (c == '\n' && preserveNewline) {
2500 if (!stoppedIgnoringSpaces && current.m_pos > 0) {
2501 // We need to stop right before the newline and then start up again.
2502 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos - 1)); // Stop
2503 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos)); // Start
2505 lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2507 lineInfo.setPreviousLineBrokeCleanly(true);
2511 if (autoWrap && betweenWords) {
2514 lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2515 // Auto-wrapping text should not wrap in the middle of a word once it has had an
2516 // opportunity to break after a word.
2520 if (midWordBreak && !U16_IS_TRAIL(c) && !(category(c) & (Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining))) {
2521 // Remember this as a breakable position in case
2522 // adding the end width forces a break.
2523 lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2524 midWordBreak &= (breakWords || breakAll);
2528 lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
2529 lastSpace = current.m_pos;
2532 if (!ignoringSpaces && currentStyle->collapseWhiteSpace()) {
2533 // If we encounter a newline, or if we encounter a
2534 // second space, we need to go ahead and break up this
2535 // run and enter a mode where we start collapsing spaces.
2536 if (currentCharacterIsSpace && previousCharacterIsSpace) {
2537 ignoringSpaces = true;
2539 // We just entered a mode where we are ignoring
2540 // spaces. Create a midpoint to terminate the run
2541 // before the second space.
2542 addMidpoint(lineMidpointState, ignoreStart);
2543 trailingObjects.updateMidpointsForTrailingBoxes(lineMidpointState, InlineIterator(), TrailingObjects::DoNotCollapseFirstSpace);
2546 } else if (ignoringSpaces) {
2547 // Stop ignoring spaces and begin at this
2549 ignoringSpaces = false;
2550 lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
2551 lastSpace = current.m_pos; // e.g., "Foo goo", don't add in any of the ignored spaces.
2552 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos));
2556 if (isSVGText && current.m_pos > 0) {
2557 // Force creation of new InlineBoxes for each absolute positioned character (those that start new text chunks).
2558 if (toRenderSVGInlineText(t)->characterStartsNewTextChunk(current.m_pos)) {
2559 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos - 1));
2560 addMidpoint(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos));
2565 if (currentCharacterIsSpace && !previousCharacterIsSpace) {
2566 ignoreStart.m_obj = current.m_obj;
2567 ignoreStart.m_pos = current.m_pos;
2570 if (!currentCharacterIsWS && previousCharacterIsWS) {
2571 if (autoWrap && currentStyle->breakOnlyAfterWhiteSpace())
2572 lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
2575 if (collapseWhiteSpace && currentCharacterIsSpace && !ignoringSpaces)
2576 trailingObjects.setTrailingWhitespace(toRenderText(current.m_obj));
2577 else if (!currentStyle->collapseWhiteSpace() || !currentCharacterIsSpace)
2578 trailingObjects.clear();
2583 // IMPORTANT: current.m_pos is > length here!
2584 float additionalTmpW = ignoringSpaces ? 0 : textWidth(t, lastSpace, current.m_pos - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace) + lastSpaceWordSpacing;
2585 width.addUncommittedWidth(additionalTmpW + inlineLogicalWidth(current.m_obj, !appliedStartWidth, includeEndWidth));
2586 includeEndWidth = false;
2588 if (!width.fitsOnLine()) {
2590 tryHyphenating(t, f, style->locale(), consecutiveHyphenatedLines, blockStyle->hyphenationLimitLines(), style->hyphenationLimitBefore(), style->hyphenationLimitAfter(), lastSpace, current.m_pos, width.currentWidth() - additionalTmpW, width.availableWidth(), isFixedPitch, collapseWhiteSpace, lastSpaceWordSpacing, lBreak, current.m_nextBreakablePosition, m_hyphenated);
2592 if (!m_hyphenated && lBreak.previousInSameNode() == softHyphen && style->hyphens() != HyphensNone)
2593 m_hyphenated = true;
2599 ASSERT_NOT_REACHED();
2601 bool checkForBreak = autoWrap;
2602 if (width.committedWidth() && !width.fitsOnLine() && lBreak.m_obj && currWS == NOWRAP)
2603 checkForBreak = true;
2604 else if (next && current.m_obj->isText() && next->isText() && !next->isBR() && (autoWrap || (next->style()->autoWrap()))) {
2605 if (currentCharacterIsSpace)
2606 checkForBreak = true;
2608 RenderText* nextText = toRenderText(next);
2609 if (nextText->textLength()) {
2610 UChar c = nextText->characters()[0];
2611 checkForBreak = (c == ' ' || c == '\t' || (c == '\n' && !next->preservesNewline()));
2612 // If the next item on the line is text, and if we did not end with
2613 // a space, then the next text run continues our word (and so it needs to
2614 // keep adding to |tmpW|. Just update and continue.
2615 } else if (nextText->isWordBreak())
2616 checkForBreak = true;
2618 if (!width.fitsOnLine() && !width.committedWidth())
2619 width.fitBelowFloats();
2621 bool canPlaceOnLine = width.fitsOnLine() || !autoWrapWasEverTrueOnLine;
2622 if (canPlaceOnLine && checkForBreak) {
2624 lBreak.moveToStartOf(next);
2629 if (checkForBreak && !width.fitsOnLine()) {
2630 // if we have floats, try to get below them.
2631 if (currentCharacterIsSpace && !ignoringSpaces && currentStyle->collapseWhiteSpace())
2632 trailingObjects.clear();
2634 if (width.committedWidth())
2637 width.fitBelowFloats();
2639 // |width| may have been adjusted because we got shoved down past a float (thus
2640 // giving us more room), so we need to retest, and only jump to
2641 // the end label if we still don't fit on the line. -dwh
2642 if (!width.fitsOnLine())
2646 if (!current.m_obj->isFloatingOrOutOfFlowPositioned()) {
2647 last = current.m_obj;
2648 if (last->isReplaced() && autoWrap && (!last->isImage() || allowImagesToBreak) && (!last->isListMarker() || toRenderListMarker(last)->isInside())) {
2650 lBreak.moveToStartOf(next);
2654 // Clear out our character space bool, since inline <pre>s don't collapse whitespace
2655 // with adjacent inline normal/nowrap spans.
2656 if (!collapseWhiteSpace)
2657 currentCharacterIsSpace = false;
2659 current.moveToStartOf(next);
2663 if (width.fitsOnLine() || lastWS == NOWRAP)
2667 if (lBreak == resolver.position() && (!lBreak.m_obj || !lBreak.m_obj->isBR())) {
2668 // we just add as much as possible
2669 if (blockStyle->whiteSpace() == PRE) {
2670 // FIXME: Don't really understand this case.
2671 if (current.m_pos) {
2672 // FIXME: This should call moveTo which would clear m_nextBreakablePosition
2673 // this code as-is is likely wrong.
2674 lBreak.m_obj = current.m_obj;
2675 lBreak.m_pos = current.m_pos - 1;
2677 lBreak.moveTo(last, last->isText() ? last->length() : 0);
2678 } else if (lBreak.m_obj) {
2679 // Don't ever break in the middle of a word if we can help it.
2680 // There's no room at all. We just have to be on this line,
2681 // even though we'll spill out.
2682 lBreak.moveTo(current.m_obj, current.m_pos);
2686 // make sure we consume at least one char/object.
2687 if (lBreak == resolver.position())
2690 // Sanity check our midpoints.
2691 checkMidpoints(lineMidpointState, lBreak);
2693 trailingObjects.updateMidpointsForTrailingBoxes(lineMidpointState, lBreak, TrailingObjects::CollapseFirstSpace);
2695 // We might have made lBreak an iterator that points past the end
2696 // of the object. Do this adjustment to make it point to the start
2697 // of the next object instead to avoid confusing the rest of the
2699 if (lBreak.m_pos > 0) {
2707 void RenderBlock::addOverflowFromInlineChildren()
2709 LayoutUnit endPadding = hasOverflowClip() ? paddingEnd() : ZERO_LAYOUT_UNIT;
2710 // FIXME: Need to find another way to do this, since scrollbars could show when we don't want them to.
2711 if (hasOverflowClip() && !endPadding && node() && node()->isRootEditableElement() && style()->isLeftToRightDirection())
2713 for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
2714 addLayoutOverflow(curr->paddedLayoutOverflowRect(endPadding));
2715 if (!hasOverflowClip())
2716 addVisualOverflow(curr->visualOverflowRect(curr->lineTop(), curr->lineBottom()));
2720 void RenderBlock::deleteEllipsisLineBoxes()
2722 ETextAlign textAlign = style()->textAlign();
2723 bool ltr = style()->isLeftToRightDirection();
2724 bool firstLine = true;
2725 for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
2726 if (curr->hasEllipsisBox()) {
2727 curr->clearTruncation();
2729 // Shift the line back where it belongs if we cannot accomodate an ellipsis.
2730 float logicalLeft = pixelSnappedLogicalLeftOffsetForLine(curr->lineTop(), firstLine);
2731 float availableLogicalWidth = logicalRightOffsetForLine(curr->lineTop(), false) - logicalLeft;
2732 float totalLogicalWidth = curr->logicalWidth();
2733 updateLogicalWidthForAlignment(textAlign, 0, logicalLeft, totalLogicalWidth, availableLogicalWidth, 0);
2736 curr->adjustLogicalPosition((logicalLeft - curr->logicalLeft()), 0);
2738 curr->adjustLogicalPosition(-(curr->logicalLeft() - logicalLeft), 0);
2744 void RenderBlock::checkLinesForTextOverflow()
2746 // Determine the width of the ellipsis using the current font.
2747 // FIXME: CSS3 says this is configurable, also need to use 0x002E (FULL STOP) if horizontal ellipsis is "not renderable"
2748 const Font& font = style()->font();
2749 DEFINE_STATIC_LOCAL(AtomicString, ellipsisStr, (&horizontalEllipsis, 1));
2750 const Font& firstLineFont = firstLineStyle()->font();
2751 int firstLineEllipsisWidth = firstLineFont.width(constructTextRun(this, firstLineFont, &horizontalEllipsis, 1, firstLineStyle()));
2752 int ellipsisWidth = (font == firstLineFont) ? firstLineEllipsisWidth : font.width(constructTextRun(this, font, &horizontalEllipsis, 1, style()));
2754 // For LTR text truncation, we want to get the right edge of our padding box, and then we want to see
2755 // if the right edge of a line box exceeds that. For RTL, we use the left edge of the padding box and
2756 // check the left edge of the line box to see if it is less
2757 // Include the scrollbar for overflow blocks, which means we want to use "contentWidth()"
2758 bool ltr = style()->isLeftToRightDirection();
2759 ETextAlign textAlign = style()->textAlign();
2760 bool firstLine = true;
2761 for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
2762 LayoutUnit blockRightEdge = logicalRightOffsetForLine(curr->lineTop(), firstLine);
2763 LayoutUnit blockLeftEdge = logicalLeftOffsetForLine(curr->lineTop(), firstLine);
2764 LayoutUnit lineBoxEdge = ltr ? curr->x() + curr->logicalWidth() : curr->x();
2765 if ((ltr && lineBoxEdge > blockRightEdge) || (!ltr && lineBoxEdge < blockLeftEdge)) {
2766 // This line spills out of our box in the appropriate direction. Now we need to see if the line
2767 // can be truncated. In order for truncation to be possible, the line must have sufficient space to
2768 // accommodate our truncation string, and no replaced elements (images, tables) can overlap the ellipsis
2771 LayoutUnit width = firstLine ? firstLineEllipsisWidth : ellipsisWidth;
2772 LayoutUnit blockEdge = ltr ? blockRightEdge : blockLeftEdge;
2773 if (curr->lineCanAccommodateEllipsis(ltr, blockEdge, lineBoxEdge, width)) {
2774 float totalLogicalWidth = curr->placeEllipsis(ellipsisStr, ltr, blockLeftEdge, blockRightEdge, width);
2776 float logicalLeft = 0; // We are only intersted in the delta from the base position.
2777 float truncatedWidth = pixelSnappedLogicalRightOffsetForLine(curr->lineTop(), firstLine);
2778 updateLogicalWidthForAlignment(textAlign, 0, logicalLeft, totalLogicalWidth, truncatedWidth, 0);
2780 curr->adjustLogicalPosition(logicalLeft, 0);
2782 curr->adjustLogicalPosition(-(truncatedWidth - (logicalLeft + totalLogicalWidth)), 0);
2789 bool RenderBlock::positionNewFloatOnLine(FloatingObject* newFloat, FloatingObject* lastFloatFromPreviousLine, LineInfo& lineInfo, LineWidth& width)
2791 if (!positionNewFloats())
2794 width.shrinkAvailableWidthForNewFloatIfNeeded(newFloat);
2796 // We only connect floats to lines for pagination purposes if the floats occur at the start of
2797 // the line and the previous line had a hard break (so this line is either the first in the block
2798 // or follows a <br>).
2799 if (!newFloat->m_paginationStrut || !lineInfo.previousLineBrokeCleanly() || !lineInfo.isEmpty())
2802 const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
2803 ASSERT(floatingObjectSet.last() == newFloat);
2805 LayoutUnit floatLogicalTop = logicalTopForFloat(newFloat);
2806 int paginationStrut = newFloat->m_paginationStrut;
2808 if (floatLogicalTop - paginationStrut != logicalHeight() + lineInfo.floatPaginationStrut())
2811 FloatingObjectSetIterator it = floatingObjectSet.end();
2812 --it; // Last float is newFloat, skip that one.
2813 FloatingObjectSetIterator begin = floatingObjectSet.begin();
2814 while (it != begin) {
2816 FloatingObject* f = *it;
2817 if (f == lastFloatFromPreviousLine)
2819 if (logicalTopForFloat(f) == logicalHeight() + lineInfo.floatPaginationStrut()) {
2820 f->m_paginationStrut += paginationStrut;
2821 RenderBox* o = f->m_renderer;
2822 setLogicalTopForChild(o, logicalTopForChild(o) + marginBeforeForChild(o) + paginationStrut);
2823 if (o->isRenderBlock())
2824 toRenderBlock(o)->setChildNeedsLayout(true, MarkOnlyThis);
2825 o->layoutIfNeeded();
2826 // Save the old logical top before calling removePlacedObject which will set
2827 // isPlaced to false. Otherwise it will trigger an assert in logicalTopForFloat.
2828 LayoutUnit oldLogicalTop = logicalTopForFloat(f);
2829 m_floatingObjects->removePlacedObject(f);
2830 setLogicalTopForFloat(f, oldLogicalTop + paginationStrut);
2831 m_floatingObjects->addPlacedObject(f);
2835 // Just update the line info's pagination strut without altering our logical height yet. If the line ends up containing
2836 // no content, then we don't want to improperly grow the height of the block.
2837 lineInfo.setFloatPaginationStrut(lineInfo.floatPaginationStrut() + paginationStrut);
2841 LayoutUnit RenderBlock::startAlignedOffsetForLine(LayoutUnit position, bool firstLine)
2843 ETextAlign textAlign = style()->textAlign();
2845 if (textAlign == TASTART) // FIXME: Handle TAEND here
2846 return startOffsetForLine(position, firstLine);
2848 // updateLogicalWidthForAlignment() handles the direction of the block so no need to consider it here
2849 float totalLogicalWidth = 0;
2850 float logicalLeft = logicalLeftOffsetForLine(logicalHeight(), false);
2851 float availableLogicalWidth = logicalRightOffsetForLine(logicalHeight(), false) - logicalLeft;
2852 updateLogicalWidthForAlignment(textAlign, 0, logicalLeft, totalLogicalWidth, availableLogicalWidth, 0);
2854 if (!style()->isLeftToRightDirection())
2855 return logicalWidth() - logicalLeft;
2860 void RenderBlock::layoutLineGridBox()
2862 if (style()->lineGrid() == RenderStyle::initialLineGrid()) {
2869 RootInlineBox* lineGridBox = new (renderArena()) RootInlineBox(this);
2870 lineGridBox->setHasTextChildren(); // Needed to make the line ascent/descent actually be honored in quirks mode.
2871 lineGridBox->setConstructed();
2872 GlyphOverflowAndFallbackFontsMap textBoxDataMap;
2873 VerticalPositionCache verticalPositionCache;
2874 lineGridBox->alignBoxesInBlockDirection(logicalHeight(), textBoxDataMap, verticalPositionCache);
2876 setLineGridBox(lineGridBox);
2878 // FIXME: If any of the characteristics of the box change compared to the old one, then we need to do a deep dirtying
2879 // (similar to what happens when the page height changes). Ideally, though, we only do this if someone is actually snapping