2 * Copyright (C) 1997 Martin Jones (mjones@kde.org)
3 * (C) 1997 Torben Weis (weis@kde.org)
4 * (C) 1998 Waldo Bastian (bastian@kde.org)
5 * (C) 1999 Lars Knoll (knoll@kde.org)
6 * (C) 1999 Antti Koivisto (koivisto@kde.org)
7 * Copyright (C) 2003, 2004, 2005, 2006, 2008, 2009, 2010 Apple Inc. All rights reserved.
8 * Copyright (C) 2006 Alexey Proskuryakov (ap@nypop.com)
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Library General Public
12 * License as published by the Free Software Foundation; either
13 * version 2 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Library General Public License for more details.
20 * You should have received a copy of the GNU Library General Public License
21 * along with this library; see the file COPYING.LIB. If not, write to
22 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 * Boston, MA 02110-1301, USA.
27 #include "RenderTableSection.h"
28 #include "CachedImage.h"
30 #include "HitTestResult.h"
31 #include "HTMLNames.h"
32 #include "PaintInfo.h"
33 #include "RenderTableCell.h"
34 #include "RenderTableCol.h"
35 #include "RenderTableRow.h"
36 #include "RenderView.h"
38 #include <wtf/HashSet.h>
39 #include <wtf/Vector.h>
45 using namespace HTMLNames;
47 // Those 2 variables are used to balance the memory consumption vs the repaint time on big tables.
48 static unsigned gMinTableSizeToUseFastPaintPathWithOverflowingCell = 75 * 75;
49 static float gMaxAllowedOverflowingCellRatioForFastPaintPath = 0.1f;
51 static inline void setRowLogicalHeightToRowStyleLogicalHeightIfNotRelative(RenderTableSection::RowStruct& row)
53 ASSERT(row.rowRenderer);
54 row.logicalHeight = row.rowRenderer->style()->logicalHeight();
55 if (row.logicalHeight.isRelative())
56 row.logicalHeight = Length();
59 RenderTableSection::RenderTableSection(Node* node)
63 , m_outerBorderStart(0)
65 , m_outerBorderBefore(0)
66 , m_outerBorderAfter(0)
67 , m_needsCellRecalc(false)
68 , m_hasMultipleCellLevels(false)
70 // init RenderObject attributes
71 setInline(false); // our object is not Inline
74 RenderTableSection::~RenderTableSection()
78 void RenderTableSection::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
80 RenderBox::styleDidChange(diff, oldStyle);
81 propagateStyleToAnonymousChildren();
83 // If border was changed, notify table.
84 RenderTable* table = this->table();
85 if (table && !table->selfNeedsLayout() && !table->normalChildNeedsLayout() && oldStyle && oldStyle->border() != style()->border())
86 table->invalidateCollapsedBorders();
89 void RenderTableSection::willBeDestroyed()
91 RenderTable* recalcTable = table();
93 RenderBox::willBeDestroyed();
95 // recalc cell info because RenderTable has unguarded pointers
96 // stored that point to this RenderTableSection.
98 recalcTable->setNeedsSectionRecalc();
101 void RenderTableSection::addChild(RenderObject* child, RenderObject* beforeChild)
103 // Make sure we don't append things after :after-generated content if we have it.
105 beforeChild = afterPseudoElementRenderer();
107 if (!child->isTableRow()) {
108 RenderObject* last = beforeChild;
111 if (last && last->isAnonymous() && !last->isBeforeOrAfterContent()) {
112 if (beforeChild == last)
113 beforeChild = last->firstChild();
114 last->addChild(child, beforeChild);
118 if (beforeChild && !beforeChild->isAnonymous() && beforeChild->parent() == this) {
119 RenderObject* row = beforeChild->previousSibling();
120 if (row && row->isTableRow() && row->isAnonymous()) {
121 row->addChild(child);
126 // If beforeChild is inside an anonymous cell/row, insert into the cell or into
127 // the anonymous row containing it, if there is one.
128 RenderObject* lastBox = last;
129 while (lastBox && lastBox->parent()->isAnonymous() && !lastBox->isTableRow())
130 lastBox = lastBox->parent();
131 if (lastBox && lastBox->isAnonymous() && !lastBox->isBeforeOrAfterContent()) {
132 lastBox->addChild(child, beforeChild);
136 RenderObject* row = new (renderArena()) RenderTableRow(document() /* anonymous table row */);
137 RefPtr<RenderStyle> newStyle = RenderStyle::create();
138 newStyle->inheritFrom(style());
139 newStyle->setDisplay(TABLE_ROW);
140 row->setStyle(newStyle.release());
141 addChild(row, beforeChild);
142 row->addChild(child);
147 setNeedsCellRecalc();
149 unsigned insertionRow = m_cRow;
155 m_grid[insertionRow].rowRenderer = toRenderTableRow(child);
158 setRowLogicalHeightToRowStyleLogicalHeightIfNotRelative(m_grid[insertionRow]);
160 // If the next renderer is actually wrapped in an anonymous table row, we need to go up and find that.
161 while (beforeChild && beforeChild->parent() != this)
162 beforeChild = beforeChild->parent();
164 ASSERT(!beforeChild || beforeChild->isTableRow());
165 RenderBox::addChild(child, beforeChild);
166 toRenderTableRow(child)->updateBeforeAndAfterContent();
169 void RenderTableSection::removeChild(RenderObject* oldChild)
171 setNeedsCellRecalc();
172 RenderBox::removeChild(oldChild);
175 void RenderTableSection::ensureRows(unsigned numRows)
177 if (numRows <= m_grid.size())
180 unsigned oldSize = m_grid.size();
181 m_grid.grow(numRows);
183 unsigned effectiveColumnCount = max(1u, table()->numEffCols());
184 for (unsigned row = oldSize; row < m_grid.size(); ++row)
185 m_grid[row].row.grow(effectiveColumnCount);
188 void RenderTableSection::addCell(RenderTableCell* cell, RenderTableRow* row)
190 // We don't insert the cell if we need cell recalc as our internal columns' representation
191 // will have drifted from the table's representation. Also recalcCells will call addCell
192 // at a later time after sync'ing our columns' with the table's.
193 if (needsCellRecalc())
196 unsigned rSpan = cell->rowSpan();
197 unsigned cSpan = cell->colSpan();
198 Vector<RenderTable::ColumnStruct>& columns = table()->columns();
199 unsigned nCols = columns.size();
200 // addCell should be called only after m_cRow has been incremented.
202 unsigned insertionRow = m_cRow - 1;
204 // ### mozilla still seems to do the old HTML way, even for strict DTD
205 // (see the annotation on table cell layouting in the CSS specs and the testcase below:
207 // <TR><TD>1 <TD rowspan="2">2 <TD>3 <TD>4
208 // <TR><TD colspan="2">5
210 while (m_cCol < nCols && (cellAt(insertionRow, m_cCol).hasCells() || cellAt(insertionRow, m_cCol).inColSpan))
214 // we ignore height settings on rowspan cells
215 Length logicalHeight = cell->style()->logicalHeight();
216 if (logicalHeight.isPositive() || (logicalHeight.isRelative() && logicalHeight.value() >= 0)) {
217 Length cRowLogicalHeight = m_grid[insertionRow].logicalHeight;
218 switch (logicalHeight.type()) {
220 if (!(cRowLogicalHeight.isPercent()) ||
221 (cRowLogicalHeight.isPercent() && cRowLogicalHeight.percent() < logicalHeight.percent()))
222 m_grid[insertionRow].logicalHeight = logicalHeight;
225 if (cRowLogicalHeight.type() < Percent ||
226 (cRowLogicalHeight.isFixed() && cRowLogicalHeight.value() < logicalHeight.value()))
227 m_grid[insertionRow].logicalHeight = logicalHeight;
236 ensureRows(insertionRow + rSpan);
238 m_grid[insertionRow].rowRenderer = row;
240 unsigned col = m_cCol;
241 // tell the cell where it is
242 bool inColSpan = false;
244 unsigned currentSpan;
245 if (m_cCol >= nCols) {
246 table()->appendColumn(cSpan);
249 if (cSpan < columns[m_cCol].span)
250 table()->splitColumn(m_cCol, cSpan);
251 currentSpan = columns[m_cCol].span;
253 for (unsigned r = 0; r < rSpan; r++) {
254 CellStruct& c = cellAt(insertionRow + r, m_cCol);
256 c.cells.append(cell);
257 // If cells overlap then we take the slow path for painting.
258 if (c.cells.size() > 1)
259 m_hasMultipleCellLevels = true;
264 cSpan -= currentSpan;
267 cell->setRow(insertionRow);
268 cell->setCol(table()->effColToCol(col));
271 void RenderTableSection::setCellLogicalWidths()
273 Vector<LayoutUnit>& columnPos = table()->columnPositions();
275 LayoutStateMaintainer statePusher(view());
277 for (unsigned i = 0; i < m_grid.size(); i++) {
278 Row& row = m_grid[i].row;
279 unsigned cols = row.size();
280 for (unsigned j = 0; j < cols; j++) {
281 CellStruct& current = row[j];
282 RenderTableCell* cell = current.primaryCell();
283 if (!cell || current.inColSpan)
286 unsigned cspan = cell->colSpan();
287 while (cspan && endCol < cols) {
288 ASSERT(endCol < table()->columns().size());
289 cspan -= table()->columns()[endCol].span;
292 LayoutUnit w = columnPos[endCol] - columnPos[j] - table()->hBorderSpacing();
293 LayoutUnit oldLogicalWidth = cell->logicalWidth();
294 if (w != oldLogicalWidth) {
295 cell->setNeedsLayout(true);
296 if (!table()->selfNeedsLayout() && cell->checkForRepaintDuringLayout()) {
297 if (!statePusher.didPush()) {
298 // Technically, we should also push state for the row, but since
299 // rows don't push a coordinate transform, that's not necessary.
300 statePusher.push(this, LayoutSize(x(), y()));
304 cell->updateLogicalWidth(w);
309 statePusher.pop(); // only pops if we pushed
312 LayoutUnit RenderTableSection::calcRowLogicalHeight()
315 setNeedsLayoutIsForbidden(true);
318 ASSERT(!needsLayout());
320 RenderTableCell* cell;
322 LayoutUnit spacing = table()->vBorderSpacing();
324 LayoutStateMaintainer statePusher(view());
326 m_rowPos.resize(m_grid.size() + 1);
327 m_rowPos[0] = spacing;
329 for (unsigned r = 0; r < m_grid.size(); r++) {
331 m_grid[r].baseline = 0;
332 LayoutUnit baseline = 0;
333 LayoutUnit bdesc = 0;
334 LayoutUnit ch = m_grid[r].logicalHeight.calcMinValue(0);
335 LayoutUnit pos = m_rowPos[r] + ch + (m_grid[r].rowRenderer ? spacing : 0);
337 m_rowPos[r + 1] = max(m_rowPos[r + 1], pos);
339 Row& row = m_grid[r].row;
340 unsigned totalCols = row.size();
342 for (unsigned c = 0; c < totalCols; c++) {
343 CellStruct& current = cellAt(r, c);
344 cell = current.primaryCell();
346 if (!cell || current.inColSpan)
349 if ((cell->row() + cell->rowSpan() - 1) > r)
352 unsigned indx = max(r - cell->rowSpan() + 1, 0u);
354 if (cell->hasOverrideHeight()) {
355 if (!statePusher.didPush()) {
356 // Technically, we should also push state for the row, but since
357 // rows don't push a coordinate transform, that's not necessary.
358 statePusher.push(this, locationOffset());
360 cell->clearIntrinsicPadding();
361 cell->clearOverrideSize();
362 cell->setChildNeedsLayout(true, false);
363 cell->layoutIfNeeded();
366 LayoutUnit adjustedLogicalHeight = cell->logicalHeight() - (cell->intrinsicPaddingBefore() + cell->intrinsicPaddingAfter());
368 ch = cell->style()->logicalHeight().calcValue(0);
369 if (document()->inQuirksMode() || cell->style()->boxSizing() == BORDER_BOX) {
370 // Explicit heights use the border box in quirks mode.
371 // Don't adjust height.
373 // In strict mode, box-sizing: content-box do the right
374 // thing and actually add in the border and padding.
375 LayoutUnit adjustedPaddingBefore = cell->paddingBefore() - cell->intrinsicPaddingBefore();
376 LayoutUnit adjustedPaddingAfter = cell->paddingAfter() - cell->intrinsicPaddingAfter();
377 ch += adjustedPaddingBefore + adjustedPaddingAfter + cell->borderBefore() + cell->borderAfter();
379 ch = max(ch, adjustedLogicalHeight);
381 pos = m_rowPos[indx] + ch + (m_grid[r].rowRenderer ? spacing : 0);
383 m_rowPos[r + 1] = max(m_rowPos[r + 1], pos);
385 // find out the baseline
386 EVerticalAlign va = cell->style()->verticalAlign();
387 if (va == BASELINE || va == TEXT_BOTTOM || va == TEXT_TOP || va == SUPER || va == SUB) {
388 LayoutUnit b = cell->cellBaselinePosition();
389 if (b > cell->borderBefore() + cell->paddingBefore()) {
390 baseline = max(baseline, b - cell->intrinsicPaddingBefore());
391 bdesc = max(bdesc, m_rowPos[indx] + ch - (b - cell->intrinsicPaddingBefore()));
396 // do we have baseline aligned elements?
398 // increase rowheight if baseline requires
399 m_rowPos[r + 1] = max(m_rowPos[r + 1], baseline + bdesc + (m_grid[r].rowRenderer ? spacing : 0));
400 m_grid[r].baseline = baseline;
403 m_rowPos[r + 1] = max(m_rowPos[r + 1], m_rowPos[r]);
407 setNeedsLayoutIsForbidden(false);
410 ASSERT(!needsLayout());
414 return m_rowPos[m_grid.size()];
417 void RenderTableSection::layout()
419 ASSERT(needsLayout());
421 LayoutStateMaintainer statePusher(view(), this, locationOffset(), style()->isFlippedBlocksWritingMode());
422 for (RenderObject* child = children()->firstChild(); child; child = child->nextSibling()) {
423 if (child->isTableRow()) {
424 child->layoutIfNeeded();
425 ASSERT(!child->needsLayout());
429 setNeedsLayout(false);
432 LayoutUnit RenderTableSection::layoutRows(LayoutUnit toAdd)
435 setNeedsLayoutIsForbidden(true);
438 ASSERT(!needsLayout());
442 unsigned totalRows = m_grid.size();
444 // Set the width of our section now. The rows will also be this width.
445 setLogicalWidth(table()->contentLogicalWidth());
447 m_overflowingCells.clear();
448 m_forceSlowPaintPathWithOverflowingCell = false;
450 if (toAdd && totalRows && (m_rowPos[totalRows] || !nextSibling())) {
451 LayoutUnit totalHeight = m_rowPos[totalRows] + toAdd;
453 LayoutUnit dh = toAdd;
454 int totalPercent = 0;
456 for (unsigned r = 0; r < totalRows; r++) {
457 if (m_grid[r].logicalHeight.isAuto())
459 else if (m_grid[r].logicalHeight.isPercent())
460 totalPercent += m_grid[r].logicalHeight.percent();
463 // try to satisfy percent
465 totalPercent = min(totalPercent, 100);
466 LayoutUnit rh = m_rowPos[1] - m_rowPos[0];
467 for (unsigned r = 0; r < totalRows; r++) {
468 if (totalPercent > 0 && m_grid[r].logicalHeight.isPercent()) {
469 LayoutUnit toAdd = min<LayoutUnit>(dh, (totalHeight * m_grid[r].logicalHeight.percent() / 100) - rh);
470 // If toAdd is negative, then we don't want to shrink the row (this bug
471 // affected Outlook Web Access).
472 toAdd = max<LayoutUnit>(0, toAdd);
475 totalPercent -= m_grid[r].logicalHeight.percent();
477 ASSERT(totalRows >= 1);
478 if (r < totalRows - 1)
479 rh = m_rowPos[r + 2] - m_rowPos[r + 1];
480 m_rowPos[r + 1] += add;
484 // distribute over variable cols
486 for (unsigned r = 0; r < totalRows; r++) {
487 if (numAuto > 0 && m_grid[r].logicalHeight.isAuto()) {
488 LayoutUnit toAdd = dh / numAuto;
493 m_rowPos[r + 1] += add;
496 if (dh > 0 && m_rowPos[totalRows]) {
497 // if some left overs, distribute equally.
498 LayoutUnit tot = m_rowPos[totalRows];
500 LayoutUnit prev = m_rowPos[0];
501 for (unsigned r = 0; r < totalRows; r++) {
502 // weight with the original height
503 add += dh * (m_rowPos[r + 1] - prev) / tot;
504 prev = m_rowPos[r + 1];
505 m_rowPos[r + 1] += add;
510 LayoutUnit hspacing = table()->hBorderSpacing();
511 LayoutUnit vspacing = table()->vBorderSpacing();
512 unsigned nEffCols = table()->numEffCols();
514 LayoutStateMaintainer statePusher(view(), this, LayoutSize(x(), y()), style()->isFlippedBlocksWritingMode());
516 for (unsigned r = 0; r < totalRows; r++) {
517 // Set the row's x/y position and width/height.
518 if (RenderTableRow* rowRenderer = m_grid[r].rowRenderer) {
519 rowRenderer->setLocation(LayoutPoint(0, m_rowPos[r]));
520 rowRenderer->setLogicalWidth(logicalWidth());
521 rowRenderer->setLogicalHeight(m_rowPos[r + 1] - m_rowPos[r] - vspacing);
522 rowRenderer->updateLayerTransform();
525 for (unsigned c = 0; c < nEffCols; c++) {
526 CellStruct& cs = cellAt(r, c);
527 RenderTableCell* cell = cs.primaryCell();
529 if (!cell || cs.inColSpan)
533 rHeight = m_rowPos[rindx + cell->rowSpan()] - m_rowPos[rindx] - vspacing;
535 // Force percent height children to lay themselves out again.
536 // This will cause these children to grow to fill the cell.
537 // FIXME: There is still more work to do here to fully match WinIE (should
538 // it become necessary to do so). In quirks mode, WinIE behaves like we
539 // do, but it will clip the cells that spill out of the table section. In
540 // strict mode, Mozilla and WinIE both regrow the table to accommodate the
541 // new height of the cell (thus letting the percentages cause growth one
542 // time only). We may also not be handling row-spanning cells correctly.
544 // Note also the oddity where replaced elements always flex, and yet blocks/tables do
545 // not necessarily flex. WinIE is crazy and inconsistent, and we can't hope to
546 // match the behavior perfectly, but we'll continue to refine it as we discover new
548 bool cellChildrenFlex = false;
549 bool flexAllChildren = cell->style()->logicalHeight().isFixed()
550 || (!table()->style()->logicalHeight().isAuto() && rHeight != cell->logicalHeight());
552 for (RenderObject* o = cell->firstChild(); o; o = o->nextSibling()) {
553 if (!o->isText() && o->style()->logicalHeight().isPercent() && (flexAllChildren || o->isReplaced() || (o->isBox() && toRenderBox(o)->scrollsOverflow()))) {
554 // Tables with no sections do not flex.
555 if (!o->isTable() || toRenderTable(o)->hasSections()) {
556 o->setNeedsLayout(true, false);
557 cellChildrenFlex = true;
562 if (HashSet<RenderBox*>* percentHeightDescendants = cell->percentHeightDescendants()) {
563 HashSet<RenderBox*>::iterator end = percentHeightDescendants->end();
564 for (HashSet<RenderBox*>::iterator it = percentHeightDescendants->begin(); it != end; ++it) {
565 RenderBox* box = *it;
566 if (!box->isReplaced() && !box->scrollsOverflow() && !flexAllChildren)
569 while (box != cell) {
570 if (box->normalChildNeedsLayout())
572 box->setChildNeedsLayout(true, false);
573 box = box->containingBlock();
578 cellChildrenFlex = true;
582 if (cellChildrenFlex) {
583 cell->setChildNeedsLayout(true, false);
584 // Alignment within a cell is based off the calculated
585 // height, which becomes irrelevant once the cell has
586 // been resized based off its percentage.
587 cell->setOverrideHeightFromRowHeight(rHeight);
588 cell->layoutIfNeeded();
590 // If the baseline moved, we may have to update the data for our row. Find out the new baseline.
591 EVerticalAlign va = cell->style()->verticalAlign();
592 if (va == BASELINE || va == TEXT_BOTTOM || va == TEXT_TOP || va == SUPER || va == SUB) {
593 LayoutUnit baseline = cell->cellBaselinePosition();
594 if (baseline > cell->borderBefore() + cell->paddingBefore())
595 m_grid[r].baseline = max(m_grid[r].baseline, baseline);
599 LayoutUnit oldIntrinsicPaddingBefore = cell->intrinsicPaddingBefore();
600 LayoutUnit oldIntrinsicPaddingAfter = cell->intrinsicPaddingAfter();
601 LayoutUnit logicalHeightWithoutIntrinsicPadding = cell->logicalHeight() - oldIntrinsicPaddingBefore - oldIntrinsicPaddingAfter;
603 LayoutUnit intrinsicPaddingBefore = 0;
604 switch (cell->style()->verticalAlign()) {
610 LayoutUnit b = cell->cellBaselinePosition();
611 if (b > cell->borderBefore() + cell->paddingBefore())
612 intrinsicPaddingBefore = getBaseline(r) - (b - oldIntrinsicPaddingBefore);
618 intrinsicPaddingBefore = (rHeight - logicalHeightWithoutIntrinsicPadding) / 2;
621 intrinsicPaddingBefore = rHeight - logicalHeightWithoutIntrinsicPadding;
627 LayoutUnit intrinsicPaddingAfter = rHeight - logicalHeightWithoutIntrinsicPadding - intrinsicPaddingBefore;
628 cell->setIntrinsicPaddingBefore(intrinsicPaddingBefore);
629 cell->setIntrinsicPaddingAfter(intrinsicPaddingAfter);
631 LayoutRect oldCellRect(cell->x(), cell->y() , cell->width(), cell->height());
633 LayoutPoint cellLocation(0, m_rowPos[rindx]);
634 if (!style()->isLeftToRightDirection())
635 cellLocation.setX(table()->columnPositions()[nEffCols] - table()->columnPositions()[table()->colToEffCol(cell->col() + cell->colSpan())] + hspacing);
637 cellLocation.setX(table()->columnPositions()[c] + hspacing);
638 cell->setLogicalLocation(cellLocation);
639 view()->addLayoutDelta(oldCellRect.location() - cell->location());
641 if (intrinsicPaddingBefore != oldIntrinsicPaddingBefore || intrinsicPaddingAfter != oldIntrinsicPaddingAfter)
642 cell->setNeedsLayout(true, false);
644 if (!cell->needsLayout() && view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(cell->logicalTop()) != cell->pageLogicalOffset())
645 cell->setChildNeedsLayout(true, false);
647 cell->layoutIfNeeded();
649 // FIXME: Make pagination work with vertical tables.
650 if (style()->isHorizontalWritingMode() && view()->layoutState()->pageLogicalHeight() && cell->height() != rHeight)
651 cell->setHeight(rHeight); // FIXME: Pagination might have made us change size. For now just shrink or grow the cell to fit without doing a relayout.
653 LayoutSize childOffset(cell->location() - oldCellRect.location());
654 if (childOffset.width() || childOffset.height()) {
655 view()->addLayoutDelta(childOffset);
657 // If the child moved, we have to repaint it as well as any floating/positioned
658 // descendants. An exception is if we need a layout. In this case, we know we're going to
659 // repaint ourselves (and the child) anyway.
660 if (!table()->selfNeedsLayout() && cell->checkForRepaintDuringLayout())
661 cell->repaintDuringLayoutIfMoved(oldCellRect);
667 setNeedsLayoutIsForbidden(false);
670 ASSERT(!needsLayout());
672 setLogicalHeight(m_rowPos[totalRows]);
674 unsigned totalCellsCount = nEffCols * totalRows;
675 int maxAllowedOverflowingCellsCount = totalCellsCount < gMinTableSizeToUseFastPaintPathWithOverflowingCell ? 0 : gMaxAllowedOverflowingCellRatioForFastPaintPath * totalCellsCount;
678 bool hasOverflowingCell = false;
680 // Now that our height has been determined, add in overflow from cells.
681 for (unsigned r = 0; r < totalRows; r++) {
682 for (unsigned c = 0; c < nEffCols; c++) {
683 CellStruct& cs = cellAt(r, c);
684 RenderTableCell* cell = cs.primaryCell();
685 if (!cell || cs.inColSpan)
687 if (r < totalRows - 1 && cell == primaryCellAt(r + 1, c))
689 addOverflowFromChild(cell);
691 hasOverflowingCell |= cell->hasVisualOverflow();
693 if (cell->hasVisualOverflow() && !m_forceSlowPaintPathWithOverflowingCell) {
694 m_overflowingCells.add(cell);
695 if (m_overflowingCells.size() > maxAllowedOverflowingCellsCount) {
696 // We need to set m_forcesSlowPaintPath only if there is a least one overflowing cells as the hit testing code rely on this information.
697 m_forceSlowPaintPathWithOverflowingCell = true;
698 // The slow path does not make any use of the overflowing cells info, don't hold on to the memory.
699 m_overflowingCells.clear();
705 ASSERT(hasOverflowingCell == this->hasOverflowingCell());
711 LayoutUnit RenderTableSection::calcOuterBorderBefore() const
713 unsigned totalCols = table()->numEffCols();
714 if (!m_grid.size() || !totalCols)
717 unsigned borderWidth = 0;
719 const BorderValue& sb = style()->borderBefore();
720 if (sb.style() == BHIDDEN)
722 if (sb.style() > BHIDDEN)
723 borderWidth = sb.width();
725 const BorderValue& rb = firstChild()->style()->borderBefore();
726 if (rb.style() == BHIDDEN)
728 if (rb.style() > BHIDDEN && rb.width() > borderWidth)
729 borderWidth = rb.width();
731 bool allHidden = true;
732 for (unsigned c = 0; c < totalCols; c++) {
733 const CellStruct& current = cellAt(0, c);
734 if (current.inColSpan || !current.hasCells())
736 const BorderValue& cb = current.primaryCell()->style()->borderBefore(); // FIXME: Make this work with perpendicular and flipped cells.
737 // FIXME: Don't repeat for the same col group
738 RenderTableCol* colGroup = table()->colElement(c);
740 const BorderValue& gb = colGroup->style()->borderBefore();
741 if (gb.style() == BHIDDEN || cb.style() == BHIDDEN)
744 if (gb.style() > BHIDDEN && gb.width() > borderWidth)
745 borderWidth = gb.width();
746 if (cb.style() > BHIDDEN && cb.width() > borderWidth)
747 borderWidth = cb.width();
749 if (cb.style() == BHIDDEN)
752 if (cb.style() > BHIDDEN && cb.width() > borderWidth)
753 borderWidth = cb.width();
759 return borderWidth / 2;
762 LayoutUnit RenderTableSection::calcOuterBorderAfter() const
764 unsigned totalCols = table()->numEffCols();
765 if (!m_grid.size() || !totalCols)
768 unsigned borderWidth = 0;
770 const BorderValue& sb = style()->borderAfter();
771 if (sb.style() == BHIDDEN)
773 if (sb.style() > BHIDDEN)
774 borderWidth = sb.width();
776 const BorderValue& rb = lastChild()->style()->borderAfter();
777 if (rb.style() == BHIDDEN)
779 if (rb.style() > BHIDDEN && rb.width() > borderWidth)
780 borderWidth = rb.width();
782 bool allHidden = true;
783 for (unsigned c = 0; c < totalCols; c++) {
784 const CellStruct& current = cellAt(m_grid.size() - 1, c);
785 if (current.inColSpan || !current.hasCells())
787 const BorderValue& cb = current.primaryCell()->style()->borderAfter(); // FIXME: Make this work with perpendicular and flipped cells.
788 // FIXME: Don't repeat for the same col group
789 RenderTableCol* colGroup = table()->colElement(c);
791 const BorderValue& gb = colGroup->style()->borderAfter();
792 if (gb.style() == BHIDDEN || cb.style() == BHIDDEN)
795 if (gb.style() > BHIDDEN && gb.width() > borderWidth)
796 borderWidth = gb.width();
797 if (cb.style() > BHIDDEN && cb.width() > borderWidth)
798 borderWidth = cb.width();
800 if (cb.style() == BHIDDEN)
803 if (cb.style() > BHIDDEN && cb.width() > borderWidth)
804 borderWidth = cb.width();
810 return (borderWidth + 1) / 2;
813 LayoutUnit RenderTableSection::calcOuterBorderStart() const
815 unsigned totalCols = table()->numEffCols();
816 if (!m_grid.size() || !totalCols)
819 unsigned borderWidth = 0;
821 const BorderValue& sb = style()->borderStart();
822 if (sb.style() == BHIDDEN)
824 if (sb.style() > BHIDDEN)
825 borderWidth = sb.width();
827 if (RenderTableCol* colGroup = table()->colElement(0)) {
828 const BorderValue& gb = colGroup->style()->borderStart();
829 if (gb.style() == BHIDDEN)
831 if (gb.style() > BHIDDEN && gb.width() > borderWidth)
832 borderWidth = gb.width();
835 bool allHidden = true;
836 for (unsigned r = 0; r < m_grid.size(); r++) {
837 const CellStruct& current = cellAt(r, 0);
838 if (!current.hasCells())
840 // FIXME: Don't repeat for the same cell
841 const BorderValue& cb = current.primaryCell()->style()->borderStart(); // FIXME: Make this work with perpendicular and flipped cells.
842 const BorderValue& rb = current.primaryCell()->parent()->style()->borderStart();
843 if (cb.style() == BHIDDEN || rb.style() == BHIDDEN)
846 if (cb.style() > BHIDDEN && cb.width() > borderWidth)
847 borderWidth = cb.width();
848 if (rb.style() > BHIDDEN && rb.width() > borderWidth)
849 borderWidth = rb.width();
854 return (borderWidth + (table()->style()->isLeftToRightDirection() ? 0 : 1)) / 2;
857 LayoutUnit RenderTableSection::calcOuterBorderEnd() const
859 unsigned totalCols = table()->numEffCols();
860 if (!m_grid.size() || !totalCols)
863 unsigned borderWidth = 0;
865 const BorderValue& sb = style()->borderEnd();
866 if (sb.style() == BHIDDEN)
868 if (sb.style() > BHIDDEN)
869 borderWidth = sb.width();
871 if (RenderTableCol* colGroup = table()->colElement(totalCols - 1)) {
872 const BorderValue& gb = colGroup->style()->borderEnd();
873 if (gb.style() == BHIDDEN)
875 if (gb.style() > BHIDDEN && gb.width() > borderWidth)
876 borderWidth = gb.width();
879 bool allHidden = true;
880 for (unsigned r = 0; r < m_grid.size(); r++) {
881 const CellStruct& current = cellAt(r, totalCols - 1);
882 if (!current.hasCells())
884 // FIXME: Don't repeat for the same cell
885 const BorderValue& cb = current.primaryCell()->style()->borderEnd(); // FIXME: Make this work with perpendicular and flipped cells.
886 const BorderValue& rb = current.primaryCell()->parent()->style()->borderEnd();
887 if (cb.style() == BHIDDEN || rb.style() == BHIDDEN)
890 if (cb.style() > BHIDDEN && cb.width() > borderWidth)
891 borderWidth = cb.width();
892 if (rb.style() > BHIDDEN && rb.width() > borderWidth)
893 borderWidth = rb.width();
898 return (borderWidth + (table()->style()->isLeftToRightDirection() ? 1 : 0)) / 2;
901 void RenderTableSection::recalcOuterBorder()
903 m_outerBorderBefore = calcOuterBorderBefore();
904 m_outerBorderAfter = calcOuterBorderAfter();
905 m_outerBorderStart = calcOuterBorderStart();
906 m_outerBorderEnd = calcOuterBorderEnd();
909 LayoutUnit RenderTableSection::firstLineBoxBaseline() const
914 LayoutUnit firstLineBaseline = m_grid[0].baseline;
915 if (firstLineBaseline)
916 return firstLineBaseline + m_rowPos[0];
918 firstLineBaseline = -1;
919 const Row& firstRow = m_grid[0].row;
920 for (size_t i = 0; i < firstRow.size(); ++i) {
921 const CellStruct& cs = firstRow.at(i);
922 const RenderTableCell* cell = cs.primaryCell();
924 firstLineBaseline = max(firstLineBaseline, cell->logicalTop() + cell->paddingBefore() + cell->borderBefore() + cell->contentLogicalHeight());
927 return firstLineBaseline;
930 void RenderTableSection::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
932 // put this back in when all layout tests can handle it
933 // ASSERT(!needsLayout());
934 // avoid crashing on bugs that cause us to paint with dirty layout
938 unsigned totalRows = m_grid.size();
939 unsigned totalCols = table()->columns().size();
941 if (!totalRows || !totalCols)
944 LayoutPoint adjustedPaintOffset = paintOffset + location();
946 PaintPhase phase = paintInfo.phase;
947 bool pushedClip = pushContentsClip(paintInfo, adjustedPaintOffset);
948 paintObject(paintInfo, adjustedPaintOffset);
950 popContentsClip(paintInfo, phase, adjustedPaintOffset);
953 static inline bool compareCellPositions(RenderTableCell* elem1, RenderTableCell* elem2)
955 return elem1->row() < elem2->row();
958 // This comparison is used only when we have overflowing cells as we have an unsorted array to sort. We thus need
959 // to sort both on rows and columns to properly repaint.
960 static inline bool compareCellPositionsWithOverflowingCells(RenderTableCell* elem1, RenderTableCell* elem2)
962 if (elem1->row() != elem2->row())
963 return elem1->row() < elem2->row();
965 return elem1->col() < elem2->col();
968 void RenderTableSection::paintCell(RenderTableCell* cell, PaintInfo& paintInfo, const LayoutPoint& paintOffset)
970 LayoutPoint cellPoint = flipForWritingModeForChild(cell, paintOffset);
971 PaintPhase paintPhase = paintInfo.phase;
972 RenderTableRow* row = toRenderTableRow(cell->parent());
974 if (paintPhase == PaintPhaseBlockBackground || paintPhase == PaintPhaseChildBlockBackground) {
975 // We need to handle painting a stack of backgrounds. This stack (from bottom to top) consists of
976 // the column group, column, row group, row, and then the cell.
977 RenderObject* col = table()->colElement(cell->col());
978 RenderObject* colGroup = 0;
979 if (col && col->parent()->style()->display() == TABLE_COLUMN_GROUP)
980 colGroup = col->parent();
982 // Column groups and columns first.
983 // FIXME: Columns and column groups do not currently support opacity, and they are being painted "too late" in
984 // the stack, since we have already opened a transparency layer (potentially) for the table row group.
985 // Note that we deliberately ignore whether or not the cell has a layer, since these backgrounds paint "behind" the
987 cell->paintBackgroundsBehindCell(paintInfo, cellPoint, colGroup);
988 cell->paintBackgroundsBehindCell(paintInfo, cellPoint, col);
990 // Paint the row group next.
991 cell->paintBackgroundsBehindCell(paintInfo, cellPoint, this);
993 // Paint the row next, but only if it doesn't have a layer. If a row has a layer, it will be responsible for
994 // painting the row background for the cell.
995 if (!row->hasSelfPaintingLayer())
996 cell->paintBackgroundsBehindCell(paintInfo, cellPoint, row);
998 if ((!cell->hasSelfPaintingLayer() && !row->hasSelfPaintingLayer()) || paintInfo.phase == PaintPhaseCollapsedTableBorders)
999 cell->paint(paintInfo, cellPoint);
1002 void RenderTableSection::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1004 // Check which rows and cols are visible and only paint these.
1005 unsigned totalRows = m_grid.size();
1006 unsigned totalCols = table()->columns().size();
1008 PaintPhase paintPhase = paintInfo.phase;
1010 LayoutUnit os = 2 * maximalOutlineSize(paintPhase);
1011 unsigned startrow = 0;
1012 unsigned endrow = totalRows;
1014 LayoutRect localRepaintRect = paintInfo.rect;
1015 localRepaintRect.moveBy(-paintOffset);
1016 if (style()->isFlippedBlocksWritingMode()) {
1017 if (style()->isHorizontalWritingMode())
1018 localRepaintRect.setY(height() - localRepaintRect.maxY());
1020 localRepaintRect.setX(width() - localRepaintRect.maxX());
1023 if (!m_forceSlowPaintPathWithOverflowingCell) {
1024 LayoutUnit before = (style()->isHorizontalWritingMode() ? localRepaintRect.y() : localRepaintRect.x()) - os;
1025 // binary search to find a row
1026 startrow = std::lower_bound(m_rowPos.begin(), m_rowPos.end(), before) - m_rowPos.begin();
1028 // The binary search above gives us the first row with
1029 // a y position >= the top of the paint rect. Thus, the previous
1030 // may need to be repainted as well.
1031 if (startrow == m_rowPos.size() || (startrow > 0 && (m_rowPos[startrow] > before)))
1034 LayoutUnit after = (style()->isHorizontalWritingMode() ? localRepaintRect.maxY() : localRepaintRect.maxX()) + os;
1035 endrow = std::lower_bound(m_rowPos.begin(), m_rowPos.end(), after) - m_rowPos.begin();
1036 if (endrow == m_rowPos.size())
1039 if (!endrow && m_rowPos[0] - table()->outerBorderBefore() <= after)
1043 unsigned startcol = 0;
1044 unsigned endcol = totalCols;
1045 // FIXME: Implement RTL.
1046 if (!m_forceSlowPaintPathWithOverflowingCell && style()->isLeftToRightDirection()) {
1047 LayoutUnit start = (style()->isHorizontalWritingMode() ? localRepaintRect.x() : localRepaintRect.y()) - os;
1048 Vector<LayoutUnit>& columnPos = table()->columnPositions();
1049 startcol = std::lower_bound(columnPos.begin(), columnPos.end(), start) - columnPos.begin();
1050 if ((startcol == columnPos.size()) || (startcol > 0 && (columnPos[startcol] > start)))
1053 LayoutUnit end = (style()->isHorizontalWritingMode() ? localRepaintRect.maxX() : localRepaintRect.maxY()) + os;
1054 endcol = std::lower_bound(columnPos.begin(), columnPos.end(), end) - columnPos.begin();
1055 if (endcol == columnPos.size())
1058 if (!endcol && columnPos[0] - table()->outerBorderStart() <= end)
1061 if (startcol < endcol) {
1062 if (!m_hasMultipleCellLevels && !m_overflowingCells.size()) {
1063 // Draw the dirty cells in the order that they appear.
1064 for (unsigned r = startrow; r < endrow; r++) {
1065 for (unsigned c = startcol; c < endcol; c++) {
1066 CellStruct& current = cellAt(r, c);
1067 RenderTableCell* cell = current.primaryCell();
1068 if (!cell || (r > startrow && primaryCellAt(r - 1, c) == cell) || (c > startcol && primaryCellAt(r, c - 1) == cell))
1070 paintCell(cell, paintInfo, paintOffset);
1074 // The overflowing cells should be scarce to avoid adding a lot of cells to the HashSet.
1075 ASSERT(m_overflowingCells.size() < totalRows * totalCols * gMaxAllowedOverflowingCellRatioForFastPaintPath);
1077 // To make sure we properly repaint the section, we repaint all the overflowing cells that we collected.
1078 Vector<RenderTableCell*> cells;
1079 copyToVector(m_overflowingCells, cells);
1081 HashSet<RenderTableCell*> spanningCells;
1083 for (unsigned r = startrow; r < endrow; r++) {
1084 for (unsigned c = startcol; c < endcol; c++) {
1085 CellStruct& current = cellAt(r, c);
1086 if (!current.hasCells())
1088 for (unsigned i = 0; i < current.cells.size(); ++i) {
1089 if (m_overflowingCells.contains(current.cells[i]))
1092 if (current.cells[i]->rowSpan() > 1 || current.cells[i]->colSpan() > 1) {
1093 if (spanningCells.contains(current.cells[i]))
1095 spanningCells.add(current.cells[i]);
1098 cells.append(current.cells[i]);
1103 // Sort the dirty cells by paint order.
1104 if (!m_overflowingCells.size())
1105 std::stable_sort(cells.begin(), cells.end(), compareCellPositions);
1107 std::sort(cells.begin(), cells.end(), compareCellPositionsWithOverflowingCells);
1109 for (unsigned i = 0; i < cells.size(); ++i)
1110 paintCell(cells[i], paintInfo, paintOffset);
1115 void RenderTableSection::imageChanged(WrappedImagePtr, const IntRect*)
1117 // FIXME: Examine cells and repaint only the rect the image paints in.
1121 void RenderTableSection::recalcCells()
1123 ASSERT(m_needsCellRecalc);
1124 // We reset the flag here to ensure that |addCell| works. This is safe to do as
1125 // fillRowsWithDefaultStartingAtPosition makes sure we match the table's columns
1127 m_needsCellRecalc = false;
1133 for (RenderObject* row = firstChild(); row; row = row->nextSibling()) {
1134 if (row->isTableRow()) {
1135 unsigned insertionRow = m_cRow;
1140 RenderTableRow* tableRow = toRenderTableRow(row);
1141 m_grid[insertionRow].rowRenderer = tableRow;
1142 setRowLogicalHeightToRowStyleLogicalHeightIfNotRelative(m_grid[insertionRow]);
1144 for (RenderObject* cell = row->firstChild(); cell; cell = cell->nextSibling()) {
1145 if (!cell->isTableCell())
1148 RenderTableCell* tableCell = toRenderTableCell(cell);
1149 addCell(tableCell, tableRow);
1154 m_grid.shrinkToFit();
1155 setNeedsLayout(true);
1158 void RenderTableSection::rowLogicalHeightChanged(unsigned rowIndex)
1160 setRowLogicalHeightToRowStyleLogicalHeightIfNotRelative(m_grid[rowIndex]);
1163 void RenderTableSection::setNeedsCellRecalc()
1165 m_needsCellRecalc = true;
1166 if (RenderTable* t = table())
1167 t->setNeedsSectionRecalc();
1170 unsigned RenderTableSection::numColumns() const
1172 unsigned result = 0;
1174 for (unsigned r = 0; r < m_grid.size(); ++r) {
1175 for (unsigned c = result; c < table()->numEffCols(); ++c) {
1176 const CellStruct& cell = cellAt(r, c);
1177 if (cell.hasCells() || cell.inColSpan)
1185 void RenderTableSection::appendColumn(unsigned pos)
1187 ASSERT(!m_needsCellRecalc);
1189 for (unsigned row = 0; row < m_grid.size(); ++row)
1190 m_grid[row].row.resize(pos + 1);
1193 void RenderTableSection::splitColumn(unsigned pos, unsigned first)
1195 ASSERT(!m_needsCellRecalc);
1199 for (unsigned row = 0; row < m_grid.size(); ++row) {
1200 Row& r = m_grid[row].row;
1201 r.insert(pos + 1, CellStruct());
1202 if (r[pos].hasCells()) {
1203 r[pos + 1].cells.append(r[pos].cells);
1204 RenderTableCell* cell = r[pos].primaryCell();
1206 ASSERT(cell->colSpan() >= (r[pos].inColSpan ? 1 : 0));
1207 unsigned colleft = cell->colSpan() - r[pos].inColSpan;
1208 if (first > colleft)
1209 r[pos + 1].inColSpan = 0;
1211 r[pos + 1].inColSpan = first + r[pos].inColSpan;
1213 r[pos + 1].inColSpan = 0;
1219 bool RenderTableSection::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
1221 // If we have no children then we have nothing to do.
1225 // Table sections cannot ever be hit tested. Effectively they do not exist.
1226 // Just forward to our children always.
1227 LayoutPoint adjustedLocation = accumulatedOffset + location();
1229 if (hasOverflowClip() && !overflowClipRect(adjustedLocation, result.region()).intersects(result.rectForPoint(pointInContainer)))
1232 if (hasOverflowingCell()) {
1233 for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
1234 // FIXME: We have to skip over inline flows, since they can show up inside table rows
1235 // at the moment (a demoted inline <form> for example). If we ever implement a
1236 // table-specific hit-test method (which we should do for performance reasons anyway),
1237 // then we can remove this check.
1238 if (child->isBox() && !toRenderBox(child)->hasSelfPaintingLayer()) {
1239 LayoutPoint childPoint = flipForWritingModeForChild(toRenderBox(child), adjustedLocation);
1240 if (child->nodeAtPoint(request, result, pointInContainer, childPoint, action)) {
1241 updateHitTestResult(result, toLayoutPoint(pointInContainer - childPoint));
1249 LayoutPoint location = pointInContainer - toLayoutSize(adjustedLocation);
1250 if (style()->isFlippedBlocksWritingMode()) {
1251 if (style()->isHorizontalWritingMode())
1252 location.setY(height() - location.y());
1254 location.setX(width() - location.x());
1257 LayoutUnit offsetInColumnDirection = style()->isHorizontalWritingMode() ? location.y() : location.x();
1258 // Find the first row that starts after offsetInColumnDirection.
1259 unsigned nextRow = std::upper_bound(m_rowPos.begin(), m_rowPos.end(), offsetInColumnDirection) - m_rowPos.begin();
1260 if (nextRow == m_rowPos.size())
1262 // Now set hitRow to the index of the hit row, or 0.
1263 unsigned hitRow = nextRow > 0 ? nextRow - 1 : 0;
1265 Vector<LayoutUnit>& columnPos = table()->columnPositions();
1266 LayoutUnit offsetInRowDirection = style()->isHorizontalWritingMode() ? location.x() : location.y();
1267 if (!style()->isLeftToRightDirection())
1268 offsetInRowDirection = columnPos[columnPos.size() - 1] - offsetInRowDirection;
1270 unsigned nextColumn = std::lower_bound(columnPos.begin(), columnPos.end(), offsetInRowDirection) - columnPos.begin();
1271 if (nextColumn == columnPos.size())
1273 unsigned hitColumn = nextColumn > 0 ? nextColumn - 1 : 0;
1275 CellStruct& current = cellAt(hitRow, hitColumn);
1277 // If the cell is empty, there's nothing to do
1278 if (!current.hasCells())
1281 for (unsigned i = current.cells.size() ; i; ) {
1283 RenderTableCell* cell = current.cells[i];
1284 LayoutPoint cellPoint = flipForWritingModeForChild(cell, adjustedLocation);
1285 if (static_cast<RenderObject*>(cell)->nodeAtPoint(request, result, pointInContainer, cellPoint, action)) {
1286 updateHitTestResult(result, toLayoutPoint(pointInContainer - cellPoint));
1294 unsigned RenderTableSection::rowIndexForRenderer(const RenderTableRow* row) const
1296 for (size_t i = 0; i < m_grid.size(); ++i) {
1297 if (m_grid[i].rowRenderer == row)
1300 ASSERT_NOT_REACHED();
1304 } // namespace WebCore