2 * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
3 * Copyright (C) 2004, 2006, 2007, 2008 Apple Inc. All right reserved.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Library General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Library General Public License for more details.
15 * You should have received a copy of the GNU Library General Public License
16 * along with this library; see the file COPYING.LIB. If not, write to
17 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 * Boston, MA 02110-1301, USA.
25 #include "CharacterNames.h"
28 #include "FrameView.h"
29 #include "InlineTextBox.h"
31 #include "RenderArena.h"
32 #include "RenderLayer.h"
33 #include "RenderListMarker.h"
34 #include "RenderView.h"
35 #include "break_lines.h"
36 #include <wtf/AlwaysInline.h>
37 #include <wtf/Vector.h>
41 using namespace Unicode;
45 // We don't let our line box tree for a single line get any deeper than this.
46 const unsigned cMaxLineDepth = 200;
57 BidiIterator(RenderBlock* b, RenderObject* o, unsigned p)
64 void increment(BidiResolver<BidiIterator, BidiRun>& state);
67 UChar current() const;
68 WTF::Unicode::Direction direction() const;
75 // Used to track a list of chained bidi runs.
76 static BidiRun* sFirstBidiRun;
77 static BidiRun* sLastBidiRun;
78 static BidiRun* sLogicallyLastBidiRun;
79 static int sBidiRunCount;
81 // Midpoint globals. The goal is not to do any allocation when dealing with
82 // these midpoints, so we just keep an array around and never clear it. We track
83 // the number of items and position using the two other variables.
84 static Vector<BidiIterator>* smidpoints;
85 static unsigned sNumMidpoints;
86 static unsigned sCurrMidpoint;
87 static bool betweenMidpoints;
89 static bool isLineEmpty = true;
90 static bool previousLineBrokeCleanly = true;
93 static int getBPMWidth(int childValue, Length cssUnit)
95 if (!cssUnit.isIntrinsicOrAuto())
96 return (cssUnit.isFixed() ? cssUnit.value() : childValue);
100 static int getBorderPaddingMargin(RenderObject* child, bool endOfInline)
102 RenderStyle* cstyle = child->style();
104 bool leftSide = (cstyle->direction() == LTR) ? !endOfInline : endOfInline;
105 result += getBPMWidth((leftSide ? child->marginLeft() : child->marginRight()),
106 (leftSide ? cstyle->marginLeft() :
107 cstyle->marginRight()));
108 result += getBPMWidth((leftSide ? child->paddingLeft() : child->paddingRight()),
109 (leftSide ? cstyle->paddingLeft() :
110 cstyle->paddingRight()));
111 result += leftSide ? child->borderLeft() : child->borderRight();
115 static int inlineWidth(RenderObject* child, bool start = true, bool end = true)
117 unsigned lineDepth = 1;
119 RenderObject* parent = child->parent();
120 while (parent->isInline() && !parent->isInlineBlockOrInlineTable() && lineDepth++ < cMaxLineDepth) {
121 if (start && parent->firstChild() == child)
122 extraWidth += getBorderPaddingMargin(parent, false);
123 if (end && parent->lastChild() == child)
124 extraWidth += getBorderPaddingMargin(parent, true);
126 parent = child->parent();
132 WTFLogChannel LogWebCoreBidiRunLeaks = { 0x00000000, "", WTFLogChannelOn };
134 struct BidiRunCounter {
139 LOG(WebCoreBidiRunLeaks, "LEAK: %d BidiRun\n", count);
142 int BidiRunCounter::count = 0;
143 static BidiRunCounter bidiRunCounter;
145 static bool inBidiRunDestroy;
148 void BidiRun::destroy(RenderArena* renderArena)
151 inBidiRunDestroy = true;
155 inBidiRunDestroy = false;
158 // Recover the size left there for us by operator delete and free the memory.
159 renderArena->free(*(size_t *)this, this);
162 void* BidiRun::operator new(size_t sz, RenderArena* renderArena) throw()
165 ++BidiRunCounter::count;
167 return renderArena->allocate(sz);
170 void BidiRun::operator delete(void* ptr, size_t sz)
173 --BidiRunCounter::count;
175 ASSERT(inBidiRunDestroy);
177 // Stash size where destroy() can find it.
182 void BidiState::deleteRuns()
188 BidiRun* curr = m_firstRun;
190 BidiRun* s = curr->next();
191 curr->destroy(curr->obj->renderArena());
200 // ---------------------------------------------------------------------
202 inline bool operator==(const BidiIterator& it1, const BidiIterator& it2)
204 return it1.pos == it2.pos && it1.obj == it2.obj;
207 inline bool operator!=(const BidiIterator& it1, const BidiIterator& it2)
209 return it1.pos != it2.pos || it1.obj != it2.obj;
212 static inline RenderObject* bidiNext(RenderBlock* block, RenderObject* current, BidiState& bidi,
213 bool skipInlines = true, bool* endOfInline = 0)
215 RenderObject* next = 0;
216 bool oldEndOfInline = endOfInline ? *endOfInline : false;
218 *endOfInline = false;
222 if (!oldEndOfInline && !current->isFloating() && !current->isReplaced() && !current->isPositioned()) {
223 next = current->firstChild();
224 if (next && bidi.adjustEmbedding() && next->isInlineFlow()) {
225 EUnicodeBidi ub = next->style()->unicodeBidi();
226 if (ub != UBNormal) {
227 TextDirection dir = next->style()->direction();
228 Direction d = (ub == Embed
229 ? (dir == RTL ? RightToLeftEmbedding : LeftToRightEmbedding)
230 : (dir == RTL ? RightToLeftOverride : LeftToRightOverride));
237 if (!skipInlines && !oldEndOfInline && current->isInlineFlow()) {
244 while (current && current != block) {
245 if (bidi.adjustEmbedding() && current->isInlineFlow() && current->style()->unicodeBidi() != UBNormal)
246 bidi.embed(PopDirectionalFormat);
248 next = current->nextSibling();
250 if (bidi.adjustEmbedding() && next->isInlineFlow()) {
251 EUnicodeBidi ub = next->style()->unicodeBidi();
252 if (ub != UBNormal) {
253 TextDirection dir = next->style()->direction();
254 Direction d = (ub == Embed
255 ? (dir == RTL ? RightToLeftEmbedding: LeftToRightEmbedding)
256 : (dir == RTL ? RightToLeftOverride : LeftToRightOverride));
263 current = current->parent();
264 if (!skipInlines && current && current != block && current->isInlineFlow()) {
276 if (next->isText() || next->isFloating() || next->isReplaced() || next->isPositioned()
277 || ((!skipInlines || !next->firstChild()) // Always return EMPTY inlines.
278 && next->isInlineFlow()))
285 static RenderObject* bidiFirst(RenderBlock* block, BidiState& bidi, bool skipInlines = true )
287 if (!block->firstChild())
290 RenderObject* o = block->firstChild();
291 if (o->isInlineFlow()) {
292 if (bidi.adjustEmbedding()) {
293 EUnicodeBidi ub = o->style()->unicodeBidi();
294 if (ub != UBNormal) {
295 TextDirection dir = o->style()->direction();
296 Direction d = (ub == Embed
297 ? (dir == RTL ? RightToLeftEmbedding : LeftToRightEmbedding)
298 : (dir == RTL ? RightToLeftOverride : LeftToRightOverride));
302 if (skipInlines && o->firstChild())
303 o = bidiNext(block, o, bidi, skipInlines);
305 return o; // Never skip empty inlines.
308 if (o && !o->isText() && !o->isReplaced() && !o->isFloating() && !o->isPositioned())
309 o = bidiNext(block, o, bidi, skipInlines);
313 inline void BidiIterator::increment(BidiState& bidi)
319 if (pos >= static_cast<RenderText *>(obj)->textLength()) {
320 obj = bidiNext(block, obj, bidi);
324 obj = bidiNext(block, obj, bidi);
329 inline bool BidiIterator::atEnd() const
334 UChar BidiIterator::current() const
336 if (!obj || !obj->isText())
339 RenderText* text = static_cast<RenderText*>(obj);
340 if (!text->characters())
343 return text->characters()[pos];
346 ALWAYS_INLINE Direction BidiIterator::direction() const
350 if (obj->isListMarker())
351 return obj->style()->direction() == LTR ? LeftToRight : RightToLeft;
354 RenderText* renderTxt = static_cast<RenderText*>(obj);
355 if (pos >= renderTxt->textLength())
357 return Unicode::direction(renderTxt->characters()[pos]);
360 // -------------------------------------------------------------------------------------------------
363 inline void BidiState::addRun(BidiRun* bidiRun)
366 m_firstRun = bidiRun;
368 m_lastRun->m_next = bidiRun;
372 sLogicallyLastBidiRun = bidiRun;
374 // Compute the number of spaces in this run,
375 if (bidiRun->obj && bidiRun->obj->isText()) {
376 RenderText* text = static_cast<RenderText*>(bidiRun->obj);
377 if (text->characters()) {
378 for (int i = bidiRun->m_start; i < bidiRun->m_stop; i++) {
379 UChar c = text->characters()[i];
380 if (c == ' ' || c == '\n' || c == '\t')
387 static void chopMidpointsAt(RenderObject* obj, unsigned pos)
391 BidiIterator* midpoints = smidpoints->data();
392 for (unsigned i = 0; i < sNumMidpoints; i++) {
393 const BidiIterator& point = midpoints[i];
394 if (point.obj == obj && point.pos == pos) {
401 static void checkMidpoints(BidiIterator& lBreak, BidiState& bidi)
403 // Check to see if our last midpoint is a start point beyond the line break. If so,
404 // shave it off the list, and shave off a trailing space if the previous end point doesn't
405 // preserve whitespace.
406 if (lBreak.obj && sNumMidpoints && sNumMidpoints%2 == 0) {
407 BidiIterator* midpoints = smidpoints->data();
408 BidiIterator& endpoint = midpoints[sNumMidpoints-2];
409 const BidiIterator& startpoint = midpoints[sNumMidpoints-1];
410 BidiIterator currpoint = endpoint;
411 while (!currpoint.atEnd() && currpoint != startpoint && currpoint != lBreak)
412 currpoint.increment(bidi);
413 if (currpoint == lBreak) {
414 // We hit the line break before the start point. Shave off the start point.
416 if (endpoint.obj->style()->collapseWhiteSpace()) {
417 if (endpoint.obj->isText()) {
418 // Don't shave a character off the endpoint if it was from a soft hyphen.
419 RenderText* textObj = static_cast<RenderText*>(endpoint.obj);
420 if (endpoint.pos + 1 < textObj->textLength()) {
421 if (textObj->characters()[endpoint.pos+1] == softHyphen)
423 } else if (startpoint.obj->isText()) {
424 RenderText *startText = static_cast<RenderText*>(startpoint.obj);
425 if (startText->textLength() && startText->characters()[0] == softHyphen)
435 static void addMidpoint(const BidiIterator& midpoint)
440 if (smidpoints->size() <= sNumMidpoints)
441 smidpoints->grow(sNumMidpoints + 10);
443 BidiIterator* midpoints = smidpoints->data();
444 midpoints[sNumMidpoints++] = midpoint;
447 static void appendRunsForObject(int start, int end, RenderObject* obj, BidiState& bidi)
449 if (start > end || obj->isFloating() ||
450 (obj->isPositioned() && !obj->hasStaticX() && !obj->hasStaticY() && !obj->container()->isInlineFlow()))
453 bool haveNextMidpoint = (smidpoints && sCurrMidpoint < sNumMidpoints);
454 BidiIterator nextMidpoint;
455 if (haveNextMidpoint)
456 nextMidpoint = smidpoints->at(sCurrMidpoint);
457 if (betweenMidpoints) {
458 if (!(haveNextMidpoint && nextMidpoint.obj == obj))
460 // This is a new start point. Stop ignoring objects and
462 betweenMidpoints = false;
463 start = nextMidpoint.pos;
466 return appendRunsForObject(start, end, obj, bidi);
469 if (!smidpoints || !haveNextMidpoint || (obj != nextMidpoint.obj)) {
470 bidi.addRun(new (obj->renderArena()) BidiRun(start, end, obj, bidi.context(), bidi.dir()));
474 // An end midpoint has been encountered within our object. We
475 // need to go ahead and append a run with our endpoint.
476 if (int(nextMidpoint.pos+1) <= end) {
477 betweenMidpoints = true;
479 if (nextMidpoint.pos != UINT_MAX) { // UINT_MAX means stop at the object and don't include any of it.
480 if (int(nextMidpoint.pos+1) > start)
481 bidi.addRun(new (obj->renderArena())
482 BidiRun(start, nextMidpoint.pos+1, obj, bidi.context(), bidi.dir()));
483 return appendRunsForObject(nextMidpoint.pos+1, end, obj, bidi);
487 bidi.addRun(new (obj->renderArena()) BidiRun(start, end, obj, bidi.context(), bidi.dir()));
492 void BidiState::appendRun()
494 if (emptyRun || eor.atEnd())
496 bool b = m_adjustEmbedding;
497 m_adjustEmbedding = false;
500 RenderObject *obj = sor.obj;
501 while (obj && obj != eor.obj && obj != endOfLine.obj) {
502 appendRunsForObject(start, obj->length(), obj, *this);
504 obj = bidiNext(sor.block, obj, *this);
507 unsigned pos = obj == eor.obj ? eor.pos : UINT_MAX;
508 if (obj == endOfLine.obj && endOfLine.pos <= pos) {
509 reachedEndOfLine = true;
512 // It's OK to add runs for zero-length RenderObjects, just don't make the run larger than it should be
513 int end = obj->length() ? pos+1 : 0;
514 appendRunsForObject(start, end, obj, *this);
517 eor.increment(*this);
519 m_direction = OtherNeutral;
520 m_status.eor = OtherNeutral;
521 m_adjustEmbedding = b;
524 InlineFlowBox* RenderBlock::createLineBoxes(RenderObject* obj)
526 // See if we have an unconstructed line box for this object that is also
527 // the last item on the line.
528 unsigned lineDepth = 1;
529 InlineFlowBox* childBox = 0;
530 InlineFlowBox* parentBox = 0;
531 InlineFlowBox* result = 0;
533 ASSERT(obj->isInlineFlow() || obj == this);
534 RenderFlow* flow = static_cast<RenderFlow*>(obj);
536 // Get the last box we made for this render object.
537 parentBox = flow->lastLineBox();
539 // If this box is constructed then it is from a previous line, and we need
540 // to make a new box for our line. If this box is unconstructed but it has
541 // something following it on the line, then we know we have to make a new box
542 // as well. In this situation our inline has actually been split in two on
543 // the same line (this can happen with very fancy language mixtures).
544 bool constructedNewBox = false;
545 if (!parentBox || parentBox->isConstructed() || parentBox->nextOnLine()) {
546 // We need to make a new box for this render object. Once
547 // made, we need to place it at the end of the current line.
548 InlineBox* newBox = obj->createInlineBox(false, obj == this);
549 ASSERT(newBox->isInlineFlowBox());
550 parentBox = static_cast<InlineFlowBox*>(newBox);
551 parentBox->setFirstLineStyleBit(m_firstLine);
552 constructedNewBox = true;
558 // If we have hit the block itself, then |box| represents the root
559 // inline box for the line, and it doesn't have to be appended to any parent
562 parentBox->addToLine(childBox);
564 if (!constructedNewBox || obj == this)
567 childBox = parentBox;
569 // If we've exceeded our line depth, then jump straight to the root and skip all the remaining
570 // intermediate inline flows.
571 obj = (++lineDepth >= cMaxLineDepth) ? this : obj->parent();
578 RootInlineBox* RenderBlock::constructLine(const BidiIterator& start, const BidiIterator& end)
581 return 0; // We had no runs. Don't make a root inline box at all. The line is empty.
583 InlineFlowBox* parentBox = 0;
584 for (BidiRun* r = sFirstBidiRun; r; r = r->next()) {
585 // Create a box for our object.
586 bool isOnlyRun = (sBidiRunCount == 1);
587 if (sBidiRunCount == 2 && !r->obj->isListMarker())
588 isOnlyRun = ((style()->direction() == RTL) ? sLastBidiRun : sFirstBidiRun)->obj->isListMarker();
589 r->box = r->obj->createInlineBox(r->obj->isPositioned(), false, isOnlyRun);
591 // If we have no parent box yet, or if the run is not simply a sibling,
592 // then we need to construct inline boxes as necessary to properly enclose the
594 if (!parentBox || parentBox->object() != r->obj->parent())
595 // Create new inline boxes all the way back to the appropriate insertion point.
596 parentBox = createLineBoxes(r->obj->parent());
598 // Append the inline box to this line.
599 parentBox->addToLine(r->box);
601 if (r->box->isInlineTextBox()) {
602 InlineTextBox *text = static_cast<InlineTextBox*>(r->box);
603 text->setStart(r->m_start);
604 text->setLen(r->m_stop - r->m_start);
605 bool visuallyOrdered = r->obj->style()->visuallyOrdered();
606 text->m_reversed = r->reversed(visuallyOrdered);
607 text->m_dirOverride = r->dirOverride(visuallyOrdered);
612 // We should have a root inline box. It should be unconstructed and
613 // be the last continuation of our line list.
614 ASSERT(lastLineBox() && !lastLineBox()->isConstructed());
616 // Set bits on our inline flow boxes that indicate which sides should
617 // paint borders/margins/padding. This knowledge will ultimately be used when
618 // we determine the horizontal positions and widths of all the inline boxes on
620 RenderObject* endObject = 0;
621 bool lastLine = !end.obj;
622 if (end.obj && end.pos == 0)
624 lastLineBox()->determineSpacingForFlowBoxes(lastLine, endObject);
626 // Now mark the line boxes as being constructed.
627 lastLineBox()->setConstructed();
629 // Return the last line.
630 return lastRootBox();
633 void RenderBlock::computeHorizontalPositionsForLine(RootInlineBox* lineBox, bool reachedEnd)
635 // First determine our total width.
636 int availableWidth = lineWidth(m_height);
637 int totWidth = lineBox->getFlowSpacingWidth();
639 bool needsWordSpacing = false;
640 for (r = sFirstBidiRun; r; r = r->next()) {
641 if (!r->box || r->obj->isPositioned() || r->box->isLineBreak())
642 continue; // Positioned objects are only participating to figure out their
643 // correct static x position. They have no effect on the width.
644 // Similarly, line break boxes have no effect on the width.
645 if (r->obj->isText()) {
646 RenderText* rt = static_cast<RenderText*>(r->obj);
647 int textWidth = rt->width(r->m_start, r->m_stop - r->m_start, totWidth, m_firstLine);
648 int rtLength = rt->textLength();
650 if (!r->compact && !r->m_start && needsWordSpacing && isSpaceOrNewline(rt->characters()[r->m_start]))
651 totWidth += rt->style(m_firstLine)->font().wordSpacing();
652 needsWordSpacing = !isSpaceOrNewline(rt->characters()[r->m_stop - 1]) && r->m_stop == rtLength;
654 r->box->setWidth(textWidth);
655 } else if (!r->obj->isInlineFlow()) {
657 r->box->setWidth(r->obj->width());
659 totWidth += r->obj->marginLeft() + r->obj->marginRight();
662 // Compacts don't contribute to the width of the line, since they are placed in the margin.
664 totWidth += r->box->width();
667 if (totWidth > availableWidth && sLogicallyLastBidiRun->obj->style(m_firstLine)->autoWrap() &&
668 sLogicallyLastBidiRun->obj->style(m_firstLine)->breakOnlyAfterWhiteSpace() &&
669 !sLogicallyLastBidiRun->compact) {
670 sLogicallyLastBidiRun->box->setWidth(sLogicallyLastBidiRun->box->width() - totWidth + availableWidth);
671 totWidth = availableWidth;
674 // Armed with the total width of the line (without justification),
675 // we now examine our text-align property in order to determine where to position the
676 // objects horizontally. The total width of the line can be increased if we end up
678 int x = leftOffset(m_height);
679 switch(style()->textAlign()) {
682 // The direction of the block should determine what happens with wide lines. In
683 // particular with RTL blocks, wide lines should still spill out to the left.
684 if (style()->direction() == RTL && totWidth > availableWidth)
685 x -= (totWidth - availableWidth);
689 if (numSpaces != 0 && !reachedEnd && !lineBox->endsWithBreak())
694 // for right to left fall through to right aligned
695 if (style()->direction() == LTR)
699 // Wide lines spill out of the block based off direction.
700 // So even if text-align is right, if direction is LTR, wide lines should overflow out of the right
701 // side of the block.
702 if (style()->direction() == RTL || totWidth < availableWidth)
703 x += availableWidth - totWidth;
708 int xd = (availableWidth - totWidth)/2;
709 x += xd > 0 ? xd : 0;
715 for (r = sFirstBidiRun; r; r = r->next()) {
716 if (!r->box) continue;
719 if (numSpaces > 0 && r->obj->isText() && !r->compact) {
720 // get the number of spaces in the run
722 for (int i = r->m_start; i < r->m_stop; i++) {
723 UChar c = static_cast<RenderText*>(r->obj)->characters()[i];
724 if (c == ' ' || c == '\n' || c == '\t')
728 ASSERT(spaces <= numSpaces);
730 // Only justify text if whitespace is collapsed.
731 if (r->obj->style()->collapseWhiteSpace()) {
732 spaceAdd = (availableWidth - totWidth)*spaces/numSpaces;
733 static_cast<InlineTextBox*>(r->box)->setSpaceAdd(spaceAdd);
734 totWidth += spaceAdd;
741 // The widths of all runs are now known. We can now place every inline box (and
742 // compute accurate widths for the inline flow boxes).
743 int leftPosition = x;
744 int rightPosition = x;
745 needsWordSpacing = false;
746 lineBox->placeBoxesHorizontally(x, leftPosition, rightPosition, needsWordSpacing);
747 lineBox->setHorizontalOverflowPositions(leftPosition, rightPosition);
750 void RenderBlock::computeVerticalPositionsForLine(RootInlineBox* lineBox)
752 lineBox->verticallyAlignBoxes(m_height);
753 lineBox->setBlockHeight(m_height);
755 // See if the line spilled out. If so set overflow height accordingly.
756 int bottomOfLine = lineBox->bottomOverflow();
757 if (bottomOfLine > m_height && bottomOfLine > m_overflowHeight)
758 m_overflowHeight = bottomOfLine;
760 // Now make sure we place replaced render objects correctly.
761 for (BidiRun* r = sFirstBidiRun; r; r = r->next()) {
763 continue; // Skip runs with no line boxes.
765 // Align positioned boxes with the top of the line box. This is
766 // a reasonable approximation of an appropriate y position.
767 if (r->obj->isPositioned())
768 r->box->setYPos(m_height);
770 // Position is used to properly position both replaced elements and
771 // to update the static normal flow x/y of positioned elements.
772 r->obj->position(r->box);
776 // collects one line of the paragraph and transforms it to visual order
777 void RenderBlock::bidiReorderLine(const BidiIterator& start, const BidiIterator& end, BidiState& bidi)
780 if (start.current() == '\n')
781 m_height += lineHeight(m_firstLine, true);
787 bidi.createBidiRunsForLine(start, end, style()->visuallyOrdered(), previousLineBrokeCleanly);
789 sFirstBidiRun = bidi.firstRun();
790 sLastBidiRun = bidi.lastRun();
791 sBidiRunCount = bidi.runCount();
794 static void buildCompactRuns(RenderObject* compactObj, BidiState& bidi)
796 ASSERT(compactObj->isRenderBlock());
797 ASSERT(!bidi.firstRun());
799 // Format the compact like it is its own single line. We build up all the runs for
800 // the little compact and then reorder them for bidi.
801 RenderBlock* compactBlock = static_cast<RenderBlock*>(compactObj);
802 bidi.setAdjustEmbedding(true);
803 BidiIterator start(compactBlock, bidiFirst(compactBlock, bidi), 0);
804 bidi.setAdjustEmbedding(false);
805 BidiIterator end = start;
807 betweenMidpoints = false;
809 previousLineBrokeCleanly = true;
811 end = compactBlock->findNextLineBreak(start, bidi);
813 compactBlock->bidiReorderLine(start, end, bidi);
815 for (BidiRun* run = bidi.firstRun(); run; run = run->next())
820 betweenMidpoints = false;
823 void RenderBlock::layoutInlineChildren(bool relayoutChildren, int& repaintTop, int& repaintBottom)
827 bool useRepaintBounds = false;
829 invalidateVerticalPosition();
831 m_overflowHeight = 0;
833 m_height = borderTop() + paddingTop();
834 int toAdd = borderBottom() + paddingBottom() + horizontalScrollbarHeight();
836 // Figure out if we should clear out our line boxes.
837 // FIXME: Handle resize eventually!
838 // FIXME: Do something better when floats are present.
839 bool fullLayout = !firstLineBox() || !firstChild() || selfNeedsLayout() || relayoutChildren || containsFloats();
843 // Text truncation only kicks in if your overflow isn't visible and your text-overflow-mode isn't
845 // FIXME: CSS3 says that descendants that are clipped must also know how to truncate. This is insanely
846 // difficult to figure out (especially in the middle of doing layout), and is really an esoteric pile of nonsense
847 // anyway, so we won't worry about following the draft here.
848 bool hasTextOverflow = style()->textOverflow() && hasOverflowClip();
850 // Walk all the lines and delete our ellipsis line boxes if they exist.
852 deleteEllipsisLineBoxes();
855 // layout replaced elements
856 bool endOfInline = false;
857 RenderObject* o = bidiFirst(this, bidi, false);
858 bool hasFloat = false;
860 o->invalidateVerticalPosition();
861 if (o->isReplaced() || o->isFloating() || o->isPositioned()) {
862 if (relayoutChildren || o->style()->width().isPercent() || o->style()->height().isPercent())
863 o->setChildNeedsLayout(true, false);
865 // If relayoutChildren is set and we have percentage padding, we also need to invalidate the child's pref widths.
866 if (relayoutChildren && (o->style()->paddingLeft().isPercent() || o->style()->paddingRight().isPercent()))
867 o->setPrefWidthsDirty(true, false);
869 if (o->isPositioned())
870 o->containingBlock()->insertPositionedObject(o);
874 else if (fullLayout || o->needsLayout()) // Replaced elements
875 o->dirtyLineBoxes(fullLayout);
879 else if (o->isText() || (o->isInlineFlow() && !endOfInline)) {
880 if (fullLayout || o->selfNeedsLayout())
881 o->dirtyLineBoxes(fullLayout);
882 o->setNeedsLayout(false);
884 o = bidiNext(this, o, bidi, false, &endOfInline);
888 fullLayout = true; // FIXME: Will need to find a way to optimize floats some day.
890 if (fullLayout && !selfNeedsLayout()) {
891 setNeedsLayout(true, false); // Mark ourselves as needing a full layout. This way we'll repaint like
892 // we're supposed to.
893 if (!document()->view()->needsFullRepaint() && m_layer) {
894 // Because we waited until we were already inside layout to discover
895 // that the block really needed a full layout, we missed our chance to repaint the layer
896 // before layout started. Luckily the layer has cached the repaint rect for its original
897 // position and size, and so we can use that to make a repaint happen now.
898 RenderView* c = view();
899 if (c && !c->printing())
900 c->repaintViewRectangle(m_layer->repaintRect());
904 BidiContext *startEmbed;
905 if (style()->direction() == LTR
907 || (style()->unicodeBidi() == UBNormal && isSVGText())
910 startEmbed = new BidiContext(0, LeftToRight, style()->unicodeBidi() == Override);
912 startEmbed = new BidiContext(1, RightToLeft, style()->unicodeBidi() == Override);
915 bidi.setLastStrongDir(startEmbed->dir());
916 bidi.setLastDir(startEmbed->dir());
917 bidi.setEorDir(startEmbed->dir());
918 bidi.setContext(startEmbed);
921 smidpoints = new Vector<BidiIterator>();
926 // We want to skip ahead to the first dirty line
928 RootInlineBox* startLine = determineStartPosition(fullLayout, start, bidi);
930 // We also find the first clean line and extract these lines. We will add them back
931 // if we determine that we're able to synchronize after handling all our dirty lines.
932 BidiIterator cleanLineStart;
933 BidiStatus cleanLineBidiStatus;
935 RootInlineBox* endLine = (fullLayout || !startLine) ?
936 0 : determineEndPosition(startLine, cleanLineStart, cleanLineBidiStatus, endLineYPos);
939 useRepaintBounds = true;
940 repaintTop = m_height;
941 repaintBottom = m_height;
942 RenderArena* arena = renderArena();
943 RootInlineBox* box = startLine;
945 repaintTop = min(repaintTop, box->topOverflow());
946 repaintBottom = max(repaintBottom, box->bottomOverflow());
947 RootInlineBox* next = box->nextRootBox();
948 box->deleteLine(arena);
954 BidiIterator end = start;
956 bool endLineMatched = false;
957 while (!end.atEnd()) {
959 if (endLine && (endLineMatched = matchedEndLine(start, bidi.status(), cleanLineStart, cleanLineBidiStatus, endLine, endLineYPos, repaintBottom, repaintTop)))
962 betweenMidpoints = false;
964 if (m_firstLine && firstChild() && firstChild()->isCompact() && firstChild()->isRenderBlock()) {
965 buildCompactRuns(firstChild(), bidi);
966 start.obj = firstChild()->nextSibling();
969 end = findNextLineBreak(start, bidi);
975 bidiReorderLine(start, end, bidi);
977 // Now that the runs have been ordered, we create the line boxes.
978 // At the same time we figure out where border/padding/margin should be applied for
979 // inline flow boxes.
981 RootInlineBox* lineBox = 0;
983 lineBox = constructLine(start, end);
985 lineBox->setEndsWithBreak(previousLineBrokeCleanly);
987 // Now we position all of our text runs horizontally.
988 computeHorizontalPositionsForLine(lineBox, end.atEnd());
990 // Now position our text runs vertically.
991 computeVerticalPositionsForLine(lineBox);
994 // Special SVG text layout code
995 lineBox->computePerCharacterLayoutInformation();
999 // Highlight acts as an overflow inflation.
1000 if (style()->highlight() != nullAtom)
1001 lineBox->addHighlightOverflow();
1009 bidi.setAdjustEmbedding(true);
1010 end.increment(bidi);
1011 bidi.setAdjustEmbedding(false);
1015 lineBox->setLineBreakInfo(end.obj, end.pos, bidi.status());
1016 if (useRepaintBounds) {
1017 repaintTop = min(repaintTop, lineBox->topOverflow());
1018 repaintBottom = max(repaintBottom, lineBox->bottomOverflow());
1022 m_firstLine = false;
1031 if (endLineMatched) {
1032 // Attach all the remaining lines, and then adjust their y-positions as needed.
1033 for (RootInlineBox* line = endLine; line; line = line->nextRootBox())
1036 // Now apply the offset to each line if needed.
1037 int delta = m_height - endLineYPos;
1039 for (RootInlineBox* line = endLine; line; line = line->nextRootBox()) {
1040 repaintTop = min(repaintTop, line->topOverflow() + (delta < 0 ? delta : 0));
1041 repaintBottom = max(repaintBottom, line->bottomOverflow() + (delta > 0 ? delta : 0));
1042 line->adjustPosition(0, delta);
1045 m_height = lastRootBox()->blockHeight();
1047 // Delete all the remaining lines.
1048 InlineRunBox* line = endLine;
1049 RenderArena* arena = renderArena();
1051 repaintTop = min(repaintTop, line->topOverflow());
1052 repaintBottom = max(repaintBottom, line->bottomOverflow());
1053 InlineRunBox* next = line->nextLineBox();
1054 line->deleteLine(arena);
1064 // in case we have a float on the last line, it might not be positioned up to now.
1065 // This has to be done before adding in the bottom border/padding, or the float will
1066 // include the padding incorrectly. -dwh
1067 positionNewFloats();
1069 // Now add in the bottom border/padding.
1072 // Always make sure this is at least our height.
1073 m_overflowHeight = max(m_height, m_overflowHeight);
1075 // See if any lines spill out of the block. If so, we need to update our overflow width.
1076 checkLinesForOverflow();
1078 if (!firstLineBox() && hasLineIfEmpty())
1079 m_height += lineHeight(true, true);
1081 // See if we have any lines that spill out of our block. If we do, then we will possibly need to
1083 if (hasTextOverflow)
1084 checkLinesForTextOverflow();
1087 RootInlineBox* RenderBlock::determineStartPosition(bool fullLayout, BidiIterator& start, BidiState& bidi)
1089 RootInlineBox* curr = 0;
1090 RootInlineBox* last = 0;
1091 RenderObject* startObj = 0;
1095 // Nuke all our lines.
1096 if (firstRootBox()) {
1097 RenderArena* arena = renderArena();
1098 curr = firstRootBox();
1100 RootInlineBox* next = curr->nextRootBox();
1101 curr->deleteLine(arena);
1104 ASSERT(!firstLineBox() && !lastLineBox());
1107 for (curr = firstRootBox(); curr && !curr->isDirty(); curr = curr->nextRootBox()) { }
1109 // We have a dirty line.
1110 if (RootInlineBox* prevRootBox = curr->prevRootBox()) {
1111 // We have a previous line.
1112 if (!prevRootBox->endsWithBreak() || prevRootBox->lineBreakObj()->isText() && prevRootBox->lineBreakPos() >= static_cast<RenderText*>(prevRootBox->lineBreakObj())->textLength())
1113 // The previous line didn't break cleanly or broke at a newline
1114 // that has been deleted, so treat it as dirty too.
1118 // No dirty lines were found.
1119 // If the last line didn't break cleanly, treat it as dirty.
1120 if (lastRootBox() && !lastRootBox()->endsWithBreak())
1121 curr = lastRootBox();
1124 // If we have no dirty lines, then last is just the last root box.
1125 last = curr ? curr->prevRootBox() : lastRootBox();
1128 m_firstLine = !last;
1129 previousLineBrokeCleanly = !last || last->endsWithBreak();
1131 m_height = last->blockHeight();
1132 startObj = last->lineBreakObj();
1133 pos = last->lineBreakPos();
1134 bidi.setStatus(last->lineBreakBidiStatus());
1136 bidi.setAdjustEmbedding(true);
1137 startObj = bidiFirst(this, bidi, 0);
1138 bidi.setAdjustEmbedding(false);
1141 start = BidiIterator(this, startObj, pos);
1146 RootInlineBox* RenderBlock::determineEndPosition(RootInlineBox* startLine, BidiIterator& cleanLineStart, BidiStatus& cleanLineBidiStatus, int& yPos)
1148 RootInlineBox* last = 0;
1152 for (RootInlineBox* curr = startLine->nextRootBox(); curr; curr = curr->nextRootBox()) {
1153 if (curr->isDirty())
1163 RootInlineBox* prev = last->prevRootBox();
1164 cleanLineStart = BidiIterator(this, prev->lineBreakObj(), prev->lineBreakPos());
1165 cleanLineBidiStatus = prev->lineBreakBidiStatus();
1166 yPos = prev->blockHeight();
1168 for (RootInlineBox* line = last; line; line = line->nextRootBox())
1169 line->extractLine(); // Disconnect all line boxes from their render objects while preserving
1170 // their connections to one another.
1175 bool RenderBlock::matchedEndLine(const BidiIterator& start, const BidiStatus& status,
1176 const BidiIterator& endLineStart, const BidiStatus& endLineStatus,
1177 RootInlineBox*& endLine, int& endYPos, int& repaintBottom, int& repaintTop)
1179 if (start == endLineStart)
1180 return status == endLineStatus;
1182 // The first clean line doesn't match, but we can check a handful of following lines to try
1183 // to match back up.
1184 static int numLines = 8; // The # of lines we're willing to match against.
1185 RootInlineBox* line = endLine;
1186 for (int i = 0; i < numLines && line; i++, line = line->nextRootBox()) {
1187 if (line->lineBreakObj() == start.obj && line->lineBreakPos() == start.pos) {
1189 if (line->lineBreakBidiStatus() != status)
1190 return false; // ...but the bidi state doesn't match.
1191 RootInlineBox* result = line->nextRootBox();
1193 // Set our yPos to be the block height of endLine.
1195 endYPos = line->blockHeight();
1197 // Now delete the lines that we failed to sync.
1198 RootInlineBox* boxToDelete = endLine;
1199 RenderArena* arena = renderArena();
1200 while (boxToDelete && boxToDelete != result) {
1201 repaintTop = min(repaintTop, boxToDelete->topOverflow());
1202 repaintBottom = max(repaintBottom, boxToDelete->bottomOverflow());
1203 RootInlineBox* next = boxToDelete->nextRootBox();
1204 boxToDelete->deleteLine(arena);
1216 static inline bool skipNonBreakingSpace(BidiIterator &it)
1218 if (it.obj->style()->nbspMode() != SPACE || it.current() != noBreakSpace)
1221 // FIXME: This is bad. It makes nbsp inconsistent with space and won't work correctly
1222 // with m_minWidth/m_maxWidth.
1223 // Do not skip a non-breaking space if it is the first character
1224 // on a line after a clean line break (or on the first line, since previousLineBrokeCleanly starts off
1226 if (isLineEmpty && previousLineBrokeCleanly)
1232 static inline bool shouldCollapseWhiteSpace(const RenderStyle* style)
1234 return style->collapseWhiteSpace() || (style->whiteSpace() == PRE_WRAP && (!isLineEmpty || !previousLineBrokeCleanly));
1237 static inline bool shouldPreserveNewline(RenderObject* object)
1240 if (object->isSVGText())
1244 return object->style()->preserveNewline();
1247 static bool inlineFlowRequiresLineBox(RenderObject* flow)
1249 // FIXME: Right now, we only allow line boxes for inlines that are truly empty.
1250 // We need to fix this, though, because at the very least, inlines containing only
1251 // ignorable whitespace should should also have line boxes.
1252 return flow->isInlineFlow() && !flow->firstChild() && flow->hasBordersPaddingOrMargin();
1255 static inline bool requiresLineBox(BidiIterator& it)
1257 if (it.obj->isFloatingOrPositioned())
1260 if (it.obj->isInlineFlow() && !inlineFlowRequiresLineBox(it.obj))
1263 if (!shouldCollapseWhiteSpace(it.obj->style()) || it.obj->isBR())
1266 UChar current = it.current();
1267 return current != ' ' && current != '\t' && current != softHyphen && (current != '\n' || shouldPreserveNewline(it.obj)) && !skipNonBreakingSpace(it);
1270 bool RenderBlock::generatesLineBoxesForInlineChild(RenderObject* inlineObj)
1272 ASSERT(inlineObj->parent() == this);
1274 BidiIterator it(this, inlineObj, 0);
1276 while (!it.atEnd() && !requiresLineBox(it))
1277 it.increment(state);
1282 int RenderBlock::skipWhitespace(BidiIterator &it, BidiState &bidi)
1284 // FIXME: The entire concept of the skipWhitespace function is flawed, since we really need to be building
1285 // line boxes even for containers that may ultimately collapse away. Otherwise we'll never get positioned
1286 // elements quite right. In other words, we need to build this function's work into the normal line
1287 // object iteration process.
1288 int w = lineWidth(m_height);
1289 bidi.setAdjustEmbedding(true);
1291 while (!it.atEnd() && !requiresLineBox(it)) {
1292 if (it.obj->isFloatingOrPositioned()) {
1293 RenderObject *o = it.obj;
1294 // add to special objects...
1295 if (o->isFloating()) {
1296 insertFloatingObject(o);
1297 positionNewFloats();
1298 w = lineWidth(m_height);
1300 else if (o->isPositioned()) {
1301 // FIXME: The math here is actually not really right. It's a best-guess approximation that
1302 // will work for the common cases
1303 RenderObject* c = o->container();
1304 if (c->isInlineFlow()) {
1305 // A relative positioned inline encloses us. In this case, we also have to determine our
1306 // position as though we were an inline. Set |staticX| and |staticY| on the relative positioned
1307 // inline so that we can obtain the value later.
1308 c->setStaticX(style()->direction() == LTR ?
1309 leftOffset(m_height) : rightOffset(m_height));
1310 c->setStaticY(m_height);
1313 if (o->hasStaticX()) {
1314 bool wasInline = o->style()->isOriginalDisplayInlineType();
1316 o->setStaticX(style()->direction() == LTR ?
1317 leftOffset(m_height) :
1318 width() - rightOffset(m_height));
1320 o->setStaticX(style()->direction() == LTR ?
1321 borderLeft() + paddingLeft() :
1322 borderRight() + paddingRight());
1324 if (o->hasStaticY())
1325 o->setStaticY(m_height);
1331 bidi.setAdjustEmbedding(false);
1335 // This is currently just used for list markers and inline flows that have line boxes. Neither should
1336 // have an effect on whitespace at the start of the line.
1337 static bool shouldSkipWhitespaceAfterStartObject(RenderBlock* block, RenderObject* o, BidiState &bidi)
1339 RenderObject* next = bidiNext(block, o, bidi);
1340 if (next && !next->isBR() && next->isText() && static_cast<RenderText*>(next)->textLength() > 0) {
1341 RenderText* nextText = static_cast<RenderText*>(next);
1342 UChar nextChar = nextText->characters()[0];
1343 if (nextText->style()->isCollapsibleWhiteSpace(nextChar)) {
1344 addMidpoint(BidiIterator(0, o, 0));
1352 void RenderBlock::fitBelowFloats(int widthToFit, int& availableWidth)
1354 ASSERT(widthToFit > availableWidth);
1357 int lastFloatBottom = m_height;
1358 int newLineWidth = availableWidth;
1360 floatBottom = nextFloatBottomBelow(lastFloatBottom);
1364 newLineWidth = lineWidth(floatBottom);
1365 lastFloatBottom = floatBottom;
1366 if (newLineWidth >= widthToFit)
1370 if (newLineWidth > availableWidth) {
1371 m_height = lastFloatBottom;
1372 availableWidth = newLineWidth;
1376 BidiIterator RenderBlock::findNextLineBreak(BidiIterator &start, BidiState &bidi)
1378 // eliminate spaces at beginning of line
1379 int width = skipWhitespace(start, bidi);
1386 // This variable is used only if whitespace isn't set to PRE, and it tells us whether
1387 // or not we are currently ignoring whitespace.
1388 bool ignoringSpaces = false;
1389 BidiIterator ignoreStart;
1391 // This variable tracks whether the very last character we saw was a space. We use
1392 // this to detect when we encounter a second space so we know we have to terminate
1394 bool currentCharacterIsSpace = false;
1395 bool currentCharacterIsWS = false;
1396 RenderObject* trailingSpaceObject = 0;
1398 BidiIterator lBreak = start;
1400 RenderObject *o = start.obj;
1401 RenderObject *last = o;
1402 RenderObject *previous = o;
1403 int pos = start.pos;
1404 bool atStart = true;
1406 bool prevLineBrokeCleanly = previousLineBrokeCleanly;
1407 previousLineBrokeCleanly = false;
1409 bool autoWrapWasEverTrueOnLine = false;
1411 // Firefox and Opera will allow a table cell to grow to fit an image inside it under
1412 // very specific cirucumstances (in order to match common WinIE renderings).
1413 // Not supporting the quirk has caused us to mis-render some real sites. (See Bugzilla 10517.)
1414 bool allowImagesToBreak = !style()->htmlHacks() || !isTableCell() || !style()->width().isIntrinsicOrAuto();
1416 EWhiteSpace currWS = style()->whiteSpace();
1417 EWhiteSpace lastWS = currWS;
1419 currWS = o->isReplaced() ? o->parent()->style()->whiteSpace() : o->style()->whiteSpace();
1420 lastWS = last->isReplaced() ? last->parent()->style()->whiteSpace() : last->style()->whiteSpace();
1422 bool autoWrap = RenderStyle::autoWrap(currWS);
1423 autoWrapWasEverTrueOnLine = autoWrapWasEverTrueOnLine || autoWrap;
1426 bool preserveNewline = o->isSVGText() ? false : RenderStyle::preserveNewline(currWS);
1428 bool preserveNewline = RenderStyle::preserveNewline(currWS);
1431 bool collapseWhiteSpace = RenderStyle::collapseWhiteSpace(currWS);
1434 if (w + tmpW <= width) {
1437 lBreak.increment(bidi);
1439 // A <br> always breaks a line, so don't let the line be collapsed
1440 // away. Also, the space at the end of a line with a <br> does not
1441 // get collapsed away. It only does this if the previous line broke
1442 // cleanly. Otherwise the <br> has no effect on whether the line is
1444 if (prevLineBrokeCleanly)
1445 isLineEmpty = false;
1446 trailingSpaceObject = 0;
1447 previousLineBrokeCleanly = true;
1450 // only check the clear status for non-empty lines.
1451 EClear clear = o->style()->clear();
1453 m_clearStatus = (EClear) (m_clearStatus | clear);
1459 if (o->isFloatingOrPositioned()) {
1460 // add to special objects...
1461 if (o->isFloating()) {
1462 insertFloatingObject(o);
1463 // check if it fits in the current line.
1464 // If it does, position it now, otherwise, position
1465 // it after moving to next line (in newLine() func)
1466 if (o->width() + o->marginLeft() + o->marginRight() + w + tmpW <= width) {
1467 positionNewFloats();
1468 width = lineWidth(m_height);
1470 } else if (o->isPositioned()) {
1471 // If our original display wasn't an inline type, then we can
1472 // go ahead and determine our static x position now.
1473 bool isInlineType = o->style()->isOriginalDisplayInlineType();
1474 bool needToSetStaticX = o->hasStaticX();
1475 if (o->hasStaticX() && !isInlineType) {
1476 o->setStaticX(o->parent()->style()->direction() == LTR ?
1477 borderLeft() + paddingLeft() :
1478 borderRight() + paddingRight());
1479 needToSetStaticX = false;
1482 // If our original display was an INLINE type, then we can go ahead
1483 // and determine our static y position now.
1484 bool needToSetStaticY = o->hasStaticY();
1485 if (o->hasStaticY() && isInlineType) {
1486 o->setStaticY(m_height);
1487 needToSetStaticY = false;
1490 bool needToCreateLineBox = needToSetStaticX || needToSetStaticY;
1491 RenderObject* c = o->container();
1492 if (c->isInlineFlow() && (!needToSetStaticX || !needToSetStaticY))
1493 needToCreateLineBox = true;
1495 // If we're ignoring spaces, we have to stop and include this object and
1496 // then start ignoring spaces again.
1497 if (needToCreateLineBox) {
1498 trailingSpaceObject = 0;
1499 ignoreStart.obj = o;
1500 ignoreStart.pos = 0;
1501 if (ignoringSpaces) {
1502 addMidpoint(ignoreStart); // Stop ignoring spaces.
1503 addMidpoint(ignoreStart); // Start ignoring again.
1508 } else if (o->isInlineFlow()) {
1509 // Right now, we should only encounter empty inlines here.
1510 ASSERT(!o->firstChild());
1512 // Now that some inline flows have line boxes, if we are already ignoring spaces, we need
1513 // to make sure that we stop to include this object and then start ignoring spaces again.
1514 // If this object is at the start of the line, we need to behave like list markers and
1515 // start ignoring spaces.
1516 if (inlineFlowRequiresLineBox(o)) {
1517 isLineEmpty = false;
1518 if (ignoringSpaces) {
1519 trailingSpaceObject = 0;
1520 addMidpoint(BidiIterator(0, o, 0)); // Stop ignoring spaces.
1521 addMidpoint(BidiIterator(0, o, 0)); // Start ignoring again.
1522 } else if (style()->collapseWhiteSpace() && start.obj == o
1523 && shouldSkipWhitespaceAfterStartObject(start.block, o, bidi)) {
1524 // Like with list markers, we start ignoring spaces to make sure that any
1525 // additional spaces we see will be discarded.
1526 currentCharacterIsSpace = true;
1527 currentCharacterIsWS = true;
1528 ignoringSpaces = true;
1532 tmpW += o->marginLeft() + o->borderLeft() + o->paddingLeft() +
1533 o->marginRight() + o->borderRight() + o->paddingRight();
1534 } else if (o->isReplaced()) {
1535 // Break on replaced elements if either has normal white-space.
1536 if ((autoWrap || RenderStyle::autoWrap(lastWS)) && (!o->isImage() || allowImagesToBreak)) {
1544 addMidpoint(BidiIterator(0, o, 0));
1546 isLineEmpty = false;
1547 ignoringSpaces = false;
1548 currentCharacterIsSpace = false;
1549 currentCharacterIsWS = false;
1550 trailingSpaceObject = 0;
1552 // Optimize for a common case. If we can't find whitespace after the list
1553 // item, then this is all moot. -dwh
1554 if (o->isListMarker() && !static_cast<RenderListMarker*>(o)->isInside()) {
1555 if (style()->collapseWhiteSpace() && shouldSkipWhitespaceAfterStartObject(start.block, o, bidi)) {
1556 // Like with inline flows, we start ignoring spaces to make sure that any
1557 // additional spaces we see will be discarded.
1558 currentCharacterIsSpace = true;
1559 currentCharacterIsWS = true;
1560 ignoringSpaces = true;
1563 tmpW += o->width() + o->marginLeft() + o->marginRight() + inlineWidth(o);
1564 } else if (o->isText()) {
1565 RenderText* t = static_cast<RenderText*>(o);
1567 int strlen = t->textLength();
1568 int len = strlen - pos;
1569 const UChar* str = t->characters();
1571 const Font& f = t->style(m_firstLine)->font();
1573 int lastSpace = pos;
1574 int wordSpacing = o->style()->wordSpacing();
1575 int lastSpaceWordSpacing = 0;
1577 bool appliedStartWidth = pos > 0; // If the span originated on a previous line,
1578 // then assume the start width has been applied.
1579 int wrapW = tmpW + inlineWidth(o, !appliedStartWidth, true);
1581 int nextBreakable = -1;
1582 bool breakNBSP = autoWrap && o->style()->nbspMode() == SPACE;
1583 // Auto-wrapping text should wrap in the middle of a word only if it could not wrap before the word,
1584 // which is only possible if the word is the first thing on the line, that is, if |w| is zero.
1585 bool breakWords = o->style()->breakWords() && ((autoWrap && !w) || currWS == PRE);
1586 bool midWordBreak = false;
1587 bool breakAll = o->style()->wordBreak() == BreakAllWordBreak && autoWrap;
1589 if (t->isWordBreak()) {
1598 bool previousCharacterIsSpace = currentCharacterIsSpace;
1599 bool previousCharacterIsWS = currentCharacterIsWS;
1601 currentCharacterIsSpace = c == ' ' || c == '\t' || (!preserveNewline && (c == '\n'));
1603 if (!collapseWhiteSpace || !currentCharacterIsSpace)
1604 isLineEmpty = false;
1606 // Check for soft hyphens. Go ahead and ignore them.
1607 if (c == softHyphen) {
1608 if (!ignoringSpaces) {
1609 // Ignore soft hyphens
1610 BidiIterator endMid;
1612 endMid = BidiIterator(0, o, pos - 1);
1614 endMid = BidiIterator(0, previous, previous->isText() ? static_cast<RenderText*>(previous)->textLength() - 1 : 0);
1615 // Two consecutive soft hyphens. Avoid overlapping midpoints.
1616 if (sNumMidpoints && smidpoints->at(sNumMidpoints - 1).obj == endMid.obj && smidpoints->at(sNumMidpoints - 1).pos > endMid.pos)
1619 addMidpoint(endMid);
1621 // Add the width up to but not including the hyphen.
1622 tmpW += t->width(lastSpace, pos - lastSpace, f, w + tmpW) + lastSpaceWordSpacing;
1624 // For wrapping text only, include the hyphen. We need to ensure it will fit
1625 // on the line if it shows when we break.
1627 tmpW += t->width(pos, 1, f, w + tmpW);
1629 addMidpoint(BidiIterator(0, o, pos + 1));
1634 lastSpaceWordSpacing = 0;
1635 lastSpace = pos; // Cheesy hack to prevent adding in widths of the run twice.
1639 bool applyWordSpacing = false;
1641 currentCharacterIsWS = currentCharacterIsSpace || (breakNBSP && c == noBreakSpace);
1643 if ((breakAll || breakWords) && !midWordBreak) {
1645 charWidth = t->width(pos, 1, f, w + wrapW);
1646 midWordBreak = w + wrapW + charWidth > width;
1649 bool betweenWords = c == '\n' || (currWS != PRE && !atStart && isBreakable(str, pos, strlen, nextBreakable, breakNBSP));
1651 if (betweenWords || midWordBreak) {
1652 bool stoppedIgnoringSpaces = false;
1653 if (ignoringSpaces) {
1654 if (!currentCharacterIsSpace) {
1655 // Stop ignoring spaces and begin at this
1657 ignoringSpaces = false;
1658 lastSpaceWordSpacing = 0;
1659 lastSpace = pos; // e.g., "Foo goo", don't add in any of the ignored spaces.
1660 addMidpoint(BidiIterator(0, o, pos));
1661 stoppedIgnoringSpaces = true;
1663 // Just keep ignoring these spaces.
1670 int additionalTmpW = t->width(lastSpace, pos - lastSpace, f, w+tmpW) + lastSpaceWordSpacing;
1671 tmpW += additionalTmpW;
1672 if (!appliedStartWidth) {
1673 tmpW += inlineWidth(o, true, false);
1674 appliedStartWidth = true;
1677 applyWordSpacing = wordSpacing && currentCharacterIsSpace && !previousCharacterIsSpace;
1679 if (!w && autoWrap && tmpW > width)
1680 fitBelowFloats(tmpW, width);
1682 if (autoWrap || breakWords) {
1683 // If we break only after white-space, consider the current character
1684 // as candidate width for this line.
1685 bool lineWasTooWide = false;
1686 if (w + tmpW <= width && currentCharacterIsWS && o->style()->breakOnlyAfterWhiteSpace() && !midWordBreak) {
1687 int charWidth = t->width(pos, 1, f, w + tmpW) + (applyWordSpacing ? wordSpacing : 0);
1688 // Check if line is too big even without the extra space
1689 // at the end of the line. If it is not, do nothing.
1690 // If the line needs the extra whitespace to be too long,
1691 // then move the line break to the space and skip all
1692 // additional whitespace.
1693 if (w + tmpW + charWidth > width) {
1694 lineWasTooWide = true;
1698 // Separate the trailing space into its own box, which we will
1699 // resize to fit on the line in computeHorizontalPositionsForLine().
1700 addMidpoint(BidiIterator(0, o, pos - 1)); // Stop
1701 addMidpoint(BidiIterator(0, o, pos)); // Start
1703 skipWhitespace(lBreak, bidi);
1706 if (lineWasTooWide || w + tmpW > width) {
1707 if (lBreak.obj && shouldPreserveNewline(lBreak.obj) && lBreak.obj->isText() && !static_cast<RenderText*>(lBreak.obj)->isWordBreak() && static_cast<RenderText*>(lBreak.obj)->characters()[lBreak.pos] == '\n') {
1708 if (!stoppedIgnoringSpaces && pos > 0) {
1709 // We need to stop right before the newline and then start up again.
1710 addMidpoint(BidiIterator(0, o, pos - 1)); // Stop
1711 addMidpoint(BidiIterator(0, o, pos)); // Start
1713 lBreak.increment(bidi);
1714 previousLineBrokeCleanly = true;
1716 goto end; // Didn't fit. Jump to the end.
1718 if (!betweenWords || (midWordBreak && !autoWrap))
1719 tmpW -= additionalTmpW;
1720 if (pos > 0 && str[pos-1] == softHyphen)
1721 // Subtract the width of the soft hyphen out since we fit on a line.
1722 tmpW -= t->width(pos-1, 1, f, w+tmpW);
1726 if (c == '\n' && preserveNewline) {
1727 if (!stoppedIgnoringSpaces && pos > 0) {
1728 // We need to stop right before the newline and then start up again.
1729 addMidpoint(BidiIterator(0, o, pos - 1)); // Stop
1730 addMidpoint(BidiIterator(0, o, pos)); // Start
1734 lBreak.increment(bidi);
1735 previousLineBrokeCleanly = true;
1739 if (autoWrap && betweenWords) {
1745 // Auto-wrapping text should not wrap in the middle of a word once it has had an
1746 // opportunity to break after a word.
1751 // Remember this as a breakable position in case
1752 // adding the end width forces a break.
1755 midWordBreak &= (breakWords || breakAll);
1759 lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
1763 if (!ignoringSpaces && o->style()->collapseWhiteSpace()) {
1764 // If we encounter a newline, or if we encounter a
1765 // second space, we need to go ahead and break up this
1766 // run and enter a mode where we start collapsing spaces.
1767 if (currentCharacterIsSpace && previousCharacterIsSpace) {
1768 ignoringSpaces = true;
1770 // We just entered a mode where we are ignoring
1771 // spaces. Create a midpoint to terminate the run
1772 // before the second space.
1773 addMidpoint(ignoreStart);
1776 } else if (ignoringSpaces) {
1777 // Stop ignoring spaces and begin at this
1779 ignoringSpaces = false;
1780 lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
1781 lastSpace = pos; // e.g., "Foo goo", don't add in any of the ignored spaces.
1782 addMidpoint(BidiIterator(0, o, pos));
1785 if (currentCharacterIsSpace && !previousCharacterIsSpace) {
1786 ignoreStart.obj = o;
1787 ignoreStart.pos = pos;
1790 if (!currentCharacterIsWS && previousCharacterIsWS) {
1791 if (autoWrap && o->style()->breakOnlyAfterWhiteSpace()) {
1797 if (collapseWhiteSpace && currentCharacterIsSpace && !ignoringSpaces)
1798 trailingSpaceObject = o;
1799 else if (!o->style()->collapseWhiteSpace() || !currentCharacterIsSpace)
1800 trailingSpaceObject = 0;
1807 // IMPORTANT: pos is > length here!
1808 if (!ignoringSpaces)
1809 tmpW += t->width(lastSpace, pos - lastSpace, f, w+tmpW) + lastSpaceWordSpacing;
1810 tmpW += inlineWidth(o, !appliedStartWidth, true);
1812 ASSERT_NOT_REACHED();
1814 RenderObject* next = bidiNext(start.block, o, bidi);
1815 bool checkForBreak = autoWrap;
1816 if (w && w + tmpW > width && lBreak.obj && currWS == NOWRAP)
1817 checkForBreak = true;
1818 else if (next && o->isText() && next->isText() && !next->isBR()) {
1819 if (autoWrap || (next->style()->autoWrap())) {
1820 if (currentCharacterIsSpace)
1821 checkForBreak = true;
1823 checkForBreak = false;
1824 RenderText* nextText = static_cast<RenderText*>(next);
1825 if (nextText->textLength()) {
1826 UChar c = nextText->characters()[0];
1827 if (c == ' ' || c == '\t' || (c == '\n' && !shouldPreserveNewline(next)))
1828 // If the next item on the line is text, and if we did not end with
1829 // a space, then the next text run continues our word (and so it needs to
1830 // keep adding to |tmpW|. Just update and continue.
1831 checkForBreak = true;
1832 } else if (nextText->isWordBreak())
1833 checkForBreak = true;
1834 bool willFitOnLine = w + tmpW <= width;
1835 if (!willFitOnLine && !w) {
1836 fitBelowFloats(tmpW, width);
1837 willFitOnLine = tmpW <= width;
1839 bool canPlaceOnLine = willFitOnLine || !autoWrapWasEverTrueOnLine;
1840 if (canPlaceOnLine && checkForBreak) {
1850 if (checkForBreak && (w + tmpW > width)) {
1851 // if we have floats, try to get below them.
1852 if (currentCharacterIsSpace && !ignoringSpaces && o->style()->collapseWhiteSpace())
1853 trailingSpaceObject = 0;
1858 fitBelowFloats(tmpW, width);
1860 // |width| may have been adjusted because we got shoved down past a float (thus
1861 // giving us more room), so we need to retest, and only jump to
1862 // the end label if we still don't fit on the line. -dwh
1863 if (w + tmpW > width)
1868 if (!o->isFloating() && (!o->isPositioned() || o->hasStaticX() || o->hasStaticY() || !o->container()->isInlineFlow()))
1872 if (!last->isFloatingOrPositioned() && last->isReplaced() && autoWrap && (!last->isImage() || allowImagesToBreak) &&
1873 (!last->isListMarker() || static_cast<RenderListMarker*>(last)->isInside())) {
1880 // Clear out our character space bool, since inline <pre>s don't collapse whitespace
1881 // with adjacent inline normal/nowrap spans.
1882 if (!collapseWhiteSpace)
1883 currentCharacterIsSpace = false;
1890 if (w + tmpW <= width || lastWS == NOWRAP) {
1897 if (lBreak == start && !lBreak.obj->isBR()) {
1898 // we just add as much as possible
1899 if (style()->whiteSpace() == PRE) {
1900 // FIXME: Don't really understand this case.
1903 lBreak.pos = pos - 1;
1906 lBreak.pos = last->isText() ? last->length() : 0;
1908 } else if (lBreak.obj) {
1909 if (last != o && !last->isListMarker()) {
1910 // better to break between object boundaries than in the middle of a word (except for list markers)
1914 // Don't ever break in the middle of a word if we can help it.
1915 // There's no room at all. We just have to be on this line,
1916 // even though we'll spill out.
1923 // make sure we consume at least one char/object.
1924 if (lBreak == start)
1925 lBreak.increment(bidi);
1927 // Sanity check our midpoints.
1928 checkMidpoints(lBreak, bidi);
1930 if (trailingSpaceObject) {
1931 // This object is either going to be part of the last midpoint, or it is going
1932 // to be the actual endpoint. In both cases we just decrease our pos by 1 level to
1933 // exclude the space, allowing it to - in effect - collapse into the newline.
1934 if (sNumMidpoints%2==1) {
1935 BidiIterator* midpoints = smidpoints->data();
1936 midpoints[sNumMidpoints-1].pos--;
1938 //else if (lBreak.pos > 0)
1940 else if (lBreak.obj == 0 && trailingSpaceObject->isText()) {
1941 // Add a new end midpoint that stops right at the very end.
1942 RenderText* text = static_cast<RenderText *>(trailingSpaceObject);
1943 unsigned length = text->textLength();
1944 unsigned pos = length >= 2 ? length - 2 : UINT_MAX;
1945 BidiIterator endMid(0, trailingSpaceObject, pos);
1946 addMidpoint(endMid);
1950 // We might have made lBreak an iterator that points past the end
1951 // of the object. Do this adjustment to make it point to the start
1952 // of the next object instead to avoid confusing the rest of the
1954 if (lBreak.pos > 0) {
1956 lBreak.increment(bidi);
1959 if (lBreak.obj && lBreak.pos >= 2 && lBreak.obj->isText()) {
1960 // For soft hyphens on line breaks, we have to chop out the midpoints that made us
1961 // ignore the hyphen so that it will render at the end of the line.
1962 UChar c = static_cast<RenderText*>(lBreak.obj)->characters()[lBreak.pos-1];
1963 if (c == softHyphen)
1964 chopMidpointsAt(lBreak.obj, lBreak.pos-2);
1970 void RenderBlock::checkLinesForOverflow()
1972 m_overflowWidth = m_width;
1973 for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
1974 m_overflowLeft = min(curr->leftOverflow(), m_overflowLeft);
1975 m_overflowTop = min(curr->topOverflow(), m_overflowTop);
1976 m_overflowWidth = max(curr->rightOverflow(), m_overflowWidth);
1977 m_overflowHeight = max(curr->bottomOverflow(), m_overflowHeight);
1981 void RenderBlock::deleteEllipsisLineBoxes()
1983 for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox())
1984 curr->clearTruncation();
1987 void RenderBlock::checkLinesForTextOverflow()
1989 // Determine the width of the ellipsis using the current font.
1990 // FIXME: CSS3 says this is configurable, also need to use 0x002E (FULL STOP) if horizontal ellipsis is "not renderable"
1991 TextRun ellipsisRun(&horizontalEllipsis, 1);
1992 static AtomicString ellipsisStr(&horizontalEllipsis, 1);
1993 const Font& firstLineFont = firstLineStyle()->font();
1994 const Font& font = style()->font();
1995 int firstLineEllipsisWidth = firstLineFont.width(ellipsisRun);
1996 int ellipsisWidth = (font == firstLineFont) ? firstLineEllipsisWidth : font.width(ellipsisRun);
1998 // For LTR text truncation, we want to get the right edge of our padding box, and then we want to see
1999 // if the right edge of a line box exceeds that. For RTL, we use the left edge of the padding box and
2000 // check the left edge of the line box to see if it is less
2001 // Include the scrollbar for overflow blocks, which means we want to use "contentWidth()"
2002 bool ltr = style()->direction() == LTR;
2003 for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
2004 int blockEdge = ltr ? rightOffset(curr->yPos()) : leftOffset(curr->yPos());
2005 int lineBoxEdge = ltr ? curr->xPos() + curr->width() : curr->xPos();
2006 if ((ltr && lineBoxEdge > blockEdge) || (!ltr && lineBoxEdge < blockEdge)) {
2007 // This line spills out of our box in the appropriate direction. Now we need to see if the line
2008 // can be truncated. In order for truncation to be possible, the line must have sufficient space to
2009 // accommodate our truncation string, and no replaced elements (images, tables) can overlap the ellipsis
2011 int width = curr == firstRootBox() ? firstLineEllipsisWidth : ellipsisWidth;
2012 if (curr->canAccommodateEllipsis(ltr, blockEdge, lineBoxEdge, width))
2013 curr->placeEllipsis(ellipsisStr, ltr, blockEdge, width);