2 * This file is part of the DOM implementation for KDE.
4 * Copyright (C) 1997 Martin Jones (mjones@kde.org)
5 * (C) 1997 Torben Weis (weis@kde.org)
6 * (C) 1998 Waldo Bastian (bastian@kde.org)
7 * (C) 1999 Lars Knoll (knoll@kde.org)
8 * (C) 1999 Antti Koivisto (koivisto@kde.org)
9 * Copyright (C) 2003 Apple Computer, Inc.
11 * This library is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Library General Public
13 * License as published by the Free Software Foundation; either
14 * version 2 of the License, or (at your option) any later version.
16 * This library is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Library General Public License for more details.
21 * You should have received a copy of the GNU Library General Public License
22 * along with this library; see the file COPYING.LIB. If not, write to
23 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 * Boston, MA 02111-1307, USA.
29 //#define DEBUG_LAYOUT
31 #include "rendering/render_table.h"
32 #include "rendering/table_layout.h"
33 #include "html/html_tableimpl.h"
34 #include "misc/htmltags.h"
35 #include "misc/htmlattrs.h"
36 #include "xml/dom_docimpl.h"
40 #include <qapplication.h>
46 #include "khtmlview.h"
48 using namespace khtml;
51 RenderTable::RenderTable(DOM::NodeImpl* node)
56 head = foot = firstBody = 0;
62 has_col_elems = false;
66 needSectionRecalc = false;
69 columnPos.resize( 2 );
72 columns.fill( ColumnStruct() );
77 RenderTable::~RenderTable()
82 void RenderTable::setStyle(RenderStyle *_style)
84 ETableLayout oldTableLayout = style() ? style()->tableLayout() : TAUTO;
85 RenderBlock::setStyle(_style);
87 // In the collapsed border model, there is no cell spacing.
88 hspacing = collapseBorders() ? 0 : style()->horizontalBorderSpacing();
89 vspacing = collapseBorders() ? 0 : style()->verticalBorderSpacing();
90 columnPos[0] = hspacing;
92 if ( !tableLayout || style()->tableLayout() != oldTableLayout ) {
95 // According to the CSS2 spec, you only use fixed table layout if an
96 // explicit width is specified on the table. Auto width implies auto table layout.
97 if (style()->tableLayout() == TFIXED && !style()->width().isVariable()) {
98 tableLayout = new FixedTableLayout(this);
100 kdDebug( 6040 ) << "using fixed table layout" << endl;
103 tableLayout = new AutoTableLayout(this);
107 void RenderTable::addChild(RenderObject *child, RenderObject *beforeChild)
110 kdDebug( 6040 ) << renderName() << "(Table)::addChild( " << child->renderName() << ", " <<
111 (beforeChild ? beforeChild->renderName() : "0") << " )" << endl;
113 RenderObject *o = child;
115 if (child->element() && child->element()->id() == ID_FORM) {
116 RenderContainer::addChild(child,beforeChild);
120 switch(child->style()->display())
123 tCaption = static_cast<RenderBlock *>(child);
126 case TABLE_COLUMN_GROUP:
127 has_col_elems = true;
129 case TABLE_HEADER_GROUP:
131 head = static_cast<RenderTableSection *>(child);
132 else if ( !firstBody )
133 firstBody = static_cast<RenderTableSection *>(child);
135 case TABLE_FOOTER_GROUP:
137 foot = static_cast<RenderTableSection *>(child);
141 case TABLE_ROW_GROUP:
143 firstBody = static_cast<RenderTableSection *>(child);
146 if ( !beforeChild && lastChild() &&
147 lastChild()->isTableSection() && lastChild()->isAnonymous() ) {
150 RenderObject *lastBox = beforeChild;
151 while ( lastBox && lastBox->parent()->isAnonymous() &&
152 !lastBox->isTableSection() && lastBox->style()->display() != TABLE_CAPTION )
153 lastBox = lastBox->parent();
154 if ( lastBox && lastBox->isAnonymous() ) {
155 lastBox->addChild( child, beforeChild );
158 if ( beforeChild && !beforeChild->isTableSection() )
160 //kdDebug( 6040 ) << this <<" creating anonymous table section beforeChild="<< beforeChild << endl;
161 o = new (renderArena()) RenderTableSection(document() /* anonymous */);
162 RenderStyle *newStyle = new (renderArena()) RenderStyle();
163 newStyle->inheritFrom(style());
164 newStyle->setDisplay(TABLE_ROW_GROUP);
165 o->setStyle(newStyle);
166 addChild(o, beforeChild);
170 child->setNeedsLayoutAndMinMaxRecalc();
173 RenderContainer::addChild(child,beforeChild);
178 void RenderTable::calcWidth()
180 if ( isPositioned() ) {
181 calcAbsoluteHorizontal();
184 RenderBlock *cb = containingBlock();
185 int availableWidth = cb->contentWidth();
187 LengthType widthType = style()->width().type;
188 if (widthType > Relative && style()->width().value > 0) {
189 // Percent or fixed table
190 m_width = style()->width().minWidth( availableWidth );
191 if(m_minWidth > m_width) m_width = m_minWidth;
194 // An auto width table should shrink to fit within the line width if necessary in order to
195 // avoid overlapping floats.
196 availableWidth = cb->lineWidth( m_y );
198 // Subtract out any fixed margins from our available width for auto width tables.
200 if (style()->marginLeft().type != Variable)
201 marginTotal += style()->marginLeft().width(availableWidth);
202 if (style()->marginRight().type != Variable)
203 marginTotal += style()->marginRight().width(availableWidth);
205 // Subtract out our margins to get the available content width.
206 int availContentWidth = kMax(0, availableWidth - marginTotal);
208 // Ensure we aren't bigger than our max width or smaller than our min width.
209 m_width = kMin(availContentWidth, m_maxWidth);
212 m_width = kMax(m_width, m_minWidth);
214 // Finally, with our true width determined, compute our margins for real.
217 calcHorizontalMargins(style()->marginLeft(),style()->marginRight(),availableWidth);
220 void RenderTable::layout()
222 KHTMLAssert( needsLayout() );
223 KHTMLAssert( minMaxKnown() );
224 KHTMLAssert( !needSectionRecalc );
226 if (posChildNeedsLayout() && !normalChildNeedsLayout() && !selfNeedsLayout()) {
227 // All we have to is lay out our positioned objects.
228 layoutPositionedObjects(true);
229 setNeedsLayout(false);
233 QRect oldBounds, oldFullBounds;
234 bool checkForRepaint = checkForRepaintDuringLayout();
236 getAbsoluteRepaintRectIncludingFloats(oldBounds, oldFullBounds);
238 //kdDebug( 6040 ) << renderName() << "(Table)"<< this << " ::layout0() width=" << width() << ", needsLayout=" << needsLayout() << endl;
241 initMaxMarginValues();
243 //int oldWidth = m_width;
246 // the optimisation below doesn't work since the internal table
247 // layout could have changed. we need to add a flag to the table
248 // layout that tells us if something has changed in the min max
249 // calculations to do it correctly.
250 // if ( oldWidth != m_width || columns.size() + 1 != columnPos.size() )
251 tableLayout->layout();
254 kdDebug( 6040 ) << renderName() << "(Table)::layout1() width=" << width() << ", marginLeft=" << marginLeft() << " marginRight=" << marginRight() << endl;
259 // layout child objects
260 int calculatedHeight = 0;
262 RenderObject *child = firstChild();
264 if ( child->needsLayout() && !(child->element() && child->element()->id() == ID_FORM))
266 if ( child->isTableSection() ) {
267 static_cast<RenderTableSection *>(child)->calcRowHeight();
268 calculatedHeight += static_cast<RenderTableSection *>(child)->layoutRows( 0 );
270 child = child->nextSibling();
273 // ### collapse caption margin
274 if(tCaption && tCaption->style()->captionSide() != CAPBOTTOM) {
275 tCaption->setPos(tCaption->marginLeft(), m_height);
276 m_height += tCaption->height() + tCaption->marginTop() + tCaption->marginBottom();
279 int bpTop = borderTop() + (collapseBorders() ? 0 : paddingTop());
280 int bpBottom = borderBottom() + (collapseBorders() ? 0 : paddingBottom());
284 int oldHeight = m_height;
286 int newHeight = m_height;
287 m_height = oldHeight;
289 Length h = style()->height();
292 th = newHeight; // FIXME: Leave this alone for now but investigate later.
293 else if (h.isFixed())
294 th = h.value - (bpTop + bpBottom); // Tables size as though CSS height includes border/padding.
295 else if (h.isPercent())
296 th = calcPercentageHeight(h);
300 if ( th > calculatedHeight ) {
301 // we have to redistribute that height to get the constraint correctly
302 // just force the first body to the height needed
303 // ### FIXME This should take height constraints on all table sections into account and distribute
304 // accordingly. For now this should be good enough
306 firstBody->calcRowHeight();
307 firstBody->layoutRows( th - calculatedHeight );
311 int bl = borderLeft();
312 if (!collapseBorders())
315 // position the table sections
317 head->setPos(bl, m_height);
318 m_height += head->height();
320 RenderObject *body = firstBody;
322 if ( body != head && body != foot && body->isTableSection() ) {
323 body->setPos(bl, m_height);
324 m_height += body->height();
326 body = body->nextSibling();
329 foot->setPos(bl, m_height);
330 m_height += foot->height();
333 m_height += bpBottom;
335 if(tCaption && tCaption->style()->captionSide()==CAPBOTTOM) {
336 tCaption->setPos(tCaption->marginLeft(), m_height);
337 m_height += tCaption->height() + tCaption->marginTop() + tCaption->marginBottom();
340 //kdDebug(0) << "table height: " << m_height << endl;
342 // table can be containing block of positioned elements.
343 // ### only pass true if width or height changed.
344 layoutPositionedObjects( true );
346 // Repaint with our new bounds if they are different from our old bounds.
348 repaintAfterLayoutIfNeeded(oldBounds, oldFullBounds);
350 m_overflowHeight = kMax(m_overflowHeight, m_height);
351 m_overflowWidth = kMax(m_overflowWidth, m_width);
353 setNeedsLayout(false);
356 void RenderTable::setCellWidths()
359 kdDebug( 6040 ) << renderName() << "(Table, this=0x" << this << ")::setCellWidths()" << endl;
362 RenderObject *child = firstChild();
364 if ( child->isTableSection() )
365 static_cast<RenderTableSection *>(child)->setCellWidths();
366 child = child->nextSibling();
370 void RenderTable::paint(PaintInfo& i, int _tx, int _ty)
375 PaintAction paintAction = i.phase;
378 kdDebug( 6040 ) << "RenderTable::paint() w/h = (" << width() << "/" << height() << ")" << endl;
381 int os = 2*maximalOutlineSize(paintAction);
382 if ((_ty >= i.r.y() + i.r.height() + os) || (_ty + height() <= i.r.y() - os)) return;
383 if ((_tx >= i.r.x() + i.r.width() + os) || (_tx + width() <= i.r.x() - os)) return;
386 kdDebug( 6040 ) << "RenderTable::paint(2) " << _tx << "/" << _ty << " (" << _y << "/" << _h << ")" << endl;
389 if ((paintAction == PaintActionBlockBackground || paintAction == PaintActionChildBlockBackground)
390 && shouldPaintBackgroundOrBorder() && style()->visibility() == VISIBLE)
391 paintBoxDecorations(i, _tx, _ty);
393 // We're done. We don't bother painting any children.
394 if (paintAction == PaintActionBlockBackground)
396 // We don't paint our own background, but we do let the kids paint their backgrounds.
397 if (paintAction == PaintActionChildBlockBackgrounds)
398 paintAction = PaintActionChildBlockBackground;
399 PaintInfo paintInfo(i.p, i.r, paintAction, paintingRootForChildren(i));
401 for (RenderObject *child = firstChild(); child; child = child->nextSibling())
402 if (child->isTableSection() || child == tCaption)
403 child->paint(paintInfo, _tx, _ty);
405 if (collapseBorders() && paintAction == PaintActionChildBlockBackground && style()->visibility() == VISIBLE) {
406 // Collect all the unique border styles that we want to paint in a sorted list. Once we
407 // have all the styles sorted, we then do individual passes, painting each style of border
408 // from lowest precedence to highest precedence.
409 paintInfo.phase = PaintActionCollapsedTableBorders;
410 QValueList<CollapsedBorderValue> borderStyles;
411 collectBorders(borderStyles);
412 QValueListIterator<CollapsedBorderValue> it = borderStyles.begin();
413 QValueListIterator<CollapsedBorderValue> end = borderStyles.end();
414 for (; it != end; ++it) {
415 m_currentBorder = &(*it);
416 for (RenderObject* child = firstChild(); child; child = child->nextSibling())
417 if (child->isTableSection())
418 child->paint(paintInfo, _tx, _ty);
423 outlineBox(i.p, _tx, _ty, "blue");
427 void RenderTable::paintBoxDecorations(PaintInfo& i, int _tx, int _ty)
432 // Account for the caption.
434 int captionHeight = (tCaption->height() + tCaption->marginBottom() + tCaption->marginTop());
436 if (tCaption->style()->captionSide() != CAPBOTTOM)
437 _ty += captionHeight;
440 int my = kMax(_ty, i.r.y());
443 mh= kMax(0, h - (i.r.y() - _ty));
445 mh = kMin(i.r.height(), h);
447 paintBackground(i.p, style()->backgroundColor(), style()->backgroundLayers(), my, mh, _tx, _ty, w, h);
449 if (style()->hasBorder() && !collapseBorders())
450 paintBorder(i.p, _tx, _ty, w, h, style());
453 void RenderTable::calcMinMaxWidth()
455 KHTMLAssert( !minMaxKnown() );
457 if ( needSectionRecalc )
461 kdDebug( 6040 ) << renderName() << "(Table " << this << ")::calcMinMaxWidth()" << endl;
464 tableLayout->calcMinMaxWidth();
466 if (tCaption && tCaption->minWidth() > m_minWidth)
467 m_minWidth = tCaption->minWidth();
471 kdDebug( 6040 ) << renderName() << " END: (Table " << this << ")::calcMinMaxWidth() min = " << m_minWidth << " max = " << m_maxWidth << endl;
475 void RenderTable::splitColumn( int pos, int firstSpan )
477 // we need to add a new columnStruct
478 int oldSize = columns.size();
479 columns.resize( oldSize + 1 );
480 int oldSpan = columns[pos].span;
481 // qDebug("splitColumn( %d,%d ), oldSize=%d, oldSpan=%d", pos, firstSpan, oldSize, oldSpan );
482 KHTMLAssert( oldSpan > firstSpan );
483 columns[pos].span = firstSpan;
484 memmove( columns.data()+pos+1, columns.data()+pos, (oldSize-pos)*sizeof(ColumnStruct) );
485 columns[pos+1].span = oldSpan - firstSpan;
487 // change width of all rows.
488 RenderObject *child = firstChild();
490 if ( child->isTableSection() ) {
491 RenderTableSection *section = static_cast<RenderTableSection *>(child);
492 int size = section->numRows();
494 if ( section->cCol > pos )
496 while ( row < size ) {
497 section->grid[row].row->resize( oldSize+1 );
498 RenderTableSection::Row &r = *section->grid[row].row;
499 memmove( r.data()+pos+1, r.data()+pos, (oldSize-pos)*sizeof( RenderTableCell * ) );
500 // qDebug("moving from %d to %d, num=%d", pos, pos+1, (oldSize-pos-1) );
501 r[pos+1] = r[pos] ? (RenderTableCell *)-1 : 0;
505 child = child->nextSibling();
507 columnPos.resize( numEffCols()+1 );
508 setNeedsLayoutAndMinMaxRecalc();
511 void RenderTable::appendColumn( int span )
514 int pos = columns.size();
515 // qDebug("appendColumn( %d ), size=%d", span, pos );
516 int newSize = pos + 1;
517 columns.resize( newSize );
518 columns[pos].span = span;
519 //qDebug("appending column at %d, span %d", pos, span );
521 // change width of all rows.
522 RenderObject *child = firstChild();
524 if ( child->isTableSection() ) {
525 RenderTableSection *section = static_cast<RenderTableSection *>(child);
526 int size = section->numRows();
528 while ( row < size ) {
529 section->grid[row].row->resize( newSize );
530 section->cellAt( row, pos ) = 0;
535 child = child->nextSibling();
537 columnPos.resize( numEffCols()+1 );
538 setNeedsLayoutAndMinMaxRecalc();
541 RenderTableCol *RenderTable::colElement( int col ) {
542 if ( !has_col_elems )
544 RenderObject *child = firstChild();
547 if ( child->isTableCol() ) {
548 RenderTableCol *colElem = static_cast<RenderTableCol *>(child);
549 int span = colElem->span();
550 if ( !colElem->firstChild() ) {
556 RenderObject *next = child->firstChild();
558 next = child->nextSibling();
559 if ( !next && child->parent()->isTableCol() )
560 next = child->parent()->nextSibling();
568 void RenderTable::recalcSections()
571 head = foot = firstBody = 0;
572 has_col_elems = false;
574 RenderObject *child = firstChild();
575 // We need to get valid pointers to caption, head, foot and firstbody again
577 switch (child->style()->display()) {
580 tCaption = static_cast<RenderBlock*>(child);
581 tCaption->setNeedsLayout(true);
585 case TABLE_COLUMN_GROUP:
586 has_col_elems = true;
588 case TABLE_HEADER_GROUP: {
589 RenderTableSection *section = static_cast<RenderTableSection *>(child);
592 else if ( !firstBody )
594 if ( section->needCellRecalc )
595 section->recalcCells();
598 case TABLE_FOOTER_GROUP: {
599 RenderTableSection *section = static_cast<RenderTableSection *>(child);
602 else if ( !firstBody )
604 if ( section->needCellRecalc )
605 section->recalcCells();
608 case TABLE_ROW_GROUP: {
609 RenderTableSection *section = static_cast<RenderTableSection *>(child);
612 if ( section->needCellRecalc )
613 section->recalcCells();
618 child = child->nextSibling();
620 needSectionRecalc = false;
621 setNeedsLayout(true);
624 RenderObject* RenderTable::removeChildNode(RenderObject* child)
626 setNeedSectionRecalc();
627 return RenderContainer::removeChildNode( child );
630 int RenderTable::borderLeft() const
632 if (collapseBorders()) {
633 // FIXME: For strict mode, returning 0 is correct, since the table border half spills into the margin,
634 // but I'm working to get this changed. For now, follow the spec.
637 return RenderBlock::borderLeft();
640 int RenderTable::borderRight() const
642 if (collapseBorders()) {
643 // FIXME: For strict mode, returning 0 is correct, since the table border half spills into the margin,
644 // but I'm working to get this changed. For now, follow the spec.
647 return RenderBlock::borderRight();
650 int RenderTable::borderTop() const
652 if (collapseBorders()) {
653 // FIXME: For strict mode, returning 0 is correct, since the table border half spills into the margin,
654 // but I'm working to get this changed. For now, follow the spec.
657 return RenderBlock::borderTop();
660 int RenderTable::borderBottom() const
662 if (collapseBorders()) {
663 // FIXME: For strict mode, returning 0 is correct, since the table border half spills into the margin,
664 // but I'm working to get this changed. For now, follow the spec.
667 return RenderBlock::borderBottom();
670 RenderTableCell* RenderTable::cellAbove(const RenderTableCell* cell) const
672 // Find the section and row to look in
674 RenderTableSection* section = 0;
677 // cell is not in the first row, so use the above row in its own section
678 section = cell->section();
681 // cell is at top of a section, use last row in previous section
682 for (RenderObject *prevSection = cell->section()->previousSibling();
683 prevSection && rAbove < 0;
684 prevSection = prevSection->previousSibling()) {
685 if (prevSection->isTableSection()) {
686 section = static_cast<RenderTableSection *>(prevSection);
687 if (section->numRows() > 0)
688 rAbove = section->numRows()-1;
693 // Look up the cell in the section's grid, which requires effective col index
694 if (section && rAbove >= 0) {
695 int effCol = colToEffCol(cell->col());
696 RenderTableCell* aboveCell;
697 // If we hit a span back up to a real cell.
699 aboveCell = section->cellAt(rAbove, effCol);
701 } while (aboveCell == (RenderTableCell *)-1 && effCol >=0);
702 return (aboveCell == (RenderTableCell *)-1) ? 0 : aboveCell;
708 RenderTableCell* RenderTable::cellBelow(const RenderTableCell* cell) const
710 // Find the section and row to look in
711 int r = cell->row() + cell->rowSpan() - 1;
712 RenderTableSection* section = 0;
714 if (r < cell->section()->numRows()-1) {
715 // The cell is not in the last row, so use the next row in the section.
716 section = cell->section();
719 // The cell is at the bottom of a section. Use the first row in the next section.
720 for (RenderObject* nextSection = cell->section()->nextSibling();
721 nextSection && rBelow < 0;
722 nextSection = nextSection->nextSibling())
724 if (nextSection->isTableSection()) {
725 section = static_cast<RenderTableSection *>(nextSection);
726 if (section->numRows() > 0)
732 // Look up the cell in the section's grid, which requires effective col index
733 if (section && rBelow >= 0) {
734 int effCol = colToEffCol(cell->col());
735 RenderTableCell* belowCell;
736 // If we hit a colspan back up to a real cell.
738 belowCell = section->cellAt(rBelow, effCol);
740 } while (belowCell == (RenderTableCell *)-1 && effCol >=0);
741 return (belowCell == (RenderTableCell *)-1) ? 0 : belowCell;
747 RenderTableCell* RenderTable::cellLeft(const RenderTableCell* cell) const
749 RenderTableSection* section = cell->section();
750 int effCol = colToEffCol(cell->col());
754 // If we hit a colspan back up to a real cell.
755 RenderTableCell* prevCell;
757 prevCell = section->cellAt(cell->row(), effCol-1);
759 } while (prevCell == (RenderTableCell *)-1 && effCol >=0);
760 return (prevCell == (RenderTableCell *)-1) ? 0 : prevCell;
763 RenderTableCell* RenderTable::cellRight(const RenderTableCell* cell) const
765 int effCol = colToEffCol(cell->col()+cell->colSpan());
766 if (effCol >= numEffCols())
768 RenderTableCell* result = cell->section()->cellAt(cell->row(), effCol);
769 return (result == (RenderTableCell*)-1) ? 0 : result;
772 RenderBlock* RenderTable::firstLineBlock() const
777 void RenderTable::updateFirstLetter()
781 void RenderTable::dump(QTextStream *stream, QString ind) const
784 *stream << " tCaption";
790 *stream << endl << ind << "cspans:";
791 for ( unsigned int i = 0; i < columns.size(); i++ )
792 *stream << " " << columns[i].span;
793 *stream << endl << ind;
795 RenderBlock::dump(stream,ind);
799 // --------------------------------------------------------------------------
801 RenderTableSection::RenderTableSection(DOM::NodeImpl* node)
802 : RenderContainer(node)
804 // init RenderObject attributes
805 setInline(false); // our object is not Inline
809 needCellRecalc = false;
812 RenderTableSection::~RenderTableSection()
817 void RenderTableSection::detach()
819 // recalc cell info because RenderTable has unguarded pointers
820 // stored that point to this RenderTableSection.
822 table()->setNeedSectionRecalc();
824 RenderContainer::detach();
827 void RenderTableSection::setStyle(RenderStyle* _style)
829 // we don't allow changing this one
831 _style->setDisplay(style()->display());
832 else if (_style->display() != TABLE_FOOTER_GROUP && _style->display() != TABLE_HEADER_GROUP)
833 _style->setDisplay(TABLE_ROW_GROUP);
835 RenderContainer::setStyle(_style);
838 void RenderTableSection::addChild(RenderObject *child, RenderObject *beforeChild)
841 kdDebug( 6040 ) << renderName() << "(TableSection)::addChild( " << child->renderName() << ", beforeChild=" <<
842 (beforeChild ? beforeChild->renderName() : "0") << " )" << endl;
844 RenderObject *row = child;
846 if (child->element() && child->element()->id() == ID_FORM) {
847 RenderContainer::addChild(child,beforeChild);
851 if ( !child->isTableRow() ) {
854 beforeChild = lastChild();
856 if( beforeChild && beforeChild->isAnonymous() )
859 RenderObject *lastBox = beforeChild;
860 while ( lastBox && lastBox->parent()->isAnonymous() && !lastBox->isTableRow() )
861 lastBox = lastBox->parent();
862 if ( lastBox && lastBox->isAnonymous() ) {
863 lastBox->addChild( child, beforeChild );
866 //kdDebug( 6040 ) << "creating anonymous table row" << endl;
867 row = new (renderArena()) RenderTableRow(document() /* anonymous table */);
868 RenderStyle *newStyle = new (renderArena()) RenderStyle();
869 newStyle->inheritFrom(style());
870 newStyle->setDisplay( TABLE_ROW );
871 row->setStyle(newStyle);
872 addChild(row, beforeChild);
875 row->addChild(child);
876 child->setNeedsLayoutAndMinMaxRecalc();
886 ensureRows( cRow+1 );
889 grid[cRow].height = child->style()->height();
890 if ( grid[cRow].height.type == Relative )
891 grid[cRow].height = Length();
895 RenderContainer::addChild(child,beforeChild);
898 void RenderTableSection::ensureRows(int numRows)
900 int nRows = gridRows;
901 if (numRows > nRows) {
902 if (numRows > static_cast<int>(grid.size()))
903 grid.resize(numRows*2+1);
906 int nCols = table()->numEffCols();
907 for (int r = nRows; r < numRows; r++ ) {
908 grid[r].row = new Row(nCols);
909 grid[r].row->fill(0);
910 grid[r].baseLine = 0;
911 grid[r].height = Length();
917 void RenderTableSection::addCell( RenderTableCell *cell )
919 int rSpan = cell->rowSpan();
920 int cSpan = cell->colSpan();
921 QMemArray<RenderTable::ColumnStruct> &columns = table()->columns;
922 int nCols = columns.size();
924 // ### mozilla still seems to do the old HTML way, even for strict DTD
925 // (see the annotation on table cell layouting in the CSS specs and the testcase below:
927 // <TR><TD>1 <TD rowspan="2">2 <TD>3 <TD>4
928 // <TR><TD colspan="2">5
931 // find empty space for the cell
935 while ( cCol < nCols && cellAt( cRow, cCol ) )
939 while ( pos < nCols && span < cSpan ) {
940 if ( cellAt( cRow, pos ) ) {
945 span += columns[pos].span;
950 while ( cCol < nCols && cellAt( cRow, cCol ) )
954 // qDebug("adding cell at %d/%d span=(%d/%d)", cRow, cCol, rSpan, cSpan );
957 // we ignore height settings on rowspan cells
958 Length height = cell->style()->height();
959 if ( height.value > 0 || (height.type == Relative && height.value >= 0) ) {
960 Length cRowHeight = grid[cRow].height;
961 switch( height.type ) {
963 if ( !(cRowHeight.type == Percent) ||
964 ( cRowHeight.type == Percent && cRowHeight.value < height.value ) )
965 grid[cRow].height = height;
968 if ( cRowHeight.type < Percent ||
969 ( cRowHeight.type == Fixed && cRowHeight.value < height.value ) )
970 grid[cRow].height = height;
974 // we treat this as variable. This is correct according to HTML4, as it only specifies length for the height.
975 if ( cRowHeight.type == Variable ||
976 ( cRowHeight.type == Relative && cRowHeight.value < height.value ) )
977 grid[cRow].height = height;
986 // make sure we have enough rows
987 ensureRows( cRow + rSpan );
990 // tell the cell where it is
991 RenderTableCell *set = cell;
994 if ( cCol >= nCols ) {
995 table()->appendColumn( cSpan );
998 if ( cSpan < columns[cCol].span )
999 table()->splitColumn( cCol, cSpan );
1000 currentSpan = columns[cCol].span;
1003 while ( r < rSpan ) {
1004 if ( !cellAt( cRow + r, cCol ) ) {
1005 // qDebug(" adding cell at %d, %d", cRow + r, cCol );
1006 cellAt( cRow + r, cCol ) = set;
1011 cSpan -= currentSpan;
1012 set = (RenderTableCell *)-1;
1015 cell->setRow( cRow );
1016 cell->setCol( table()->effColToCol( col ) );
1022 void RenderTableSection::setCellWidths()
1025 kdDebug( 6040 ) << renderName() << "(Table, this=0x" << this << ")::setCellWidths()" << endl;
1027 QMemArray<int> &columnPos = table()->columnPos;
1029 int rows = gridRows;
1030 for ( int i = 0; i < rows; i++ ) {
1031 Row &row = *grid[i].row;
1032 int cols = row.size();
1033 for ( int j = 0; j < cols; j++ ) {
1034 RenderTableCell *cell = row[j];
1035 // qDebug("cell[%d,%d] = %p", i, j, cell );
1036 if ( !cell || cell == (RenderTableCell *)-1 )
1039 int cspan = cell->colSpan();
1040 while ( cspan && endCol < cols ) {
1041 cspan -= table()->columns[endCol].span;
1044 int w = columnPos[endCol] - columnPos[j] - table()->hBorderSpacing();
1046 kdDebug( 6040 ) << "setting width of cell " << cell << " " << cell->row() << "/" << cell->col() << " to " << w << " colspan=" << cell->colSpan() << " start=" << j << " end=" << endCol << endl;
1048 int oldWidth = cell->width();
1049 if ( w != oldWidth ) {
1050 cell->setNeedsLayout(true);
1051 cell->setWidth( w );
1058 void RenderTableSection::calcRowHeight()
1061 RenderTableCell *cell;
1063 int totalRows = gridRows;
1064 int spacing = table()->vBorderSpacing();
1066 rowPos.resize( totalRows + 1 );
1067 rowPos[0] = spacing;
1069 for ( int r = 0; r < totalRows; r++ ) {
1074 // qDebug("height of row %d is %d/%d", r, grid[r].height.value, grid[r].height.type );
1075 int ch = grid[r].height.minWidth( 0 );
1076 int pos = rowPos[ r+1 ] + ch + spacing;
1078 if ( pos > rowPos[r+1] )
1081 Row *row = grid[r].row;
1082 int totalCols = row->size();
1083 int totalRows = gridRows;
1085 for ( int c = 0; c < totalCols; c++ ) {
1086 cell = cellAt(r, c);
1087 if ( !cell || cell == (RenderTableCell *)-1 )
1089 if ( r < totalRows - 1 && cellAt(r+1, c) == cell )
1092 if ( ( indx = r - cell->rowSpan() + 1 ) < 0 )
1095 if (cell->overrideSize() != -1) {
1096 cell->setOverrideSize(-1);
1097 cell->setChildNeedsLayout(true, false);
1098 cell->layoutIfNeeded();
1101 // Explicit heights use the border box in quirks mode. In strict mode do the right
1102 // thing and actually add in the border and padding.
1103 ch = cell->style()->height().width(0) +
1104 (cell->style()->htmlHacks() ? 0 : (cell->paddingTop() + cell->paddingBottom() +
1105 cell->borderTop() + cell->borderBottom()));
1106 if (cell->height() > ch)
1107 ch = cell->height();
1109 pos = rowPos[ indx ] + ch + spacing;
1111 if ( pos > rowPos[r+1] )
1114 // find out the baseline
1115 EVerticalAlign va = cell->style()->verticalAlign();
1116 if (va == BASELINE || va == TEXT_BOTTOM || va == TEXT_TOP
1117 || va == SUPER || va == SUB)
1119 int b=cell->baselinePosition();
1124 int td = rowPos[ indx ] + ch - b;
1130 //do we have baseline aligned elements?
1132 // increase rowheight if baseline requires
1133 int bRowPos = baseline + bdesc + spacing ; // + 2*padding
1134 if (rowPos[r+1]<bRowPos)
1135 rowPos[r+1]=bRowPos;
1137 grid[r].baseLine = baseline;
1140 if ( rowPos[r+1] < rowPos[r] )
1141 rowPos[r+1] = rowPos[r];
1142 // qDebug("rowpos(%d)=%d", r, rowPos[r] );
1146 int RenderTableSection::layoutRows( int toAdd )
1150 int totalRows = gridRows;
1151 int hspacing = table()->hBorderSpacing();
1152 int vspacing = table()->vBorderSpacing();
1154 if (toAdd && totalRows && (rowPos[totalRows] || !nextSibling())) {
1156 int totalHeight = rowPos[totalRows] + toAdd;
1157 // qDebug("layoutRows: totalHeight = %d", totalHeight );
1160 int totalPercent = 0;
1161 int numVariable = 0;
1162 for ( int r = 0; r < totalRows; r++ ) {
1163 if ( grid[r].height.type == Variable )
1165 else if ( grid[r].height.type == Percent )
1166 totalPercent += grid[r].height.value;
1168 if ( totalPercent ) {
1169 // qDebug("distributing %d over percent rows totalPercent=%d", dh, totalPercent );
1170 // try to satisfy percent
1172 if ( totalPercent > 100 )
1174 int rh = rowPos[1]-rowPos[0];
1175 for ( int r = 0; r < totalRows; r++ ) {
1176 if ( totalPercent > 0 && grid[r].height.type == Percent ) {
1177 int toAdd = kMin(dh, (totalHeight * grid[r].height.value / 100)-rh);
1178 // If toAdd is negative, then we don't want to shrink the row (this bug
1179 // affected Outlook Web Access).
1180 toAdd = QMAX(0, toAdd);
1183 totalPercent -= grid[r].height.value;
1184 // qDebug( "adding %d to row %d", toAdd, r );
1186 if ( r < totalRows-1 )
1187 rh = rowPos[r+2] - rowPos[r+1];
1191 if ( numVariable ) {
1192 // distribute over variable cols
1193 // qDebug("distributing %d over variable rows numVariable=%d", dh, numVariable );
1195 for ( int r = 0; r < totalRows; r++ ) {
1196 if ( numVariable > 0 && grid[r].height.type == Variable ) {
1197 int toAdd = dh/numVariable;
1205 if (dh>0 && rowPos[totalRows]) {
1206 // if some left overs, distribute equally.
1207 int tot=rowPos[totalRows];
1210 for ( int r = 0; r < totalRows; r++ ) {
1211 //weight with the original height
1212 add+=dh*(rowPos[r+1]-prev)/tot;
1219 int leftOffset = hspacing;
1221 int nEffCols = table()->numEffCols();
1222 for ( int r = 0; r < totalRows; r++ )
1224 Row *row = grid[r].row;
1225 int totalCols = row->size();
1226 for ( int c = 0; c < nEffCols; c++ )
1228 RenderTableCell *cell = cellAt(r, c);
1229 if (!cell || cell == (RenderTableCell *)-1 )
1231 if ( r < totalRows - 1 && cell == cellAt(r+1, c) )
1234 if ( ( rindx = r-cell->rowSpan()+1 ) < 0 )
1237 rHeight = rowPos[r+1] - rowPos[rindx] - vspacing;
1239 // Force percent height children to lay themselves out again.
1240 // This will cause these children to grow to fill the cell.
1241 // FIXME: There is still more work to do here to fully match WinIE (should
1242 // it become necessary to do so). In quirks mode, WinIE behaves like we
1243 // do, but it will clip the cells that spill out of the table section. In
1244 // strict mode, Mozilla and WinIE both regrow the table to accommodate the
1245 // new height of the cell (thus letting the percentages cause growth one
1246 // time only). We may also not be handling row-spanning cells correctly.
1248 // Note also the oddity where replaced elements always flex, and yet blocks/tables do
1249 // not necessarily flex. WinIE is crazy and inconsistent, and we can't hope to
1250 // match the behavior perfectly, but we'll continue to refine it as we discover new
1252 bool cellChildrenFlex = false;
1253 bool flexAllChildren = cell->style()->height().isFixed() ||
1254 (!table()->style()->height().isVariable() && rHeight != cell->height());
1255 RenderObject* o = cell->firstChild();
1257 if (!o->isText() && o->style()->height().isPercent() && (o->isReplaced() || flexAllChildren)) {
1258 // Tables with no sections do not flex.
1259 if (!o->isTable() || static_cast<RenderTable*>(o)->hasSections()) {
1260 o->setNeedsLayout(true, false);
1261 cell->setChildNeedsLayout(true, false);
1262 cellChildrenFlex = true;
1265 o = o->nextSibling();
1267 if (cellChildrenFlex) {
1268 cell->setOverrideSize(kMax(0,
1269 rHeight - cell->borderTop() - cell->paddingTop() -
1270 cell->borderBottom() - cell->paddingBottom()));
1271 cell->layoutIfNeeded();
1273 // Alignment within a cell is based off the calculated
1274 // height, which becomes irrelevant once the cell has
1275 // been resized based off its percentage. -dwh
1276 cell->setCellTopExtra(0);
1277 cell->setCellBottomExtra(0);
1281 kdDebug( 6040 ) << "setting position " << r << "/" << c << ": "
1282 << table()->columnPos[c] /*+ padding */ << "/" << rowPos[rindx] << " height=" << rHeight<< endl;
1285 EVerticalAlign va = cell->style()->verticalAlign();
1294 te = getBaseline(r) - cell->baselinePosition() ;
1300 te = (rHeight - cell->height())/2;
1303 te = rHeight - cell->height();
1309 // kdDebug( 6040 ) << "CELL " << cell << " te=" << te << ", be=" << rHeight - cell->height() - te << ", rHeight=" << rHeight << ", valign=" << va << endl;
1311 cell->setCellTopExtra( te );
1312 cell->setCellBottomExtra( rHeight - cell->height() - te);
1315 int oldCellX = cell->xPos();
1316 int oldCellY = cell->yPos();
1318 if (style()->direction()==RTL) {
1320 table()->columnPos[(int)totalCols] -
1321 table()->columnPos[table()->colToEffCol(cell->col()+cell->colSpan())] +
1325 cell->setPos( table()->columnPos[c] + leftOffset, rowPos[rindx] );
1328 // If the cell moved, we have to repaint it as well as any floating/positioned
1329 // descendants. An exception is if we need a layout. In this case, we know we're going to
1330 // repaint ourselves (and the cell) anyway.
1331 if (!table()->selfNeedsLayout() && cell->checkForRepaintDuringLayout())
1332 cell->repaintDuringLayoutIfMoved(oldCellX, oldCellY);
1336 m_height = rowPos[totalRows];
1341 void RenderTableSection::paint(PaintInfo& i, int tx, int ty)
1343 unsigned int totalRows = gridRows;
1344 unsigned int totalCols = table()->columns.size();
1349 // check which rows and cols are visible and only paint these
1350 // ### fixme: could use a binary search here
1351 PaintAction paintAction = i.phase;
1352 int x = i.r.x(); int y = i.r.y(); int w = i.r.width(); int h = i.r.height();
1354 int os = 2*maximalOutlineSize(paintAction);
1355 unsigned int startrow = 0;
1356 unsigned int endrow = totalRows;
1357 for ( ; startrow < totalRows; startrow++ ) {
1358 if ( ty + rowPos[startrow+1] >= y - os)
1361 for ( ; endrow > 0; endrow-- ) {
1362 if ( ty + rowPos[endrow-1] <= y + h + os)
1365 unsigned int startcol = 0;
1366 unsigned int endcol = totalCols;
1367 if ( style()->direction() == LTR ) {
1368 for ( ; startcol < totalCols; startcol++ ) {
1369 if ( tx + table()->columnPos[startcol+1] >= x - os)
1372 for ( ; endcol > 0; endcol-- ) {
1373 if ( tx + table()->columnPos[endcol-1] <= x + w + os)
1378 if ( startcol < endcol ) {
1380 for ( unsigned int r = startrow; r < endrow; r++ ) {
1381 unsigned int c = startcol;
1382 // since a cell can be -1 (indicating a colspan) we might have to search backwards to include it
1383 while ( c && cellAt( r, c ) == (RenderTableCell *)-1 )
1385 for ( ; c < endcol; c++ ) {
1386 RenderTableCell *cell = cellAt(r, c);
1387 if (!cell || cell == (RenderTableCell *)-1 )
1390 // Cells must always paint in the order in which they appear taking into account
1391 // their upper left originating row/column. For cells with rowspans, avoid repainting
1392 // if we've already seen the cell.
1393 if (r > startrow && (cellAt(r-1, c) == cell))
1397 kdDebug( 6040 ) << "painting cell " << r << "/" << c << endl;
1399 cell->paint(i, tx, ty);
1405 void RenderTableSection::recalcCells()
1412 RenderObject *row = firstChild();
1416 ensureRows( cRow+1 );
1417 RenderObject *cell = row->firstChild();
1419 if ( cell->isTableCell() )
1420 addCell( static_cast<RenderTableCell *>(cell) );
1421 cell = cell->nextSibling();
1423 row = row->nextSibling();
1425 needCellRecalc = false;
1426 setNeedsLayout(true);
1429 void RenderTableSection::clearGrid()
1431 int rows = gridRows;
1433 delete grid[rows].row;
1437 RenderObject* RenderTableSection::removeChildNode(RenderObject* child)
1439 setNeedCellRecalc();
1440 return RenderContainer::removeChildNode( child );
1444 void RenderTableSection::dump(QTextStream *stream, QString ind) const
1446 *stream << endl << ind << "grid=(" << grid.size() << "," << table()->numEffCols() << ")" << endl << ind;
1447 for ( unsigned int r = 0; r < grid.size(); r++ ) {
1448 for ( int c = 0; c < table()->numEffCols(); c++ ) {
1449 if ( cellAt( r, c ) && cellAt( r, c ) != (RenderTableCell *)-1 )
1450 *stream << "(" << cellAt( r, c )->row() << "," << cellAt( r, c )->col() << ","
1451 << cellAt(r, c)->rowSpan() << "," << cellAt(r, c)->colSpan() << ") ";
1453 *stream << cellAt( r, c ) << "null cell ";
1455 *stream << endl << ind;
1457 RenderContainer::dump(stream,ind);
1461 // -------------------------------------------------------------------------
1463 RenderTableRow::RenderTableRow(DOM::NodeImpl* node)
1464 : RenderContainer(node)
1466 // init RenderObject attributes
1467 setInline(false); // our object is not Inline
1470 void RenderTableRow::detach()
1472 RenderTableSection *s = section();
1474 s->setNeedCellRecalc();
1476 RenderContainer::detach();
1479 void RenderTableRow::setStyle(RenderStyle* style)
1481 style->setDisplay(TABLE_ROW);
1482 RenderContainer::setStyle(style);
1485 void RenderTableRow::addChild(RenderObject *child, RenderObject *beforeChild)
1488 kdDebug( 6040 ) << renderName() << "(TableRow)::addChild( " << child->renderName() << " )" << ", " <<
1489 (beforeChild ? beforeChild->renderName() : "0") << " )" << endl;
1491 if (child->element() && child->element()->id() == ID_FORM) {
1492 RenderContainer::addChild(child,beforeChild);
1496 RenderTableCell *cell;
1498 if ( !child->isTableCell() ) {
1499 RenderObject *last = beforeChild;
1502 RenderTableCell *cell = 0;
1503 if( last && last->isAnonymous() && last->isTableCell() )
1504 cell = static_cast<RenderTableCell *>(last);
1506 cell = new (renderArena()) RenderTableCell(document() /* anonymous object */);
1507 RenderStyle *newStyle = new (renderArena()) RenderStyle();
1508 newStyle->inheritFrom(style());
1509 newStyle->setDisplay( TABLE_CELL );
1510 cell->setStyle(newStyle);
1511 addChild(cell, beforeChild);
1513 cell->addChild(child);
1514 child->setNeedsLayoutAndMinMaxRecalc();
1517 cell = static_cast<RenderTableCell *>(child);
1519 static_cast<RenderTableSection *>(parent())->addCell( cell );
1521 RenderContainer::addChild(cell,beforeChild);
1523 if ( ( beforeChild || nextSibling()) && section() )
1524 section()->setNeedCellRecalc();
1527 RenderObject* RenderTableRow::removeChildNode(RenderObject* child)
1529 // RenderTableCell detach should do it
1531 // section()->setNeedCellRecalc();
1532 return RenderContainer::removeChildNode( child );
1536 void RenderTableRow::dump(QTextStream *stream, QString ind) const
1538 RenderContainer::dump(stream,ind);
1542 void RenderTableRow::layout()
1544 KHTMLAssert( needsLayout() );
1545 KHTMLAssert( minMaxKnown() );
1547 RenderObject *child = firstChild();
1549 if (child->isTableCell()) {
1550 RenderTableCell *cell = static_cast<RenderTableCell *>(child);
1551 if (child->needsLayout()) {
1552 cell->calcVerticalMargins();
1554 cell->setCellTopExtra(0);
1555 cell->setCellBottomExtra(0);
1558 child = child->nextSibling();
1560 setNeedsLayout(false);
1563 QRect RenderTableRow::getAbsoluteRepaintRect()
1565 // For now, just repaint the whole table.
1566 // FIXME: Find a better way to do this.
1567 RenderTable* parentTable = table();
1569 return parentTable->getAbsoluteRepaintRect();
1574 // -------------------------------------------------------------------------
1576 RenderTableCell::RenderTableCell(DOM::NodeImpl* _node)
1577 : RenderBlock(_node)
1581 updateFromElement();
1582 setShouldPaintBackgroundOrBorder(true);
1585 m_percentageHeight = 0;
1588 void RenderTableCell::detach()
1590 if (parent() && section())
1591 section()->setNeedCellRecalc();
1593 RenderBlock::detach();
1596 void RenderTableCell::updateFromElement()
1598 DOM::NodeImpl *node = element();
1599 if ( node && (node->id() == ID_TD || node->id() == ID_TH) ) {
1600 DOM::HTMLTableCellElementImpl *tc = static_cast<DOM::HTMLTableCellElementImpl *>(node);
1601 cSpan = tc->colSpan();
1602 rSpan = tc->rowSpan();
1608 void RenderTableCell::calcMinMaxWidth()
1610 RenderBlock::calcMinMaxWidth();
1611 if (element() && style()->whiteSpace() == NORMAL) {
1612 // See if nowrap was set.
1613 DOMString nowrap = static_cast<ElementImpl*>(element())->getAttribute(ATTR_NOWRAP);
1614 if (!nowrap.isNull() && style()->width().isFixed())
1615 // Nowrap is set, but we didn't actually use it because of the
1616 // fixed width set on the cell. Even so, it is a WinIE/Moz trait
1617 // to make the minwidth of the cell into the fixed width. They do this
1618 // even in strict mode, so do not make this a quirk. Affected the top
1620 if (m_minWidth < style()->width().value)
1621 m_minWidth = style()->width().value;
1625 void RenderTableCell::calcWidth()
1629 void RenderTableCell::setWidth( int width )
1631 if ( width != m_width ) {
1633 m_widthChanged = true;
1637 void RenderTableCell::layout()
1639 layoutBlock(m_widthChanged);
1640 m_widthChanged = false;
1643 void RenderTableCell::computeAbsoluteRepaintRect(QRect& r, bool f)
1645 r.setY(r.y() + _topExtra);
1646 RenderBlock::computeAbsoluteRepaintRect(r, f);
1649 bool RenderTableCell::absolutePosition(int &xPos, int &yPos, bool f)
1651 bool ret = RenderBlock::absolutePosition(xPos, yPos, f);
1657 short RenderTableCell::baselinePosition( bool ) const
1659 RenderObject *o = firstChild();
1660 int offset = paddingTop() + borderTop();
1661 if ( !o ) return offset;
1662 while ( o->firstChild() ) {
1663 if ( !o->isInline() )
1664 offset += o->paddingTop() + o->borderTop();
1665 o = o->firstChild();
1667 offset += o->baselinePosition( true );
1672 void RenderTableCell::setStyle( RenderStyle *style )
1674 style->setDisplay(TABLE_CELL);
1676 if (style->whiteSpace() == KHTML_NOWRAP) {
1677 // Figure out if we are really nowrapping or if we should just
1678 // use normal instead. If the width of the cell is fixed, then
1679 // we don't actually use NOWRAP.
1680 if (style->width().isFixed())
1681 style->setWhiteSpace(NORMAL);
1683 style->setWhiteSpace(NOWRAP);
1686 RenderBlock::setStyle( style );
1687 setShouldPaintBackgroundOrBorder(true);
1690 bool RenderTableCell::requiresLayer() {
1691 // FIXME: This is only here until we figure out how to position
1692 // table cells properly when they have layers.
1696 // The following rules apply for resolving conflicts and figuring out which border
1698 // (1) Borders with the 'border-style' of 'hidden' take precedence over all other conflicting
1699 // borders. Any border with this value suppresses all borders at this location.
1700 // (2) Borders with a style of 'none' have the lowest priority. Only if the border properties of all
1701 // the elements meeting at this edge are 'none' will the border be omitted (but note that 'none' is
1702 // the default value for the border style.)
1703 // (3) If none of the styles are 'hidden' and at least one of them is not 'none', then narrow borders
1704 // are discarded in favor of wider ones. If several have the same 'border-width' then styles are preferred
1705 // in this order: 'double', 'solid', 'dashed', 'dotted', 'ridge', 'outset', 'groove', and the lowest: 'inset'.
1706 // (4) If border styles differ only in color, then a style set on a cell wins over one on a row,
1707 // which wins over a row group, column, column group and, lastly, table. It is undefined which color
1708 // is used when two elements of the same type disagree.
1709 static CollapsedBorderValue compareBorders(const CollapsedBorderValue& border1,
1710 const CollapsedBorderValue& border2)
1712 // Sanity check the values passed in. If either is null, return the other.
1713 if (!border2.exists()) return border1;
1714 if (!border1.exists()) return border2;
1717 if (border1.style() == BHIDDEN || border2.style() == BHIDDEN)
1718 return CollapsedBorderValue(); // No border should exist at this location.
1720 // Rule #2 above. A style of 'none' has lowest priority and always loses to any other border.
1721 if (border2.style() == BNONE) return border1;
1722 if (border1.style() == BNONE) return border2;
1724 // The first part of rule #3 above. Wider borders win.
1725 if (border1.width() != border2.width())
1726 return border1.width() > border2.width() ? border1 : border2;
1728 // The borders have equal width. Sort by border style.
1729 if (border1.style() != border2.style())
1730 return border1.style() > border2.style() ? border1 : border2;
1732 // The border have the same width and style. Rely on precedence (cell over row over row group, etc.)
1733 return border1.precedence >= border2.precedence ? border1 : border2;
1736 CollapsedBorderValue RenderTableCell::collapsedLeftBorder() const
1738 // For border left, we need to check, in order of precedence:
1739 // (1) Our left border.
1740 CollapsedBorderValue result(&style()->borderLeft(), BCELL);
1742 // (2) The previous cell's right border.
1743 RenderTableCell* prevCell = table()->cellLeft(this);
1745 result = compareBorders(result, CollapsedBorderValue(&prevCell->style()->borderRight(), BCELL));
1746 if (!result.exists()) return result;
1748 else if (col() == 0) {
1749 // (3) Our row's left border.
1750 result = compareBorders(result, CollapsedBorderValue(&parent()->style()->borderLeft(), BROW));
1751 if (!result.exists()) return result;
1753 // (4) Our row group's left border.
1754 result = compareBorders(result, CollapsedBorderValue(§ion()->style()->borderLeft(), BROWGROUP));
1755 if (!result.exists()) return result;
1758 // (5) Our column's left border.
1759 RenderTableCol* colElt = table()->colElement(col());
1761 result = compareBorders(result, CollapsedBorderValue(&colElt->style()->borderLeft(), BCOL));
1762 if (!result.exists()) return result;
1765 // (6) The previous column's right border.
1767 colElt = table()->colElement(col()-1);
1769 result = compareBorders(result, CollapsedBorderValue(&colElt->style()->borderRight(), BCOL));
1770 if (!result.exists()) return result;
1775 // (7) The table's left border.
1776 result = compareBorders(result, CollapsedBorderValue(&table()->style()->borderLeft(), BTABLE));
1777 if (!result.exists()) return result;
1783 CollapsedBorderValue RenderTableCell::collapsedRightBorder() const
1785 RenderTable* tableElt = table();
1786 bool inLastColumn = false;
1787 int effCol = tableElt->colToEffCol(col()+colSpan()-1);
1788 if (effCol == tableElt->numEffCols()-1)
1789 inLastColumn = true;
1791 // For border right, we need to check, in order of precedence:
1792 // (1) Our right border.
1793 CollapsedBorderValue result = CollapsedBorderValue(&style()->borderRight(), BCELL);
1795 // (2) The next cell's left border.
1796 if (!inLastColumn) {
1797 RenderTableCell* nextCell = tableElt->cellRight(this);
1799 result = compareBorders(result, CollapsedBorderValue(&nextCell->style()->borderLeft(), BCELL));
1800 if (!result.exists()) return result;
1804 // (3) Our row's right border.
1805 result = compareBorders(result, CollapsedBorderValue(&parent()->style()->borderRight(), BROW));
1806 if (!result.exists()) return result;
1808 // (4) Our row group's right border.
1809 result = compareBorders(result, CollapsedBorderValue(§ion()->style()->borderRight(), BROWGROUP));
1810 if (!result.exists()) return result;
1813 // (5) Our column's right border.
1814 RenderTableCol* colElt = table()->colElement(col()+colSpan()-1);
1816 result = compareBorders(result, CollapsedBorderValue(&colElt->style()->borderRight(), BCOL));
1817 if (!result.exists()) return result;
1820 // (6) The next column's left border.
1821 if (!inLastColumn) {
1822 colElt = tableElt->colElement(col()+colSpan());
1824 result = compareBorders(result, CollapsedBorderValue(&colElt->style()->borderLeft(), BCOL));
1825 if (!result.exists()) return result;
1829 // (7) The table's right border.
1830 result = compareBorders(result, CollapsedBorderValue(&tableElt->style()->borderRight(), BTABLE));
1831 if (!result.exists()) return result;
1837 CollapsedBorderValue RenderTableCell::collapsedTopBorder() const
1839 // For border top, we need to check, in order of precedence:
1840 // (1) Our top border.
1841 CollapsedBorderValue result = CollapsedBorderValue(&style()->borderTop(), BCELL);
1843 RenderTableCell* prevCell = table()->cellAbove(this);
1845 // (2) A previous cell's bottom border.
1846 result = compareBorders(result, CollapsedBorderValue(&prevCell->style()->borderBottom(), BCELL));
1847 if (!result.exists()) return result;
1850 // (3) Our row's top border.
1851 result = compareBorders(result, CollapsedBorderValue(&parent()->style()->borderTop(), BROW));
1852 if (!result.exists()) return result;
1854 // (4) The previous row's bottom border.
1856 RenderObject* prevRow = 0;
1857 if (prevCell->section() == section())
1858 prevRow = parent()->previousSibling();
1860 prevRow = prevCell->section()->lastChild();
1863 result = compareBorders(result, CollapsedBorderValue(&prevRow->style()->borderBottom(), BROW));
1864 if (!result.exists()) return result;
1868 // Now check row groups.
1869 RenderObject* currSection = parent()->parent();
1871 // (5) Our row group's top border.
1872 result = compareBorders(result, CollapsedBorderValue(&currSection->style()->borderTop(), BROWGROUP));
1873 if (!result.exists()) return result;
1875 // (6) Previous row group's bottom border.
1876 for (currSection = currSection->previousSibling(); currSection;
1877 currSection = currSection->previousSibling()) {
1878 if (currSection->isTableSection()) {
1879 RenderTableSection* section = static_cast<RenderTableSection*>(currSection);
1880 result = compareBorders(result, CollapsedBorderValue(§ion->style()->borderBottom(), BROWGROUP));
1881 if (!result.exists()) return result;
1887 // (8) Our column's top border.
1888 RenderTableCol* colElt = table()->colElement(col());
1890 result = compareBorders(result, CollapsedBorderValue(&colElt->style()->borderTop(), BCOL));
1891 if (!result.exists()) return result;
1894 // (9) The table's top border.
1895 result = compareBorders(result, CollapsedBorderValue(&table()->style()->borderTop(), BTABLE));
1896 if (!result.exists()) return result;
1902 CollapsedBorderValue RenderTableCell::collapsedBottomBorder() const
1904 // For border top, we need to check, in order of precedence:
1905 // (1) Our bottom border.
1906 CollapsedBorderValue result = CollapsedBorderValue(&style()->borderBottom(), BCELL);
1908 RenderTableCell* nextCell = table()->cellBelow(this);
1910 // (2) A following cell's top border.
1911 result = compareBorders(result, CollapsedBorderValue(&nextCell->style()->borderTop(), BCELL));
1912 if (!result.exists()) return result;
1915 // (3) Our row's bottom border. (FIXME: Deal with rowspan!)
1916 result = compareBorders(result, CollapsedBorderValue(&parent()->style()->borderBottom(), BROW));
1917 if (!result.exists()) return result;
1919 // (4) The next row's top border.
1921 result = compareBorders(result, CollapsedBorderValue(&nextCell->parent()->style()->borderTop(), BROW));
1922 if (!result.exists()) return result;
1925 // Now check row groups.
1926 RenderObject* currSection = parent()->parent();
1927 if (row()+rowSpan() >= static_cast<RenderTableSection*>(currSection)->numRows()) {
1928 // (5) Our row group's bottom border.
1929 result = compareBorders(result, CollapsedBorderValue(&currSection->style()->borderBottom(), BROWGROUP));
1930 if (!result.exists()) return result;
1932 // (6) Following row group's top border.
1933 for (currSection = currSection->nextSibling(); currSection;
1934 currSection = currSection->nextSibling()) {
1935 if (currSection->isTableSection()) {
1936 RenderTableSection* section = static_cast<RenderTableSection*>(currSection);
1937 result = compareBorders(result, CollapsedBorderValue(§ion->style()->borderTop(), BROWGROUP));
1938 if (!result.exists()) return result;
1944 // (8) Our column's bottom border.
1945 RenderTableCol* colElt = table()->colElement(col());
1947 result = compareBorders(result, CollapsedBorderValue(&colElt->style()->borderBottom(), BCOL));
1948 if (!result.exists()) return result;
1951 // (9) The table's bottom border.
1952 result = compareBorders(result, CollapsedBorderValue(&table()->style()->borderBottom(), BTABLE));
1953 if (!result.exists()) return result;
1959 int RenderTableCell::borderLeft() const
1961 if (table()->collapseBorders()) {
1962 CollapsedBorderValue border = collapsedLeftBorder();
1963 if (border.exists())
1964 return int(border.width()/2.0+0.5); // Give the extra pixel to top and left.
1967 return RenderBlock::borderLeft();
1970 int RenderTableCell::borderRight() const
1972 if (table()->collapseBorders()) {
1973 CollapsedBorderValue border = collapsedRightBorder();
1974 if (border.exists())
1975 return border.width()/2;
1978 return RenderBlock::borderRight();
1981 int RenderTableCell::borderTop() const
1983 if (table()->collapseBorders()) {
1984 CollapsedBorderValue border = collapsedTopBorder();
1985 if (border.exists())
1986 return int(border.width()/2.0+0.5); // Give the extra pixel to top and left.
1989 return RenderBlock::borderTop();
1992 int RenderTableCell::borderBottom() const
1994 if (table()->collapseBorders()) {
1995 CollapsedBorderValue border = collapsedBottomBorder();
1996 if (border.exists())
1997 return border.width()/2;
2000 return RenderBlock::borderBottom();
2004 #include <qpainter.h>
2006 static void outlineBox(QPainter *p, int _tx, int _ty, int w, int h)
2008 p->setPen(QPen(QColor("yellow"), 3, Qt::DotLine));
2009 p->setBrush( Qt::NoBrush );
2010 p->drawRect(_tx, _ty, w, h );
2014 void RenderTableCell::paint(PaintInfo& i, int _tx, int _ty)
2018 kdDebug( 6040 ) << renderName() << "(RenderTableCell)::paint() w/h = (" << width() << "/" << height() << ")" << " _y/_h=" << _y << "/" << _h << endl;
2024 // check if we need to do anything at all...
2025 int os = 2*maximalOutlineSize(i.phase);
2026 if ((_ty >= i.r.y() + i.r.height() + os) || (_ty + _topExtra + m_height + _bottomExtra <= i.r.y() - os))
2029 if (i.phase == PaintActionCollapsedTableBorders && style()->visibility() == VISIBLE) {
2031 int h = height() + borderTopExtra() + borderBottomExtra();
2032 paintCollapsedBorder(i.p, _tx, _ty, w, h);
2035 RenderBlock::paintObject(i, _tx, _ty + _topExtra);
2038 ::outlineBox( i.p, _tx, _ty, width(), height() + borderTopExtra() + borderBottomExtra());
2042 static EBorderStyle collapsedBorderStyle(EBorderStyle style)
2044 if (style == OUTSET)
2046 else if (style == INSET)
2051 struct CollapsedBorder {
2054 CollapsedBorderValue border;
2055 RenderObject::BorderSide side;
2064 class CollapsedBorders
2067 CollapsedBorders(int i) :count(0) {}
2069 void addBorder(const CollapsedBorderValue& b, RenderObject::BorderSide s, bool paint,
2070 int _x1, int _y1, int _x2, int _y2,
2071 EBorderStyle _style)
2073 if (b.exists() && paint) {
2074 borders[count].border = b;
2075 borders[count].side = s;
2076 borders[count].shouldPaint = paint;
2077 borders[count].x1 = _x1;
2078 borders[count].x2 = _x2;
2079 borders[count].y1 = _y1;
2080 borders[count].y2 = _y2;
2081 borders[count].style = _style;
2086 CollapsedBorder* nextBorder() {
2087 for (int i = 0; i < count; i++) {
2088 if (borders[i].border.exists() && borders[i].shouldPaint) {
2089 borders[i].shouldPaint = false;
2097 CollapsedBorder borders[4];
2101 static void addBorderStyle(QValueList<CollapsedBorderValue>& borderStyles, CollapsedBorderValue borderValue)
2103 if (!borderValue.exists() || borderStyles.contains(borderValue))
2106 QValueListIterator<CollapsedBorderValue> it = borderStyles.begin();
2107 QValueListIterator<CollapsedBorderValue> end = borderStyles.end();
2108 for (; it != end; ++it) {
2109 CollapsedBorderValue result = compareBorders(*it, borderValue);
2110 if (result == *it) {
2111 borderStyles.insert(it, borderValue);
2116 borderStyles.append(borderValue);
2119 void RenderTableCell::collectBorders(QValueList<CollapsedBorderValue>& borderStyles)
2121 addBorderStyle(borderStyles, collapsedLeftBorder());
2122 addBorderStyle(borderStyles, collapsedRightBorder());
2123 addBorderStyle(borderStyles, collapsedTopBorder());
2124 addBorderStyle(borderStyles, collapsedBottomBorder());
2127 void RenderTableCell::paintCollapsedBorder(QPainter* p, int _tx, int _ty, int w, int h)
2129 if (!table()->currentBorderStyle())
2132 CollapsedBorderValue leftVal = collapsedLeftBorder();
2133 CollapsedBorderValue rightVal = collapsedRightBorder();
2134 CollapsedBorderValue topVal = collapsedTopBorder();
2135 CollapsedBorderValue bottomVal = collapsedBottomBorder();
2137 // Adjust our x/y/width/height so that we paint the collapsed borders at the correct location.
2138 int topWidth = topVal.width();
2139 int bottomWidth = bottomVal.width();
2140 int leftWidth = leftVal.width();
2141 int rightWidth = rightVal.width();
2145 w += leftWidth/2 + int(rightWidth/2.0+0.5);
2146 h += topWidth/2 + int(bottomWidth/2.0+0.5);
2148 bool tt = topVal.isTransparent();
2149 bool bt = bottomVal.isTransparent();
2150 bool rt = rightVal.isTransparent();
2151 bool lt = leftVal.isTransparent();
2153 EBorderStyle ts = collapsedBorderStyle(topVal.style());
2154 EBorderStyle bs = collapsedBorderStyle(bottomVal.style());
2155 EBorderStyle ls = collapsedBorderStyle(leftVal.style());
2156 EBorderStyle rs = collapsedBorderStyle(rightVal.style());
2158 bool render_t = ts > BHIDDEN && !tt;
2159 bool render_l = ls > BHIDDEN && !lt;
2160 bool render_r = rs > BHIDDEN && !rt;
2161 bool render_b = bs > BHIDDEN && !bt;
2163 // We never paint diagonals at the joins. We simply let the border with the highest
2164 // precedence paint on top of borders with lower precedence.
2165 CollapsedBorders borders(4);
2166 borders.addBorder(topVal, BSTop, render_t, _tx, _ty, _tx + w, _ty + topWidth, ts);
2167 borders.addBorder(bottomVal, BSBottom, render_b, _tx, _ty + h - bottomWidth, _tx + w, _ty + h, bs);
2168 borders.addBorder(leftVal, BSLeft, render_l, _tx, _ty, _tx + leftWidth, _ty + h, ls);
2169 borders.addBorder(rightVal, BSRight, render_r, _tx + w - rightWidth, _ty, _tx + w, _ty + h, rs);
2171 for (CollapsedBorder* border = borders.nextBorder(); border; border = borders.nextBorder()) {
2172 if (border->border == *table()->currentBorderStyle())
2173 drawBorder(p, border->x1, border->y1, border->x2, border->y2, border->side,
2174 border->border.color(), style()->color(), border->style, 0, 0);
2178 QRect RenderTableCell::getAbsoluteRepaintRect()
2180 int ow = style() ? style()->outlineSize() : 0;
2181 QRect r(-ow, -ow - borderTopExtra(),
2182 overflowWidth(false)+ow*2, overflowHeight(false)+borderTopExtra()+borderBottomExtra()+ow*2);
2183 computeAbsoluteRepaintRect(r);
2187 void RenderTableCell::paintBoxDecorations(PaintInfo& i, int _tx, int _ty)
2189 RenderTable* tableElt = table();
2190 if (!tableElt->collapseBorders() && style()->emptyCells() == HIDE && !firstChild())
2194 int h = height() + borderTopExtra() + borderBottomExtra();
2195 _ty -= borderTopExtra();
2197 QColor c = style()->backgroundColor();
2198 if ( !c.isValid() && parent() ) // take from row
2199 c = parent()->style()->backgroundColor();
2200 if ( !c.isValid() && parent() && parent()->parent() ) // take from rowgroup
2201 c = parent()->parent()->style()->backgroundColor();
2202 if ( !c.isValid() ) {
2203 // see if we have a col or colgroup for this
2204 RenderTableCol *col = table()->colElement( _col );
2206 c = col->style()->backgroundColor();
2207 if ( !c.isValid() ) {
2209 RenderStyle *style = col->parent()->style();
2210 if ( style->display() == TABLE_COLUMN_GROUP )
2211 c = style->backgroundColor();
2216 // FIXME: This code is just plain wrong. Rows and columns should paint their backgrounds
2217 // independent from the cell.
2218 // ### get offsets right in case the bgimage is inherited.
2219 const BackgroundLayer* bgLayer = style()->backgroundLayers();
2220 if (!bgLayer->hasImage() && parent())
2221 bgLayer = parent()->style()->backgroundLayers();
2222 if (!bgLayer->hasImage() && parent() && parent()->parent())
2223 bgLayer = parent()->parent()->style()->backgroundLayers();
2224 if (!bgLayer->hasImage()) {
2225 // see if we have a col or colgroup for this
2226 RenderTableCol* col = table()->colElement(_col);
2228 bgLayer = col->style()->backgroundLayers();
2229 if (!bgLayer->hasImage()) {
2231 RenderStyle *style = col->parent()->style();
2232 if (style->display() == TABLE_COLUMN_GROUP)
2233 bgLayer = style->backgroundLayers();
2238 int my = kMax(_ty, i.r.y());
2239 int end = kMin(i.r.y() + i.r.height(), _ty + h);
2242 if (bgLayer->hasImage() || c.isValid())
2243 paintBackground(i.p, c, bgLayer, my, mh, _tx, _ty, w, h);
2245 if (style()->hasBorder() && !tableElt->collapseBorders())
2246 paintBorder(i.p, _tx, _ty, w, h, style());
2251 void RenderTableCell::dump(QTextStream *stream, QString ind) const
2253 *stream << " row=" << _row;
2254 *stream << " col=" << _col;
2255 *stream << " rSpan=" << rSpan;
2256 *stream << " cSpan=" << cSpan;
2257 // *stream << " nWrap=" << nWrap;
2259 RenderBlock::dump(stream,ind);
2263 // -------------------------------------------------------------------------
2265 RenderTableCol::RenderTableCol(DOM::NodeImpl* node)
2266 : RenderContainer(node)
2268 // init RenderObject attributes
2269 setInline(true); // our object is not Inline
2272 updateFromElement();
2275 void RenderTableCol::updateFromElement()
2277 DOM::NodeImpl *node = element();
2278 if ( node && (node->id() == ID_COL || node->id() == ID_COLGROUP) ) {
2279 DOM::HTMLTableColElementImpl *tc = static_cast<DOM::HTMLTableColElementImpl *>(node);
2282 _span = ! ( style() && style()->display() == TABLE_COLUMN_GROUP );
2285 bool RenderTableCol::canHaveChildren() const
2287 // cols cannot have children. This is actually necessary to fix a bug
2288 // with libraries.uc.edu, which makes a <p> be a table-column.
2289 return style()->display() == TABLE_COLUMN_GROUP;
2292 void RenderTableCol::addChild(RenderObject *child, RenderObject *beforeChild)
2295 //kdDebug( 6040 ) << renderName() << "(Table)::addChild( " << child->renderName() << " )" << ", " <<
2296 // (beforeChild ? beforeChild->renderName() : 0) << " )" << endl;
2299 KHTMLAssert(child->style()->display() == TABLE_COLUMN);
2301 // these have to come before the table definition!
2302 RenderContainer::addChild(child,beforeChild);
2306 void RenderTableCol::dump(QTextStream *stream, QString ind) const
2308 *stream << " _span=" << _span;
2309 RenderContainer::dump(stream,ind);