2 * This file is part of the html renderer for KDE.
4 * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
5 * Copyright (C) 2004 Apple Computer, Inc.
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Library General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Library General Public License for more details.
17 * You should have received a copy of the GNU Library General Public License
18 * along with this library; see the file COPYING.LIB. If not, write to
19 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
24 #include "break_lines.h"
25 #include "render_block.h"
26 #include "render_text.h"
27 #include "render_arena.h"
28 #include "render_canvas.h"
29 #include "khtmlview.h"
30 #include "xml/dom_docimpl.h"
33 #include "qdatetime.h"
34 #include "qfontmetrics.h"
37 //#define DEBUG_LINEBREAKS
39 using DOM::AtomicString;
44 // an iterator which goes through a BidiParagraph
47 BidiIterator() : par(0), obj(0), pos(0) {}
48 BidiIterator(RenderBlock *_par, RenderObject *_obj, unsigned int _pos) : par(_par), obj(_obj), pos(_pos) {}
50 void increment( BidiState &bidi );
54 const QChar ¤t() const;
55 QChar::Direction direction() const;
63 BidiStatus() : eor(QChar::DirON), lastStrong(QChar::DirON), last(QChar::DirON) {}
66 QChar::Direction lastStrong;
67 QChar::Direction last;
71 BidiState() : context(0) {}
81 // Used to track a list of chained bidi runs.
82 static BidiRun* sFirstBidiRun;
83 static BidiRun* sLastBidiRun;
84 static int sBidiRunCount;
85 static BidiRun* sCompactFirstBidiRun;
86 static BidiRun* sCompactLastBidiRun;
87 static int sCompactBidiRunCount;
88 static bool sBuildingCompactRuns;
90 // Midpoint globals. The goal is not to do any allocation when dealing with
91 // these midpoints, so we just keep an array around and never clear it. We track
92 // the number of items and position using the two other variables.
93 static QMemArray<BidiIterator> *smidpoints;
94 static uint sNumMidpoints;
95 static uint sCurrMidpoint;
96 static bool betweenMidpoints;
98 static bool isLineEmpty = true;
99 static bool previousLineBrokeCleanly = true;
100 static QChar::Direction dir;
101 static bool adjustEmbedding;
102 static bool emptyRun = true;
103 static int numSpaces;
105 static void embed( QChar::Direction d, BidiState &bidi );
106 static void appendRun( BidiState &bidi );
108 static int getBPMWidth(int childValue, Length cssUnit)
110 if (cssUnit.type != Variable)
111 return (cssUnit.type == Fixed ? cssUnit.value : childValue);
115 static int getBorderPaddingMargin(RenderObject* child, bool endOfInline)
117 RenderStyle* cstyle = child->style();
119 bool leftSide = (cstyle->direction() == LTR) ? !endOfInline : endOfInline;
120 result += getBPMWidth((leftSide ? child->marginLeft() : child->marginRight()),
121 (leftSide ? cstyle->marginLeft() :
122 cstyle->marginRight()));
123 result += getBPMWidth((leftSide ? child->paddingLeft() : child->paddingRight()),
124 (leftSide ? cstyle->paddingLeft() :
125 cstyle->paddingRight()));
126 result += leftSide ? child->borderLeft() : child->borderRight();
130 static int inlineWidth(RenderObject* child, bool start = true, bool end = true)
133 RenderObject* parent = child->parent();
134 while (parent->isInline() && !parent->isInlineBlockOrInlineTable()) {
135 if (start && parent->firstChild() == child)
136 extraWidth += getBorderPaddingMargin(parent, false);
137 if (end && parent->lastChild() == child)
138 extraWidth += getBorderPaddingMargin(parent, true);
140 parent = child->parent();
146 static bool inBidiRunDetach;
149 void BidiRun::detach(RenderArena* renderArena)
152 inBidiRunDetach = true;
156 inBidiRunDetach = false;
159 // Recover the size left there for us by operator delete and free the memory.
160 renderArena->free(*(size_t *)this, this);
163 void* BidiRun::operator new(size_t sz, RenderArena* renderArena) throw()
165 return renderArena->allocate(sz);
168 void BidiRun::operator delete(void* ptr, size_t sz)
170 assert(inBidiRunDetach);
172 // Stash size where detach can find it.
176 static void deleteBidiRuns(RenderArena* arena)
181 BidiRun* curr = sFirstBidiRun;
183 BidiRun* s = curr->nextRun;
193 // ---------------------------------------------------------------------
195 /* a small helper class used internally to resolve Bidi embedding levels.
196 Each line of text caches the embedding level at the start of the line for faster
199 BidiContext::BidiContext(unsigned char l, QChar::Direction e, BidiContext *p, bool o)
200 : level(l) , override(o), dir(e)
205 basicDir = p->basicDir;
211 BidiContext::~BidiContext()
213 if(parent) parent->deref();
216 void BidiContext::ref() const
221 void BidiContext::deref() const
224 if(count <= 0) delete this;
227 // ---------------------------------------------------------------------
229 inline bool operator==( const BidiIterator &it1, const BidiIterator &it2 )
231 if(it1.pos != it2.pos) return false;
232 if(it1.obj != it2.obj) return false;
236 inline bool operator!=( const BidiIterator &it1, const BidiIterator &it2 )
238 if(it1.pos != it2.pos) return true;
239 if(it1.obj != it2.obj) return true;
243 static inline RenderObject *Bidinext(RenderObject *par, RenderObject *current, BidiState &bidi,
244 bool skipInlines = true, bool* endOfInline = 0)
246 RenderObject *next = 0;
247 bool oldEndOfInline = endOfInline ? *endOfInline : false;
249 *endOfInline = false;
253 //kdDebug( 6040 ) << "current = " << current << endl;
254 if (!oldEndOfInline && !current->isFloating() && !current->isReplaced() && !current->isPositioned()) {
255 next = current->firstChild();
256 if ( next && adjustEmbedding ) {
257 EUnicodeBidi ub = next->style()->unicodeBidi();
258 if ( ub != UBNormal && !emptyRun ) {
259 EDirection dir = next->style()->direction();
260 QChar::Direction d = ( ub == Embed ? ( dir == RTL ? QChar::DirRLE : QChar::DirLRE )
261 : ( dir == RTL ? QChar::DirRLO : QChar::DirLRO ) );
267 if (!skipInlines && !oldEndOfInline && current->isInlineFlow())
275 while (current && current != par) {
276 next = current->nextSibling();
278 if ( adjustEmbedding && current->style()->unicodeBidi() != UBNormal && !emptyRun ) {
279 embed( QChar::DirPDF, bidi );
281 current = current->parent();
282 if (!skipInlines && current && current != par && current->isInlineFlow()) {
293 if (next->isText() || next->isBR() || next->isFloating() || next->isReplaced() || next->isPositioned()
294 || ((!skipInlines || !next->firstChild()) // Always return EMPTY inlines.
295 && next->isInlineFlow()))
302 static RenderObject *first( RenderObject *par, BidiState &bidi, bool skipInlines = true )
304 if(!par->firstChild()) return 0;
305 RenderObject *o = par->firstChild();
307 if (o->isInlineFlow()) {
308 if (skipInlines && o->firstChild())
309 o = Bidinext( par, o, bidi, skipInlines );
311 return o; // Never skip empty inlines.
314 if (o && !o->isText() && !o->isBR() && !o->isReplaced() && !o->isFloating() && !o->isPositioned())
315 o = Bidinext( par, o, bidi, skipInlines );
319 inline void BidiIterator::increment (BidiState &bidi)
324 if(pos >= static_cast<RenderText *>(obj)->stringLength()) {
325 obj = Bidinext( par, obj, bidi );
329 obj = Bidinext( par, obj, bidi );
334 inline bool BidiIterator::atEnd() const
336 if(!obj) return true;
340 const QChar &BidiIterator::current() const
342 static QChar nullCharacter;
344 if (!obj || !obj->isText())
345 return nullCharacter;
347 RenderText* text = static_cast<RenderText*>(obj);
349 return nullCharacter;
351 return text->text()[pos];
354 inline QChar::Direction BidiIterator::direction() const
358 if (obj->isListMarker())
359 return obj->style()->direction() == LTR ? QChar::DirL : QChar::DirR;
363 RenderText *renderTxt = static_cast<RenderText *>( obj );
364 if ( pos >= renderTxt->stringLength() )
367 return renderTxt->text()[pos].direction();
370 // -------------------------------------------------------------------------------------------------
372 static void addRun(BidiRun* bidiRun)
375 sFirstBidiRun = sLastBidiRun = bidiRun;
377 sLastBidiRun->nextRun = bidiRun;
378 sLastBidiRun = bidiRun;
381 bidiRun->compact = sBuildingCompactRuns;
383 // Compute the number of spaces in this run,
384 if (bidiRun->obj && bidiRun->obj->isText()) {
385 RenderText* text = static_cast<RenderText*>(bidiRun->obj);
387 for (int i = bidiRun->start; i < bidiRun->stop; i++) {
388 const QChar c = text->text()[i];
389 if (c == ' ' || c == '\n')
396 static void reverseRuns(int start, int end)
401 assert(start >= 0 && end < sBidiRunCount);
403 // Get the item before the start of the runs to reverse and put it in
404 // |beforeStart|. |curr| should point to the first run to reverse.
405 BidiRun* curr = sFirstBidiRun;
406 BidiRun* beforeStart = 0;
411 curr = curr->nextRun;
414 BidiRun* startRun = curr;
417 curr = curr->nextRun;
419 BidiRun* endRun = curr;
420 BidiRun* afterEnd = curr->nextRun;
424 BidiRun* newNext = afterEnd;
427 BidiRun* next = curr->nextRun;
428 curr->nextRun = newNext;
434 // Now hook up beforeStart and afterEnd to the newStart and newEnd.
436 beforeStart->nextRun = endRun;
438 sFirstBidiRun = endRun;
440 startRun->nextRun = afterEnd;
442 sLastBidiRun = startRun;
445 static void chopMidpointsAt(RenderObject* obj, uint pos)
447 if (!sNumMidpoints) return;
448 BidiIterator* midpoints = smidpoints->data();
449 for (uint i = 0; i < sNumMidpoints; i++) {
450 const BidiIterator& point = midpoints[i];
451 if (point.obj == obj && point.pos == pos) {
458 static void checkMidpoints(BidiIterator& lBreak, BidiState &bidi)
460 // Check to see if our last midpoint is a start point beyond the line break. If so,
461 // shave it off the list, and shave off a trailing space if the previous end point isn't
463 if (lBreak.obj && sNumMidpoints && sNumMidpoints%2 == 0) {
464 BidiIterator* midpoints = smidpoints->data();
465 BidiIterator& endpoint = midpoints[sNumMidpoints-2];
466 const BidiIterator& startpoint = midpoints[sNumMidpoints-1];
467 BidiIterator currpoint = endpoint;
468 while (!currpoint.atEnd() && currpoint != startpoint && currpoint != lBreak)
469 currpoint.increment( bidi );
470 if (currpoint == lBreak) {
471 // We hit the line break before the start point. Shave off the start point.
473 if (endpoint.obj->style()->whiteSpace() != PRE) {
474 if (endpoint.obj->isText()) {
475 // Don't shave a character off the endpoint if it was from a soft hyphen.
476 RenderText* textObj = static_cast<RenderText*>(endpoint.obj);
477 if (endpoint.pos+1 < textObj->length() &&
478 textObj->text()[endpoint.pos+1].unicode() == SOFT_HYPHEN)
487 static void addMidpoint(const BidiIterator& midpoint)
492 if (smidpoints->size() <= sNumMidpoints)
493 smidpoints->resize(sNumMidpoints+10);
495 BidiIterator* midpoints = smidpoints->data();
496 midpoints[sNumMidpoints++] = midpoint;
499 static void appendRunsForObject(int start, int end, RenderObject* obj, BidiState &bidi)
501 if (start > end || obj->isFloating() ||
502 (obj->isPositioned() && !obj->hasStaticX() && !obj->hasStaticY() && !obj->container()->isInlineFlow()))
505 bool haveNextMidpoint = (smidpoints && sCurrMidpoint < sNumMidpoints);
506 BidiIterator nextMidpoint;
507 if (haveNextMidpoint)
508 nextMidpoint = smidpoints->at(sCurrMidpoint);
509 if (betweenMidpoints) {
510 if (!(haveNextMidpoint && nextMidpoint.obj == obj))
512 // This is a new start point. Stop ignoring objects and
514 betweenMidpoints = false;
515 start = nextMidpoint.pos;
518 return appendRunsForObject(start, end, obj, bidi);
521 if (!smidpoints || !haveNextMidpoint || (obj != nextMidpoint.obj)) {
522 addRun(new (obj->renderArena()) BidiRun(start, end, obj, bidi.context, dir));
526 // An end midpoint has been encountered within our object. We
527 // need to go ahead and append a run with our endpoint.
528 if (int(nextMidpoint.pos+1) <= end) {
529 betweenMidpoints = true;
531 if (nextMidpoint.pos != UINT_MAX) { // UINT_MAX means stop at the object and don't include any of it.
532 addRun(new (obj->renderArena())
533 BidiRun(start, nextMidpoint.pos+1, obj, bidi.context, dir));
534 return appendRunsForObject(nextMidpoint.pos+1, end, obj, bidi);
538 addRun(new (obj->renderArena()) BidiRun(start, end, obj, bidi.context, dir));
542 static void appendRun( BidiState &bidi )
544 if ( emptyRun ) return;
546 kdDebug(6041) << "appendRun: dir="<<(int)dir<<endl;
549 bool b = adjustEmbedding;
550 adjustEmbedding = false;
552 int start = bidi.sor.pos;
553 RenderObject *obj = bidi.sor.obj;
554 while( obj && obj != bidi.eor.obj ) {
555 appendRunsForObject(start, obj->length(), obj, bidi);
557 obj = Bidinext( bidi.sor.par, obj, bidi );
560 appendRunsForObject(start, bidi.eor.pos+1, obj, bidi);
562 bidi.eor.increment( bidi );
565 bidi.status.eor = QChar::DirON;
569 static void embed( QChar::Direction d, BidiState &bidi )
572 qDebug("*** embed dir=%d emptyrun=%d", d, emptyRun );
574 bool b = adjustEmbedding ;
575 adjustEmbedding = false;
576 if ( d == QChar::DirPDF ) {
577 BidiContext *c = bidi.context->parent;
579 if ( bidi.eor != bidi.last ) {
581 bidi.eor = bidi.last;
585 bidi.status.last = bidi.context->dir;
586 bidi.context->deref();
588 if(bidi.context->override)
589 dir = bidi.context->dir;
592 bidi.status.lastStrong = bidi.context->dir;
595 QChar::Direction runDir;
596 if( d == QChar::DirRLE || d == QChar::DirRLO )
597 runDir = QChar::DirR;
599 runDir = QChar::DirL;
601 if( d == QChar::DirLRO || d == QChar::DirRLO )
606 unsigned char level = bidi.context->level;
607 if ( runDir == QChar::DirR ) {
608 if(level%2) // we have an odd level
613 if(level%2) // we have an odd level
620 if ( bidi.eor != bidi.last ) {
622 bidi.eor = bidi.last;
627 bidi.context = new BidiContext(level, runDir, bidi.context, override);
631 bidi.status.last = runDir;
632 bidi.status.lastStrong = runDir;
638 InlineFlowBox* RenderBlock::createLineBoxes(RenderObject* obj)
640 // See if we have an unconstructed line box for this object that is also
641 // the last item on the line.
642 KHTMLAssert(obj->isInlineFlow() || obj == this);
643 RenderFlow* flow = static_cast<RenderFlow*>(obj);
645 // Get the last box we made for this render object.
646 InlineFlowBox* box = flow->lastLineBox();
648 // If this box is constructed then it is from a previous line, and we need
649 // to make a new box for our line. If this box is unconstructed but it has
650 // something following it on the line, then we know we have to make a new box
651 // as well. In this situation our inline has actually been split in two on
652 // the same line (this can happen with very fancy language mixtures).
653 if (!box || box->isConstructed() || box->nextOnLine()) {
654 // We need to make a new box for this render object. Once
655 // made, we need to place it at the end of the current line.
656 InlineBox* newBox = obj->createInlineBox(false, obj == this);
657 KHTMLAssert(newBox->isInlineFlowBox());
658 box = static_cast<InlineFlowBox*>(newBox);
659 box->setFirstLineStyleBit(m_firstLine);
661 // We have a new box. Append it to the inline box we get by constructing our
662 // parent. If we have hit the block itself, then |box| represents the root
663 // inline box for the line, and it doesn't have to be appended to any parent
666 InlineFlowBox* parentBox = createLineBoxes(obj->parent());
667 parentBox->addToLine(box);
674 RootInlineBox* RenderBlock::constructLine(const BidiIterator &start, const BidiIterator &end)
677 return 0; // We had no runs. Don't make a root inline box at all. The line is empty.
679 InlineFlowBox* parentBox = 0;
680 for (BidiRun* r = sFirstBidiRun; r; r = r->nextRun) {
681 // Create a box for our object.
682 r->box = r->obj->createInlineBox(r->obj->isPositioned(), false, sBidiRunCount == 1);
684 // If we have no parent box yet, or if the run is not simply a sibling,
685 // then we need to construct inline boxes as necessary to properly enclose the
687 if (!parentBox || (parentBox->object() != r->obj->parent()))
688 // Create new inline boxes all the way back to the appropriate insertion point.
689 parentBox = createLineBoxes(r->obj->parent());
691 // Append the inline box to this line.
692 parentBox->addToLine(r->box);
696 // We should have a root inline box. It should be unconstructed and
697 // be the last continuation of our line list.
698 KHTMLAssert(lastLineBox() && !lastLineBox()->isConstructed());
700 // Set bits on our inline flow boxes that indicate which sides should
701 // paint borders/margins/padding. This knowledge will ultimately be used when
702 // we determine the horizontal positions and widths of all the inline boxes on
704 RenderObject* endObject = 0;
705 bool lastLine = !end.obj;
706 if (end.obj && end.pos == 0)
708 lastLineBox()->determineSpacingForFlowBoxes(lastLine, endObject);
710 // Now mark the line boxes as being constructed.
711 lastLineBox()->setConstructed();
713 // Return the last line.
714 return lastRootBox();
717 void RenderBlock::computeHorizontalPositionsForLine(RootInlineBox* lineBox, BidiState &bidi)
719 // First determine our total width.
720 int availableWidth = lineWidth(m_height);
721 int totWidth = lineBox->getFlowSpacingWidth();
723 for (r = sFirstBidiRun; r; r = r->nextRun) {
724 if (!r->box || r->obj->isPositioned())
725 continue; // Positioned objects are only participating to figure out their
726 // correct static x position. They have no effect on the width.
727 if (r->obj->isText()) {
728 int textWidth = static_cast<RenderText *>(r->obj)->width(r->start, r->stop-r->start, m_firstLine);
730 RenderStyle *style = r->obj->style();
731 if (style->whiteSpace() == NORMAL && style->khtmlLineBreak() == AFTER_WHITE_SPACE) {
732 // shrink the box as needed to keep the line from overflowing the available width
733 textWidth = kMin(textWidth, availableWidth - totWidth + style->borderLeftWidth());
736 r->box->setWidth(textWidth);
738 else if (!r->obj->isInlineFlow()) {
740 r->box->setWidth(r->obj->width());
742 totWidth += r->obj->marginLeft() + r->obj->marginRight();
745 // Compacts don't contribute to the width of the line, since they are placed in the margin.
747 totWidth += r->box->width();
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
754 int x = leftOffset(m_height);
755 switch(style()->textAlign()) {
758 // The direction of the block should determine what happens with wide lines. In
759 // particular with RTL blocks, wide lines should still spill out to the left.
760 if (style()->direction() == RTL && totWidth > availableWidth)
761 x -= (totWidth - availableWidth);
765 if (numSpaces != 0 && !bidi.current.atEnd() && !lineBox->endsWithBreak())
770 // for right to left fall through to right aligned
771 if (bidi.context->basicDir == QChar::DirL)
775 // Wide lines spill out of the block based off direction.
776 // So even if text-align is right, if direction is LTR, wide lines should overflow out of the right
777 // side of the block.
778 if (style()->direction() == RTL || totWidth < availableWidth)
779 x += availableWidth - totWidth;
784 int xd = (availableWidth - totWidth)/2;
791 for (r = sFirstBidiRun; r; r = r->nextRun) {
792 if (!r->box) continue;
795 if (numSpaces > 0 && r->obj->isText() && !r->compact) {
796 // get the number of spaces in the run
798 for ( int i = r->start; i < r->stop; i++ ) {
799 const QChar c = static_cast<RenderText *>(r->obj)->text()[i];
800 if (c == ' ' || c == '\n')
804 KHTMLAssert(spaces <= numSpaces);
806 // Only justify text with white-space: normal.
807 if (r->obj->style()->whiteSpace() != PRE) {
808 spaceAdd = (availableWidth - totWidth)*spaces/numSpaces;
809 static_cast<InlineTextBox*>(r->box)->setSpaceAdd(spaceAdd);
810 totWidth += spaceAdd;
817 // The widths of all runs are now known. We can now place every inline box (and
818 // compute accurate widths for the inline flow boxes).
819 int leftPosition = x;
820 int rightPosition = x;
821 lineBox->placeBoxesHorizontally(x, leftPosition, rightPosition);
822 lineBox->setHorizontalOverflowPositions(leftPosition, rightPosition);
825 void RenderBlock::computeVerticalPositionsForLine(RootInlineBox* lineBox)
827 lineBox->verticallyAlignBoxes(m_height);
828 lineBox->setBlockHeight(m_height);
830 // See if the line spilled out. If so set overflow height accordingly.
831 int bottomOfLine = lineBox->bottomOverflow();
832 if (bottomOfLine > m_height && bottomOfLine > m_overflowHeight)
833 m_overflowHeight = bottomOfLine;
835 // Now make sure we place replaced render objects correctly.
836 for (BidiRun* r = sFirstBidiRun; r; r = r->nextRun) {
837 if (!r->box) continue; // Skip runs with no line boxes.
839 // Align positioned boxes with the top of the line box. This is
840 // a reasonable approximation of an appropriate y position.
841 if (r->obj->isPositioned())
842 r->box->setYPos(m_height);
844 // Position is used to properly position both replaced elements and
845 // to update the static normal flow x/y of positioned elements.
846 r->obj->position(r->box, r->start, r->stop - r->start, r->level%2);
850 // collects one line of the paragraph and transforms it to visual order
851 void RenderBlock::bidiReorderLine(const BidiIterator &start, const BidiIterator &end, BidiState &bidi)
853 if ( start == end ) {
854 if ( start.current() == '\n' ) {
855 m_height += lineHeight( m_firstLine, true );
861 kdDebug(6041) << "reordering Line from " << start.obj << "/" << start.pos << " to " << end.obj << "/" << end.pos << endl;
872 // Adopt the directionality of the text's element if specified as RTL
873 // and the first position is neutral.
874 if (start.direction() == QChar::DirON) {
876 if (start.obj->style()->direction() == RTL)
879 else if (style()->direction() == RTL) {
888 bidi.current = start;
889 bidi.last = bidi.current;
894 QChar::Direction dirCurrent;
896 //kdDebug(6041) << "atEnd" << endl;
897 BidiContext *c = bidi.context;
898 if ( bidi.current.atEnd())
903 dirCurrent = bidi.current.direction();
906 #ifndef QT_NO_UNICODETABLES
909 kdDebug(6041) << "directions: dir=" << (int)dir << " current=" << (int)dirCurrent << " last=" << status.last << " eor=" << status.eor << " lastStrong=" << status.lastStrong << " embedding=" << (int)context->dir << " level =" << (int)context->level << endl;
914 // embedding and overrides (X1-X9 in the Bidi specs)
920 bidi.eor = bidi.last;
921 embed( dirCurrent, bidi );
926 if(dir == QChar::DirON)
928 switch(bidi.status.last)
931 bidi.eor = bidi.current; bidi.status.eor = QChar::DirL; break;
946 if(dir != QChar::DirL) {
947 //last stuff takes embedding dir
948 if( bidi.context->dir == QChar::DirR ) {
949 if(!(bidi.status.eor == QChar::DirR)) {
955 bidi.eor = bidi.last;
958 bidi.status.eor = QChar::DirL;
960 if(bidi.status.eor == QChar::DirR) {
964 bidi.eor = bidi.current; bidi.status.eor = QChar::DirL; break;
968 bidi.eor = bidi.current; bidi.status.eor = QChar::DirL;
973 bidi.status.lastStrong = QChar::DirL;
977 if(dir == QChar::DirON) dir = QChar::DirR;
978 switch(bidi.status.last)
982 bidi.eor = bidi.current; bidi.status.eor = QChar::DirR; break;
988 bidi.eor = bidi.current;
989 bidi.status.eor = QChar::DirR;
999 if( !(bidi.status.eor == QChar::DirR) && !(bidi.status.eor == QChar::DirAL) ) {
1000 //last stuff takes embedding dir
1001 if(bidi.context->dir == QChar::DirR || bidi.status.lastStrong == QChar::DirR) {
1004 bidi.eor = bidi.current;
1005 bidi.status.eor = QChar::DirR;
1007 bidi.eor = bidi.last;
1010 bidi.status.eor = QChar::DirR;
1013 bidi.eor = bidi.current; bidi.status.eor = QChar::DirR;
1018 bidi.status.lastStrong = dirCurrent;
1024 // ### if @sor, set dir to dirSor
1027 if(!(bidi.status.lastStrong == QChar::DirAL)) {
1028 // if last strong was AL change EN to AN
1029 if(dir == QChar::DirON) {
1030 if(bidi.status.lastStrong == QChar::DirAL)
1035 switch(bidi.status.last)
1038 if ( bidi.status.lastStrong == QChar::DirR || bidi.status.lastStrong == QChar::DirAL ) {
1041 bidi.status.eor = QChar::DirEN;
1046 bidi.eor = bidi.current;
1047 bidi.status.eor = dirCurrent;
1053 bidi.status.eor = QChar::DirEN;
1054 dir = QChar::DirEN; break;
1057 if(bidi.status.eor == QChar::DirEN) {
1058 bidi.eor = bidi.current; break;
1065 if(bidi.status.eor == QChar::DirR) {
1067 bidi.eor = bidi.last;
1070 bidi.status.eor = QChar::DirEN;
1072 else if( bidi.status.eor == QChar::DirL ||
1073 (bidi.status.eor == QChar::DirEN && bidi.status.lastStrong == QChar::DirL)) {
1074 bidi.eor = bidi.current; bidi.status.eor = dirCurrent;
1076 // numbers on both sides, neutrals get right to left direction
1077 if(dir != QChar::DirL) {
1079 bidi.eor = bidi.last;
1083 bidi.status.eor = QChar::DirEN;
1085 bidi.eor = bidi.current; bidi.status.eor = dirCurrent;
1094 dirCurrent = QChar::DirAN;
1095 if(dir == QChar::DirON) dir = QChar::DirAN;
1096 switch(bidi.status.last)
1100 bidi.eor = bidi.current; bidi.status.eor = QChar::DirAN; break;
1105 dir = QChar::DirAN; bidi.status.eor = QChar::DirAN;
1108 if(bidi.status.eor == QChar::DirAN) {
1109 bidi.eor = bidi.current; bidi.status.eor = QChar::DirR; break;
1118 if(bidi.status.eor == QChar::DirR) {
1120 bidi.eor = bidi.last;
1123 bidi.status.eor = QChar::DirAN;
1124 } else if( bidi.status.eor == QChar::DirL ||
1125 (bidi.status.eor == QChar::DirEN && bidi.status.lastStrong == QChar::DirL)) {
1126 bidi.eor = bidi.current; bidi.status.eor = dirCurrent;
1128 // numbers on both sides, neutrals get right to left direction
1129 if(dir != QChar::DirL) {
1131 bidi.eor = bidi.last;
1135 bidi.status.eor = QChar::DirAN;
1137 bidi.eor = bidi.current; bidi.status.eor = dirCurrent;
1148 if(bidi.status.last == QChar::DirEN) {
1149 dirCurrent = QChar::DirEN;
1150 bidi.eor = bidi.current; bidi.status.eor = dirCurrent;
1155 // boundary neutrals should be ignored
1160 // ### what do we do with newline and paragraph seperators that come to here?
1163 // ### implement rule L1
1173 //cout << " after: dir=" << // dir << " current=" << dirCurrent << " last=" << status.last << " eor=" << status.eor << " lastStrong=" << status.lastStrong << " embedding=" << context->dir << endl;
1175 if(bidi.current.atEnd()) break;
1177 // set status.last as needed.
1186 switch(bidi.status.last)
1193 bidi.status.last = dirCurrent;
1196 bidi.status.last = QChar::DirON;
1204 if ( bidi.status.last == QChar::DirL ) {
1205 bidi.status.last = QChar::DirL;
1210 bidi.status.last = dirCurrent;
1215 bidi.last = bidi.current;
1218 bidi.sor = bidi.current;
1219 bidi.eor = bidi.current;
1223 // this causes the operator ++ to open and close embedding levels as needed
1224 // for the CSS unicode-bidi property
1225 adjustEmbedding = true;
1226 bidi.current.increment( bidi );
1227 adjustEmbedding = false;
1229 if ( bidi.current == end ) {
1237 kdDebug(6041) << "reached end of line current=" << current.obj << "/" << current.pos
1238 << ", eor=" << eor.obj << "/" << eor.pos << endl;
1240 if ( !emptyRun && bidi.sor != bidi.current ) {
1241 bidi.eor = bidi.last;
1245 // reorder line according to run structure...
1247 // first find highest and lowest levels
1248 uchar levelLow = 128;
1249 uchar levelHigh = 0;
1250 BidiRun *r = sFirstBidiRun;
1252 if ( r->level > levelHigh )
1253 levelHigh = r->level;
1254 if ( r->level < levelLow )
1255 levelLow = r->level;
1259 // implements reordering of the line (L2 according to Bidi spec):
1260 // L2. From the highest level found in the text to the lowest odd level on each line,
1261 // reverse any contiguous sequence of characters that are at that level or higher.
1263 // reversing is only done up to the lowest odd level
1264 if( !(levelLow%2) ) levelLow++;
1267 kdDebug(6041) << "lineLow = " << (uint)levelLow << ", lineHigh = " << (uint)levelHigh << endl;
1268 kdDebug(6041) << "logical order is:" << endl;
1269 QPtrListIterator<BidiRun> it2(runs);
1271 for ( ; (r2 = it2.current()); ++it2 )
1272 kdDebug(6041) << " " << r2 << " start=" << r2->start << " stop=" << r2->stop << " level=" << (uint)r2->level << endl;
1275 int count = sBidiRunCount - 1;
1277 // do not reverse for visually ordered web sites
1278 if(!style()->visuallyOrdered()) {
1279 while(levelHigh >= levelLow) {
1281 BidiRun* currRun = sFirstBidiRun;
1282 while ( i < count ) {
1283 while(i < count && currRun && currRun->level < levelHigh) {
1285 currRun = currRun->nextRun;
1288 while(i <= count && currRun && currRun->level >= levelHigh) {
1290 currRun = currRun->nextRun;
1293 reverseRuns(start, end);
1295 if(i >= count) break;
1302 kdDebug(6041) << "visual order is:" << endl;
1303 for (BidiRun* curr = sFirstRun; curr; curr = curr->nextRun)
1304 kdDebug(6041) << " " << curr << endl;
1308 static void buildCompactRuns(RenderObject* compactObj, BidiState &bidi)
1310 sBuildingCompactRuns = true;
1311 if (!compactObj->isRenderBlock()) {
1312 // Just append a run for our object.
1313 isLineEmpty = false;
1314 addRun(new (compactObj->renderArena()) BidiRun(0, compactObj->length(), compactObj, bidi.context, dir));
1317 // Format the compact like it is its own single line. We build up all the runs for
1318 // the little compact and then reorder them for bidi.
1319 RenderBlock* compactBlock = static_cast<RenderBlock*>(compactObj);
1320 adjustEmbedding = true;
1321 BidiIterator start(compactBlock, first(compactBlock, bidi), 0);
1322 adjustEmbedding = false;
1323 BidiIterator end = start;
1325 betweenMidpoints = false;
1327 previousLineBrokeCleanly = true;
1329 end = compactBlock->findNextLineBreak(start, bidi);
1331 compactBlock->bidiReorderLine(start, end, bidi);
1335 sCompactFirstBidiRun = sFirstBidiRun;
1336 sCompactLastBidiRun = sLastBidiRun;
1337 sCompactBidiRunCount = sBidiRunCount;
1341 betweenMidpoints = false;
1342 sBuildingCompactRuns = false;
1345 QRect RenderBlock::layoutInlineChildren(bool relayoutChildren)
1349 bool useRepaintRect = false;
1350 QRect repaintRect(0,0,0,0);
1352 m_overflowHeight = 0;
1354 invalidateVerticalPositions();
1358 kdDebug( 6040 ) << renderName() << " layoutInlineChildren( " << this <<" )" << endl;
1360 #if BIDI_DEBUG > 1 || defined( DEBUG_LINEBREAKS )
1361 kdDebug(6041) << " ------- bidi start " << this << " -------" << endl;
1364 m_height = borderTop() + paddingTop();
1365 int toAdd = borderBottom() + paddingBottom();
1366 if (includeScrollbarSize())
1367 toAdd += m_layer->horizontalScrollbarHeight();
1369 // Figure out if we should clear out our line boxes.
1370 // FIXME: Handle resize eventually!
1371 // FIXME: Do something better when floats are present.
1372 bool fullLayout = !firstLineBox() || !firstChild() || selfNeedsLayout() || relayoutChildren || containsFloats();
1376 // Text truncation only kicks in if your overflow isn't visible and your text-overflow-mode isn't
1378 // FIXME: CSS3 says that descendants that are clipped must also know how to truncate. This is insanely
1379 // difficult to figure out (especially in the middle of doing layout), and is really an esoteric pile of nonsense
1380 // anyway, so we won't worry about following the draft here.
1381 bool hasTextOverflow = style()->textOverflow() && hasOverflowClip();
1383 // Walk all the lines and delete our ellipsis line boxes if they exist.
1384 if (hasTextOverflow)
1385 deleteEllipsisLineBoxes();
1387 int oldLineBottom = lastRootBox() ? lastRootBox()->bottomOverflow() : m_height;
1388 int startLineBottom = 0;
1391 // layout replaced elements
1392 bool endOfInline = false;
1393 RenderObject *o = first(this, bidi, false);
1394 bool hasFloat = false;
1396 if (o->isReplaced() || o->isFloating() || o->isPositioned()) {
1397 if (relayoutChildren || o->style()->width().isPercent() || o->style()->height().isPercent())
1398 o->setChildNeedsLayout(true, false);
1399 if (o->isPositioned())
1400 o->containingBlock()->insertPositionedObject(o);
1402 if (o->isFloating())
1404 else if (fullLayout || o->needsLayout()) // Replaced elements
1405 o->dirtyLineBoxes(fullLayout);
1406 o->layoutIfNeeded();
1409 else if (o->isText() || (o->isInlineFlow() && !endOfInline)) {
1410 if (fullLayout || o->selfNeedsLayout())
1411 o->dirtyLineBoxes(fullLayout);
1412 o->setNeedsLayout(false);
1414 o = Bidinext( this, o, bidi, false, &endOfInline);
1418 fullLayout = true; // FIXME: Will need to find a way to optimize floats some day.
1420 if (fullLayout && !selfNeedsLayout()) {
1421 setNeedsLayout(true, false); // Mark ourselves as needing a full layout. This way we'll repaint like
1422 // we're supposed to.
1423 if (!document()->view()->needsFullRepaint() && m_layer) {
1424 // Because we waited until we were already inside layout to discover
1425 // that the block really needed a full layout, we missed our chance to repaint the layer
1426 // before layout started. Luckily the layer has cached the repaint rect for its original
1427 // position and size, and so we can use that to make a repaint happen now.
1428 RenderCanvas* c = canvas();
1429 if (c && !c->printingMode())
1430 c->repaintViewRectangle(m_layer->repaintRect());
1434 BidiContext *startEmbed;
1435 if( style()->direction() == LTR ) {
1436 startEmbed = new BidiContext( 0, QChar::DirL );
1437 bidi.status.eor = QChar::DirL;
1439 startEmbed = new BidiContext( 1, QChar::DirR );
1440 bidi.status.eor = QChar::DirR;
1444 bidi.status.lastStrong = QChar::DirON;
1445 bidi.status.last = QChar::DirON;
1446 bidi.context = startEmbed;
1449 smidpoints = new QMemArray<BidiIterator>;
1453 sCompactFirstBidiRun = sCompactLastBidiRun = 0;
1454 sCompactBidiRunCount = 0;
1456 // We want to skip ahead to the first dirty line
1458 RootInlineBox* startLine = determineStartPosition(fullLayout, start, bidi);
1460 // We also find the first clean line and extract these lines. We will add them back
1461 // if we determine that we're able to synchronize after handling all our dirty lines.
1462 BidiIterator cleanLineStart;
1464 RootInlineBox* endLine = (fullLayout || !startLine) ?
1465 0 : determineEndPosition(startLine, cleanLineStart, endLineYPos);
1467 useRepaintRect = true;
1468 startLineBottom = startLine->bottomOverflow();
1469 repaintRect.setY(kMin(m_height, startLine->topOverflow()));
1470 RenderArena* arena = renderArena();
1471 RootInlineBox* box = startLine;
1473 RootInlineBox* next = box->nextRootBox();
1474 box->deleteLine(arena);
1480 BidiIterator end = start;
1482 bool endLineMatched = false;
1483 while (!end.atEnd()) {
1485 if (endLine && (endLineMatched = matchedEndLine(start, cleanLineStart, endLine, endLineYPos)))
1488 betweenMidpoints = false;
1490 if (m_firstLine && firstChild() && firstChild()->isCompact() && firstChild()->isRenderBlock()) {
1491 buildCompactRuns(firstChild(), bidi);
1492 start.obj = firstChild()->nextSibling();
1495 end = findNextLineBreak(start, bidi);
1496 if( start.atEnd() ) break;
1498 bidiReorderLine(start, end, bidi);
1500 // Now that the runs have been ordered, we create the line boxes.
1501 // At the same time we figure out where border/padding/margin should be applied for
1502 // inline flow boxes.
1503 if (sCompactFirstBidiRun) {
1504 // We have a compact line sharing this line. Link the compact runs
1505 // to our runs to create a single line of runs.
1506 sCompactLastBidiRun->nextRun = sFirstBidiRun;
1507 sFirstBidiRun = sCompactFirstBidiRun;
1508 sBidiRunCount += sCompactBidiRunCount;
1511 RootInlineBox* lineBox = 0;
1512 if (sBidiRunCount) {
1513 lineBox = constructLine(start, end);
1515 lineBox->setEndsWithBreak(previousLineBrokeCleanly);
1517 // Now we position all of our text runs horizontally.
1518 computeHorizontalPositionsForLine(lineBox, bidi);
1520 // Now position our text runs vertically.
1521 computeVerticalPositionsForLine(lineBox);
1523 deleteBidiRuns(renderArena());
1527 if (end == start || (!previousLineBrokeCleanly && end.obj && end.obj->style()->whiteSpace() == PRE && end.current() == QChar('\n'))) {
1528 adjustEmbedding = true;
1529 end.increment(bidi);
1530 adjustEmbedding = false;
1534 lineBox->setLineBreakInfo(end.obj, end.pos);
1536 m_firstLine = false;
1542 sCompactFirstBidiRun = sCompactLastBidiRun = 0;
1543 sCompactBidiRunCount = 0;
1545 startEmbed->deref();
1549 if (endLineMatched) {
1550 // Note our current y-position for correct repainting when no lines move. If no lines move, we still have to
1551 // repaint up to the maximum of the bottom overflow of the old start line or the bottom overflow of the new last line.
1552 int currYPos = kMax(startLineBottom, m_height);
1554 currYPos = kMax(currYPos, lastRootBox()->bottomOverflow());
1556 // Attach all the remaining lines, and then adjust their y-positions as needed.
1557 for (RootInlineBox* line = endLine; line; line = line->nextRootBox())
1560 // Now apply the offset to each line if needed.
1561 int delta = m_height - endLineYPos;
1563 for (RootInlineBox* line = endLine; line; line = line->nextRootBox())
1564 line->adjustPosition(0, delta);
1565 m_height = lastRootBox()->blockHeight();
1566 m_overflowHeight = kMax(m_height, m_overflowHeight);
1567 int bottomOfLine = lastRootBox()->bottomOverflow();
1568 if (bottomOfLine > m_height && bottomOfLine > m_overflowHeight)
1569 m_overflowHeight = bottomOfLine;
1571 repaintRect.setHeight(kMax(m_overflowHeight-delta, m_overflowHeight) - repaintRect.y());
1573 repaintRect.setHeight(currYPos - repaintRect.y());
1576 // Delete all the remaining lines.
1577 m_overflowHeight = kMax(m_height, m_overflowHeight);
1578 InlineRunBox* line = endLine;
1579 RenderArena* arena = renderArena();
1581 InlineRunBox* next = line->nextLineBox();
1583 repaintRect.setHeight(kMax(m_overflowHeight, line->bottomOverflow()) - repaintRect.y());
1584 line->deleteLine(arena);
1594 // in case we have a float on the last line, it might not be positioned up to now.
1595 // This has to be done before adding in the bottom border/padding, or the float will
1596 // include the padding incorrectly. -dwh
1597 positionNewFloats();
1599 // Now add in the bottom border/padding.
1602 // Always make sure this is at least our height.
1603 m_overflowHeight = kMax(m_height, m_overflowHeight);
1605 // See if any lines spill out of the block. If so, we need to update our overflow width.
1606 checkLinesForOverflow();
1608 if (useRepaintRect) {
1609 repaintRect.setWidth(kMax((int)m_width, m_overflowWidth));
1610 if (repaintRect.height() == 0)
1611 repaintRect.setHeight(kMax(oldLineBottom, m_overflowHeight) - repaintRect.y());
1614 if (!firstLineBox() && element() && element()->isContentEditable() && element()->rootEditableElement() == element())
1615 m_height += lineHeight(true);
1617 // See if we have any lines that spill out of our block. If we do, then we will possibly need to
1619 if (hasTextOverflow)
1620 checkLinesForTextOverflow();
1625 kdDebug(6041) << " ------- bidi end " << this << " -------" << endl;
1627 //kdDebug() << "RenderBlock::layoutInlineChildren time used " << qt.elapsed() << endl;
1628 //kdDebug(6040) << "height = " << m_height <<endl;
1631 RootInlineBox* RenderBlock::determineStartPosition(bool fullLayout, BidiIterator& start, BidiState& bidi)
1633 RootInlineBox* curr = 0;
1634 RootInlineBox* last = 0;
1635 RenderObject* startObj = 0;
1639 // Nuke all our lines.
1640 if (firstRootBox()) {
1641 RenderArena* arena = renderArena();
1642 curr = firstRootBox();
1644 RootInlineBox* next = curr->nextRootBox();
1645 curr->deleteLine(arena);
1648 KHTMLAssert(!m_firstLineBox && !m_lastLineBox);
1652 for (curr = firstRootBox(); curr && !curr->isDirty(); curr = curr->nextRootBox());
1654 // We have a dirty line.
1655 if (curr->prevRootBox()) {
1656 // We have a previous line.
1657 if (!curr->prevRootBox()->endsWithBreak())
1658 curr = curr->prevRootBox(); // The previous line didn't break cleanly, so treat it as dirty also.
1662 // No dirty lines were found.
1663 // If the last line didn't break cleanly, treat it as dirty.
1664 if (lastRootBox() && !lastRootBox()->endsWithBreak())
1665 curr = lastRootBox();
1668 // If we have no dirty lines, then last is just the last root box.
1669 last = curr ? curr->prevRootBox() : lastRootBox();
1672 m_firstLine = !last;
1673 previousLineBrokeCleanly = !last || last->endsWithBreak();
1675 m_height = last->blockHeight();
1676 int bottomOfLine = last->bottomOverflow();
1677 if (bottomOfLine > m_height && bottomOfLine > m_overflowHeight)
1678 m_overflowHeight = bottomOfLine;
1679 startObj = last->lineBreakObj();
1680 pos = last->lineBreakPos();
1683 startObj = first(this, bidi, 0);
1685 adjustEmbedding = true;
1686 start = BidiIterator(this, startObj, pos);
1688 adjustEmbedding = false;
1693 RootInlineBox* RenderBlock::determineEndPosition(RootInlineBox* startLine, BidiIterator& cleanLineStart,
1696 RootInlineBox* last = 0;
1700 for (RootInlineBox* curr = startLine->nextRootBox(); curr; curr = curr->nextRootBox()) {
1701 if (curr->isDirty())
1711 cleanLineStart = BidiIterator(this, last->prevRootBox()->lineBreakObj(), last->prevRootBox()->lineBreakPos());
1712 yPos = last->prevRootBox()->blockHeight();
1714 for (RootInlineBox* line = last; line; line = line->nextRootBox())
1715 line->extractLine(); // Disconnect all line boxes from their render objects while preserving
1716 // their connections to one another.
1721 bool RenderBlock::matchedEndLine(const BidiIterator& start, const BidiIterator& endLineStart,
1722 RootInlineBox*& endLine, int& endYPos)
1724 if (start == endLineStart)
1725 return true; // The common case. All the data we already have is correct.
1727 // The first clean line doesn't match, but we can check a handful of following lines to try
1728 // to match back up.
1729 static int numLines = 8; // The # of lines we're willing to match against.
1730 RootInlineBox* line = endLine;
1731 for (int i = 0; i < numLines && line; i++, line = line->nextRootBox()) {
1732 if (line->lineBreakObj() == start.obj && line->lineBreakPos() == start.pos) {
1734 RootInlineBox* result = line->nextRootBox();
1736 // Set our yPos to be the block height of endLine.
1738 endYPos = line->blockHeight();
1740 // Now delete the lines that we failed to sync.
1741 RootInlineBox* boxToDelete = endLine;
1742 RenderArena* arena = renderArena();
1743 while (boxToDelete && boxToDelete != result) {
1744 RootInlineBox* next = boxToDelete->nextRootBox();
1745 boxToDelete->deleteLine(arena);
1757 static const ushort nonBreakingSpace = 0xa0;
1759 inline bool RenderBlock::skipNonBreakingSpace(BidiIterator &it)
1761 if (it.obj->style()->nbspMode() != SPACE || it.current().unicode() != nonBreakingSpace)
1764 // Do not skip a non-breaking space if it is the first character
1765 // on the first line of a block.
1766 if (m_firstLine && isLineEmpty)
1769 // Do not skip a non-breaking space if it is the first character
1770 // on a line after a clean line break.
1771 if (!m_firstLine && isLineEmpty && previousLineBrokeCleanly)
1777 int RenderBlock::skipWhitespace(BidiIterator &it, BidiState &bidi)
1779 // FIXME: The entire concept of the skipWhitespace function is flawed, since we really need to be building
1780 // line boxes even for containers that may ultimately collapse away. Otherwise we'll never get positioned
1781 // elements quite right. In other words, we need to build this function's work into the normal line
1782 // object iteration process.
1783 int w = lineWidth(m_height);
1784 while (!it.atEnd() && (it.obj->isInlineFlow() || (it.obj->style()->whiteSpace() != PRE && !it.obj->isBR() &&
1785 (it.current() == ' ' || it.current() == '\n' ||
1786 skipNonBreakingSpace(it) || it.obj->isFloatingOrPositioned())))) {
1787 if (it.obj->isFloatingOrPositioned()) {
1788 RenderObject *o = it.obj;
1789 // add to special objects...
1790 if (o->isFloating()) {
1791 insertFloatingObject(o);
1792 positionNewFloats();
1793 w = lineWidth(m_height);
1795 else if (o->isPositioned()) {
1796 // FIXME: The math here is actually not really right. It's a best-guess approximation that
1797 // will work for the common cases
1798 RenderObject* c = o->container();
1799 if (c->isInlineFlow()) {
1800 // A relative positioned inline encloses us. In this case, we also have to determine our
1801 // position as though we were an inline. Set |staticX| and |staticY| on the relative positioned
1802 // inline so that we can obtain the value later.
1803 c->setStaticX(style()->direction() == LTR ?
1804 leftOffset(m_height) : rightOffset(m_height));
1805 c->setStaticY(m_height);
1808 if (o->hasStaticX()) {
1809 bool wasInline = o->style()->isOriginalDisplayInlineType();
1811 o->setStaticX(style()->direction() == LTR ?
1812 leftOffset(m_height) :
1813 width() - rightOffset(m_height));
1815 o->setStaticX(style()->direction() == LTR ?
1816 borderLeft() + paddingLeft() :
1817 borderRight() + paddingRight());
1819 if (o->hasStaticY())
1820 o->setStaticY(m_height);
1824 adjustEmbedding = true;
1826 adjustEmbedding = false;
1831 BidiIterator RenderBlock::findNextLineBreak(BidiIterator &start, BidiState &bidi)
1833 int width = lineWidth(m_height);
1836 #ifdef DEBUG_LINEBREAKS
1837 kdDebug(6041) << "findNextLineBreak: line at " << m_height << " line width " << width << endl;
1838 kdDebug(6041) << "sol: " << start.obj << " " << start.pos << endl;
1841 // eliminate spaces at beginning of line
1842 width = skipWhitespace(start, bidi);
1846 // This variable is used only if whitespace isn't set to PRE, and it tells us whether
1847 // or not we are currently ignoring whitespace.
1848 bool ignoringSpaces = false;
1849 BidiIterator ignoreStart;
1851 // This variable tracks whether the very last character we saw was a space. We use
1852 // this to detect when we encounter a second space so we know we have to terminate
1854 bool currentCharacterIsSpace = false;
1855 bool currentCharacterIsWS = false;
1856 RenderObject* trailingSpaceObject = 0;
1858 BidiIterator lBreak = start;
1860 RenderObject *o = start.obj;
1861 RenderObject *last = o;
1862 int pos = start.pos;
1864 bool prevLineBrokeCleanly = previousLineBrokeCleanly;
1865 previousLineBrokeCleanly = false;
1868 #ifdef DEBUG_LINEBREAKS
1869 kdDebug(6041) << "new object "<< o <<" width = " << w <<" tmpw = " << tmpW << endl;
1872 if (w + tmpW <= width) {
1875 lBreak.increment(bidi);
1877 // A <br> always breaks a line, so don't let the line be collapsed
1878 // away. Also, the space at the end of a line with a <br> does not
1879 // get collapsed away. It only does this if the previous line broke
1880 // cleanly. Otherwise the <br> has no effect on whether the line is
1882 if (prevLineBrokeCleanly)
1883 isLineEmpty = false;
1884 trailingSpaceObject = 0;
1885 previousLineBrokeCleanly = true;
1888 // only check the clear status for non-empty lines.
1889 EClear clear = o->style()->clear();
1891 m_clearStatus = (EClear) (m_clearStatus | clear);
1896 if( o->isFloatingOrPositioned() ) {
1897 // add to special objects...
1898 if(o->isFloating()) {
1899 insertFloatingObject(o);
1900 // check if it fits in the current line.
1901 // If it does, position it now, otherwise, position
1902 // it after moving to next line (in newLine() func)
1903 if (o->width()+o->marginLeft()+o->marginRight()+w+tmpW <= width) {
1904 positionNewFloats();
1905 width = lineWidth(m_height);
1908 else if (o->isPositioned()) {
1909 // If our original display wasn't an inline type, then we can
1910 // go ahead and determine our static x position now.
1911 bool isInlineType = o->style()->isOriginalDisplayInlineType();
1912 bool needToSetStaticX = o->hasStaticX();
1913 if (o->hasStaticX() && !isInlineType) {
1914 o->setStaticX(o->parent()->style()->direction() == LTR ?
1915 borderLeft()+paddingLeft() :
1916 borderRight()+paddingRight());
1917 needToSetStaticX = false;
1920 // If our original display was an INLINE type, then we can go ahead
1921 // and determine our static y position now.
1922 bool needToSetStaticY = o->hasStaticY();
1923 if (o->hasStaticY() && isInlineType) {
1924 o->setStaticY(m_height);
1925 needToSetStaticY = false;
1928 bool needToCreateLineBox = needToSetStaticX || needToSetStaticY;
1929 RenderObject* c = o->container();
1930 if (c->isInlineFlow() && (!needToSetStaticX || !needToSetStaticY))
1931 needToCreateLineBox = true;
1933 // If we're ignoring spaces, we have to stop and include this object and
1934 // then start ignoring spaces again.
1935 if (needToCreateLineBox) {
1936 trailingSpaceObject = 0;
1937 ignoreStart.obj = o;
1938 ignoreStart.pos = 0;
1939 if (ignoringSpaces) {
1940 addMidpoint(ignoreStart); // Stop ignoring spaces.
1941 addMidpoint(ignoreStart); // Start ignoring again.
1946 } else if (o->isInlineFlow()) {
1947 // Only empty inlines matter. We treat those similarly to replaced elements.
1948 KHTMLAssert(!o->firstChild());
1949 tmpW += o->marginLeft()+o->borderLeft()+o->paddingLeft()+
1950 o->marginRight()+o->borderRight()+o->paddingRight();
1951 } else if ( o->isReplaced() ) {
1952 EWhiteSpace currWS = o->style()->whiteSpace();
1953 EWhiteSpace lastWS = last->style()->whiteSpace();
1955 // WinIE marquees have different whitespace characteristics by default when viewed from
1956 // the outside vs. the inside. Text inside is NOWRAP, and so we altered the marquee's
1957 // style to reflect this, but we now have to get back to the original whitespace value
1958 // for the marquee when checking for line breaking.
1959 if (o->isHTMLMarquee() && o->layer() && o->layer()->marquee())
1960 currWS = o->layer()->marquee()->whiteSpace();
1961 if (last->isHTMLMarquee() && last->layer() && last->layer()->marquee())
1962 lastWS = last->layer()->marquee()->whiteSpace();
1964 // Break on replaced elements if either has normal white-space.
1965 // FIXME: This does not match WinIE, Opera, and Mozilla. They treat replaced elements
1966 // like characters in a word, and require spaces between the replaced elements in order
1968 if (currWS == NORMAL || lastWS == NORMAL) {
1975 tmpW += o->width()+o->marginLeft()+o->marginRight()+inlineWidth(o);
1976 if (ignoringSpaces) {
1977 BidiIterator startMid( 0, o, 0 );
1978 addMidpoint(startMid);
1980 isLineEmpty = false;
1981 ignoringSpaces = false;
1982 currentCharacterIsSpace = false;
1983 currentCharacterIsWS = false;
1984 trailingSpaceObject = 0;
1986 if (o->isListMarker() && o->style()->listStylePosition() == OUTSIDE) {
1987 // The marker must not have an effect on whitespace at the start
1988 // of the line. We start ignoring spaces to make sure that any additional
1989 // spaces we see will be discarded.
1991 // Optimize for a common case. If we can't find whitespace after the list
1992 // item, then this is all moot. -dwh
1993 RenderObject* next = Bidinext( start.par, o, bidi );
1994 if (!m_pre && next && next->isText() && static_cast<RenderText*>(next)->stringLength() > 0) {
1995 if (static_cast<RenderText*>(next)->text()[0].unicode() == nonBreakingSpace &&
1996 o->style()->whiteSpace() == NORMAL && o->style()->nbspMode() == SPACE) {
1997 currentCharacterIsWS = true;
1999 if (static_cast<RenderText*>(next)->text()[0].unicode() == ' ' ||
2000 static_cast<RenderText*>(next)->text()[0] == '\n') {
2001 currentCharacterIsSpace = true;
2002 currentCharacterIsWS = true;
2003 ignoringSpaces = true;
2004 BidiIterator endMid( 0, o, 0 );
2005 addMidpoint(endMid);
2009 } else if ( o->isText() ) {
2010 RenderText *t = static_cast<RenderText *>(o);
2011 int strlen = t->stringLength();
2012 int len = strlen - pos;
2013 QChar *str = t->text();
2015 const Font *f = t->htmlFont( m_firstLine );
2016 // proportional font, needs a bit more work.
2017 int lastSpace = pos;
2018 bool isPre = o->style()->whiteSpace() == PRE;
2019 int wordSpacing = o->style()->wordSpacing();
2021 bool appliedStartWidth = pos > 0; // If the span originated on a previous line,
2022 // then assume the start width has been applied.
2023 bool appliedEndWidth = false;
2028 bool previousCharacterIsSpace = currentCharacterIsSpace;
2029 bool previousCharacterIsWS = currentCharacterIsWS;
2030 const QChar c = str[pos];
2031 currentCharacterIsSpace = c == ' ' || (!isPre && c == '\n');
2033 if (isPre || !currentCharacterIsSpace)
2034 isLineEmpty = false;
2036 // Check for soft hyphens. Go ahead and ignore them.
2037 if (c.unicode() == SOFT_HYPHEN && pos > 0) {
2038 if (!ignoringSpaces) {
2039 // Ignore soft hyphens
2040 BidiIterator endMid(0, o, pos-1);
2041 addMidpoint(endMid);
2043 // Add the width up to but not including the hyphen.
2044 tmpW += t->width(lastSpace, pos - lastSpace, f);
2046 // For whitespace normal only, include the hyphen. We need to ensure it will fit
2047 // on the line if it shows when we break.
2048 if (o->style()->whiteSpace() == NORMAL)
2049 tmpW += t->width(pos, 1, f);
2051 BidiIterator startMid(0, o, pos+1);
2052 addMidpoint(startMid);
2057 lastSpace = pos; // Cheesy hack to prevent adding in widths of the run twice.
2061 bool applyWordSpacing = false;
2062 bool isNormal = o->style()->whiteSpace() == NORMAL;
2063 bool breakNBSP = isNormal && o->style()->nbspMode() == SPACE;
2064 bool breakWords = w == 0 && isNormal && o->style()->wordWrap() == BREAK_WORD;
2066 currentCharacterIsWS = currentCharacterIsSpace || (breakNBSP && c.unicode() == nonBreakingSpace);
2069 wrapW += t->width(pos, 1, f);
2070 if ((isPre && c == '\n') || (!isPre && isBreakable(str, pos, strlen, breakNBSP)) || (breakWords && wrapW > width)) {
2071 if (ignoringSpaces) {
2072 if (!currentCharacterIsSpace) {
2073 // Stop ignoring spaces and begin at this
2075 ignoringSpaces = false;
2076 lastSpace = pos; // e.g., "Foo goo", don't add in any of the ignored spaces.
2077 BidiIterator startMid ( 0, o, pos );
2078 addMidpoint(startMid);
2080 // Just keep ignoring these spaces.
2087 tmpW += t->width(lastSpace, pos - lastSpace, f);
2088 if (!appliedStartWidth) {
2089 tmpW += inlineWidth(o, true, false);
2090 appliedStartWidth = true;
2093 applyWordSpacing = (wordSpacing && currentCharacterIsSpace && !previousCharacterIsSpace &&
2094 !t->containsOnlyWhitespace(pos+1, strlen-(pos+1)));
2096 #ifdef DEBUG_LINEBREAKS
2097 kdDebug(6041) << "found space at " << pos << " in string '" << QString( str, strlen ).latin1() << "' adding " << tmpW << " new width = " << w << endl;
2099 if ( !isPre && w + tmpW > width && w == 0 ) {
2100 int fb = nearestFloatBottom(m_height);
2101 int newLineWidth = lineWidth(fb);
2102 // See if |tmpW| will fit on the new line. As long as it does not,
2103 // keep adjusting our float bottom until we find some room.
2104 int lastFloatBottom = m_height;
2105 while (lastFloatBottom < fb && tmpW > newLineWidth) {
2106 lastFloatBottom = fb;
2107 fb = nearestFloatBottom(fb);
2108 newLineWidth = lineWidth(fb);
2111 if(!w && m_height < fb && width < newLineWidth) {
2113 width = newLineWidth;
2114 #ifdef DEBUG_LINEBREAKS
2115 kdDebug() << "RenderBlock::findNextLineBreak new position at " << m_height << " newWidth " << width << endl;
2120 if (o->style()->whiteSpace() == NORMAL) {
2121 // In AFTER_WHITE_SPACE mode, consider the current character
2122 // as candidate width for this line.
2123 int charWidth = o->style()->khtmlLineBreak() == AFTER_WHITE_SPACE ? t->width(pos, 1, f) : 0;
2124 if (w + tmpW + charWidth > width) {
2125 if (o->style()->khtmlLineBreak() == AFTER_WHITE_SPACE) {
2126 // Check if line is too big even without the extra space
2127 // at the end of the line. If it is not, do nothing.
2128 // If the line needs the extra whitespace to be too long,
2129 // then move the line break to the space and skip all
2130 // additional whitespace.
2131 if (w + tmpW < width) {
2134 skipWhitespace(lBreak, bidi);
2137 goto end; // Didn't fit. Jump to the end.
2139 else if (pos > 1 && str[pos-1].unicode() == SOFT_HYPHEN)
2140 // Subtract the width of the soft hyphen out since we fit on a line.
2141 tmpW -= t->width(pos-1, 1, f);
2144 if( *(str+pos) == '\n' && isPre) {
2148 #ifdef DEBUG_LINEBREAKS
2149 kdDebug(6041) << "forced break sol: " << start.obj << " " << start.pos << " end: " << lBreak.obj << " " << lBreak.pos << " width=" << w << endl;
2154 if (o->style()->whiteSpace() == NORMAL) {
2163 if (applyWordSpacing)
2166 if (!ignoringSpaces && !isPre) {
2167 // If we encounter a newline, or if we encounter a
2168 // second space, we need to go ahead and break up this
2169 // run and enter a mode where we start collapsing spaces.
2170 if (currentCharacterIsSpace && previousCharacterIsSpace) {
2171 ignoringSpaces = true;
2173 // We just entered a mode where we are ignoring
2174 // spaces. Create a midpoint to terminate the run
2175 // before the second space.
2176 addMidpoint(ignoreStart);
2181 else if (ignoringSpaces) {
2182 // Stop ignoring spaces and begin at this
2184 ignoringSpaces = false;
2185 lastSpace = pos; // e.g., "Foo goo", don't add in any of the ignored spaces.
2186 BidiIterator startMid ( 0, o, pos );
2187 addMidpoint(startMid);
2190 if (currentCharacterIsSpace && !previousCharacterIsSpace) {
2191 ignoreStart.obj = o;
2192 ignoreStart.pos = pos;
2195 if (!currentCharacterIsWS && previousCharacterIsWS) {
2196 if (o->style()->khtmlLineBreak() == AFTER_WHITE_SPACE && o->style()->whiteSpace() == NORMAL) {
2202 if (!isPre && currentCharacterIsSpace && !ignoringSpaces)
2203 trailingSpaceObject = o;
2204 else if (isPre || !currentCharacterIsSpace)
2205 trailingSpaceObject = 0;
2211 // IMPORTANT: pos is > length here!
2212 if (!ignoringSpaces)
2213 tmpW += t->width(lastSpace, pos - lastSpace, f);
2214 if (!appliedStartWidth)
2215 tmpW += inlineWidth(o, true, false);
2216 if (!appliedEndWidth)
2217 tmpW += inlineWidth(o, false, true);
2219 KHTMLAssert( false );
2221 RenderObject* next = Bidinext(start.par, o, bidi);
2222 bool isNormal = o->style()->whiteSpace() == NORMAL;
2223 bool checkForBreak = isNormal;
2224 if (w && w + tmpW > width+1 && lBreak.obj && o->style()->whiteSpace() == NOWRAP)
2225 checkForBreak = true;
2226 else if (next && o->isText() && next->isText() && !next->isBR()) {
2227 if (isNormal || (next->style()->whiteSpace() == NORMAL)) {
2228 if (currentCharacterIsSpace)
2229 checkForBreak = true;
2231 RenderText* nextText = static_cast<RenderText*>(next);
2232 int strlen = nextText->stringLength();
2233 QChar *str = nextText->text();
2235 ((str[0].unicode() == ' ') ||
2236 (next->style()->whiteSpace() != PRE && str[0] == '\n')))
2237 // If the next item on the line is text, and if we did not end with
2238 // a space, then the next text run continues our word (and so it needs to
2239 // keep adding to |tmpW|. Just update and continue.
2240 checkForBreak = true;
2242 checkForBreak = false;
2244 bool canPlaceOnLine = (w + tmpW <= width+1) || !isNormal;
2245 if (canPlaceOnLine && checkForBreak) {
2255 if (checkForBreak && (w + tmpW > width+1)) {
2256 //kdDebug() << " too wide w=" << w << " tmpW = " << tmpW << " width = " << width << endl;
2257 //kdDebug() << "start=" << start.obj << " current=" << o << endl;
2258 // if we have floats, try to get below them.
2259 if (currentCharacterIsSpace && !ignoringSpaces && o->style()->whiteSpace() != PRE)
2260 trailingSpaceObject = 0;
2262 int fb = nearestFloatBottom(m_height);
2263 int newLineWidth = lineWidth(fb);
2264 // See if |tmpW| will fit on the new line. As long as it does not,
2265 // keep adjusting our float bottom until we find some room.
2266 int lastFloatBottom = m_height;
2267 while (lastFloatBottom < fb && tmpW > newLineWidth) {
2268 lastFloatBottom = fb;
2269 fb = nearestFloatBottom(fb);
2270 newLineWidth = lineWidth(fb);
2272 if( !w && m_height < fb && width < newLineWidth ) {
2274 width = newLineWidth;
2275 #ifdef DEBUG_LINEBREAKS
2276 kdDebug() << "RenderBlock::findNextLineBreak new position at " << m_height << " newWidth " << width << endl;
2280 // |width| may have been adjusted because we got shoved down past a float (thus
2281 // giving us more room), so we need to retest, and only jump to
2282 // the end label if we still don't fit on the line. -dwh
2283 if (w + tmpW > width+1)
2290 if (!last->isFloatingOrPositioned() && last->isReplaced() && last->style()->whiteSpace() == NORMAL) {
2291 // Go ahead and add in tmpW.
2298 // Clear out our character space bool, since inline <pre>s don't collapse whitespace
2299 // with adjacent inline normal/nowrap spans.
2300 if (last->style()->whiteSpace() == PRE)
2301 currentCharacterIsSpace = false;
2306 #ifdef DEBUG_LINEBREAKS
2307 kdDebug( 6041 ) << "end of par, width = " << width << " linewidth = " << w + tmpW << endl;
2309 if( w + tmpW <= width || (last && last->style()->whiteSpace() == NOWRAP)) {
2316 if( lBreak == start && !lBreak.obj->isBR() ) {
2317 // we just add as much as possible
2321 lBreak.pos = pos - 1;
2324 lBreak.pos = last->isText() ? last->length() : 0;
2326 } else if( lBreak.obj ) {
2328 // better to break between object boundaries than in the middle of a word
2332 // Don't ever break in the middle of a word if we can help it.
2333 // There's no room at all. We just have to be on this line,
2334 // even though we'll spill out.
2341 // make sure we consume at least one char/object.
2342 if( lBreak == start )
2343 lBreak.increment(bidi);
2345 #ifdef DEBUG_LINEBREAKS
2346 kdDebug(6041) << "regular break sol: " << start.obj << " " << start.pos << " end: " << lBreak.obj << " " << lBreak.pos << " width=" << w << endl;
2349 // Sanity check our midpoints.
2350 checkMidpoints(lBreak, bidi);
2352 if (trailingSpaceObject) {
2353 // This object is either going to be part of the last midpoint, or it is going
2354 // to be the actual endpoint. In both cases we just decrease our pos by 1 level to
2355 // exclude the space, allowing it to - in effect - collapse into the newline.
2356 if (sNumMidpoints%2==1) {
2357 BidiIterator* midpoints = smidpoints->data();
2358 midpoints[sNumMidpoints-1].pos--;
2360 //else if (lBreak.pos > 0)
2362 else if (lBreak.obj == 0 && trailingSpaceObject->isText()) {
2363 // Add a new end midpoint that stops right at the very end.
2364 RenderText* text = static_cast<RenderText *>(trailingSpaceObject);
2365 unsigned pos = text->length() >=2 ? text->length() - 2 : UINT_MAX;
2366 BidiIterator endMid ( 0, trailingSpaceObject, pos );
2367 addMidpoint(endMid);
2371 // We might have made lBreak an iterator that points past the end
2372 // of the object. Do this adjustment to make it point to the start
2373 // of the next object instead to avoid confusing the rest of the
2375 if (lBreak.pos > 0) {
2377 lBreak.increment(bidi);
2380 if (lBreak.obj && lBreak.pos >= 2 && lBreak.obj->isText()) {
2381 // For soft hyphens on line breaks, we have to chop out the midpoints that made us
2382 // ignore the hyphen so that it will render at the end of the line.
2383 QChar c = static_cast<RenderText*>(lBreak.obj)->text()[lBreak.pos-1];
2384 if (c.unicode() == SOFT_HYPHEN)
2385 chopMidpointsAt(lBreak.obj, lBreak.pos-2);
2391 void RenderBlock::checkLinesForOverflow()
2393 // FIXME: Inline blocks can have overflow. Need to understand when those objects are present on a line
2394 // and factor that in somehow.
2395 m_overflowWidth = m_width;
2396 for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
2397 m_overflowLeft = kMin(curr->leftOverflow(), m_overflowLeft);
2398 m_overflowTop = kMin(curr->topOverflow(), m_overflowTop);
2399 m_overflowWidth = kMax(curr->rightOverflow(), m_overflowWidth);
2400 m_overflowHeight = kMax(curr->bottomOverflow(), m_overflowHeight);
2404 void RenderBlock::deleteEllipsisLineBoxes()
2406 for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox())
2407 curr->clearTruncation();
2410 void RenderBlock::checkLinesForTextOverflow()
2412 // Determine the width of the ellipsis using the current font.
2413 QChar ellipsis = 0x2026; // FIXME: CSS3 says this is configurable, also need to use 0x002E (FULL STOP) if 0x2026 not renderable
2414 static AtomicString ellipsisStr(ellipsis);
2415 const Font& firstLineFont = style(true)->htmlFont();
2416 const Font& font = style()->htmlFont();
2417 int firstLineEllipsisWidth = firstLineFont.width(&ellipsis, 1, 0);
2418 int ellipsisWidth = (font == firstLineFont) ? firstLineEllipsisWidth : font.width(&ellipsis, 1, 0);
2420 // For LTR text truncation, we want to get the right edge of our padding box, and then we want to see
2421 // if the right edge of a line box exceeds that. For RTL, we use the left edge of the padding box and
2422 // check the left edge of the line box to see if it is less
2423 // Include the scrollbar for overflow blocks, which means we want to use "contentWidth()"
2424 bool ltr = style()->direction() == LTR;
2425 for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
2426 int blockEdge = ltr ? rightOffset(curr->yPos()) : leftOffset(curr->yPos());
2427 int lineBoxEdge = ltr ? curr->xPos() + curr->width() : curr->xPos();
2428 if ((ltr && lineBoxEdge > blockEdge) || (!ltr && lineBoxEdge < blockEdge)) {
2429 // This line spills out of our box in the appropriate direction. Now we need to see if the line
2430 // can be truncated. In order for truncation to be possible, the line must have sufficient space to
2431 // accommodate our truncation string, and no replaced elements (images, tables) can overlap the ellipsis
2433 int width = curr == firstRootBox() ? firstLineEllipsisWidth : ellipsisWidth;
2434 if (curr->canAccommodateEllipsis(ltr, blockEdge, lineBoxEdge, width))
2435 curr->placeEllipsis(ellipsisStr, ltr, blockEdge, width);
2440 // For --enable-final
2442 #undef DEBUG_LINEBREAKS