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 && row->rowRenderer);
54 row->logicalHeight = row->rowRenderer->style()->logicalHeight();
55 if (row->logicalHeight.isRelative())
56 row->logicalHeight = Length();
59 RenderTableSection::RenderTableSection(Node* node)
64 , m_outerBorderStart(0)
66 , m_outerBorderBefore(0)
67 , m_outerBorderAfter(0)
68 , m_needsCellRecalc(false)
69 , m_hasMultipleCellLevels(false)
71 // init RenderObject attributes
72 setInline(false); // our object is not Inline
75 RenderTableSection::~RenderTableSection()
80 void RenderTableSection::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
82 RenderBox::styleDidChange(diff, oldStyle);
83 propagateStyleToAnonymousChildren();
86 void RenderTableSection::willBeDestroyed()
88 RenderTable* recalcTable = table();
90 RenderBox::willBeDestroyed();
92 // recalc cell info because RenderTable has unguarded pointers
93 // stored that point to this RenderTableSection.
95 recalcTable->setNeedsSectionRecalc();
98 void RenderTableSection::addChild(RenderObject* child, RenderObject* beforeChild)
100 // Make sure we don't append things after :after-generated content if we have it.
101 if (!beforeChild && isAfterContent(lastChild()))
102 beforeChild = lastChild();
104 if (!child->isTableRow()) {
105 RenderObject* last = beforeChild;
108 if (last && last->isAnonymous() && !last->isBeforeOrAfterContent()) {
109 if (beforeChild == last)
110 beforeChild = last->firstChild();
111 last->addChild(child, beforeChild);
115 // If beforeChild is inside an anonymous cell/row, insert into the cell or into
116 // the anonymous row containing it, if there is one.
117 RenderObject* lastBox = last;
118 while (lastBox && lastBox->parent()->isAnonymous() && !lastBox->isTableRow())
119 lastBox = lastBox->parent();
120 if (lastBox && lastBox->isAnonymous() && !lastBox->isBeforeOrAfterContent()) {
121 lastBox->addChild(child, beforeChild);
125 RenderObject* row = new (renderArena()) RenderTableRow(document() /* anonymous table row */);
126 RefPtr<RenderStyle> newStyle = RenderStyle::create();
127 newStyle->inheritFrom(style());
128 newStyle->setDisplay(TABLE_ROW);
129 row->setStyle(newStyle.release());
130 addChild(row, beforeChild);
131 row->addChild(child);
136 setNeedsCellRecalc();
141 // make sure we have enough rows
142 if (!ensureRows(m_cRow + 1))
145 m_grid[m_cRow].rowRenderer = toRenderTableRow(child);
148 setRowLogicalHeightToRowStyleLogicalHeightIfNotRelative(&m_grid[m_cRow]);
150 // If the next renderer is actually wrapped in an anonymous table row, we need to go up and find that.
151 while (beforeChild && beforeChild->parent() != this)
152 beforeChild = beforeChild->parent();
154 ASSERT(!beforeChild || beforeChild->isTableRow());
155 RenderBox::addChild(child, beforeChild);
156 toRenderTableRow(child)->updateBeforeAndAfterContent();
159 void RenderTableSection::removeChild(RenderObject* oldChild)
161 setNeedsCellRecalc();
162 RenderBox::removeChild(oldChild);
165 bool RenderTableSection::ensureRows(int numRows)
167 int nRows = m_gridRows;
168 if (numRows > nRows) {
169 if (numRows > static_cast<int>(m_grid.size())) {
170 size_t maxSize = numeric_limits<size_t>::max() / sizeof(RowStruct);
171 if (static_cast<size_t>(numRows) > maxSize)
173 m_grid.grow(numRows);
175 m_gridRows = numRows;
176 int nCols = max(1, table()->numEffCols());
177 for (int r = nRows; r < numRows; r++) {
178 m_grid[r].row = new Row(nCols);
179 m_grid[r].rowRenderer = 0;
180 m_grid[r].baseline = 0;
181 m_grid[r].logicalHeight = Length();
188 void RenderTableSection::addCell(RenderTableCell* cell, RenderTableRow* row)
190 int rSpan = cell->rowSpan();
191 int cSpan = cell->colSpan();
192 Vector<RenderTable::ColumnStruct>& columns = table()->columns();
193 int nCols = columns.size();
195 // ### mozilla still seems to do the old HTML way, even for strict DTD
196 // (see the annotation on table cell layouting in the CSS specs and the testcase below:
198 // <TR><TD>1 <TD rowspan="2">2 <TD>3 <TD>4
199 // <TR><TD colspan="2">5
201 while (m_cCol < nCols && (cellAt(m_cRow, m_cCol).hasCells() || cellAt(m_cRow, m_cCol).inColSpan))
205 // we ignore height settings on rowspan cells
206 Length logicalHeight = cell->style()->logicalHeight();
207 if (logicalHeight.isPositive() || (logicalHeight.isRelative() && logicalHeight.value() >= 0)) {
208 Length cRowLogicalHeight = m_grid[m_cRow].logicalHeight;
209 switch (logicalHeight.type()) {
211 if (!(cRowLogicalHeight.isPercent()) ||
212 (cRowLogicalHeight.isPercent() && cRowLogicalHeight.percent() < logicalHeight.percent()))
213 m_grid[m_cRow].logicalHeight = logicalHeight;
216 if (cRowLogicalHeight.type() < Percent ||
217 (cRowLogicalHeight.isFixed() && cRowLogicalHeight.value() < logicalHeight.value()))
218 m_grid[m_cRow].logicalHeight = logicalHeight;
227 // make sure we have enough rows
228 if (!ensureRows(m_cRow + rSpan))
231 m_grid[m_cRow].rowRenderer = row;
234 // tell the cell where it is
235 bool inColSpan = false;
238 if (m_cCol >= nCols) {
239 table()->appendColumn(cSpan);
242 if (cSpan < (int)columns[m_cCol].span)
243 table()->splitColumn(m_cCol, cSpan);
244 currentSpan = columns[m_cCol].span;
246 for (int r = 0; r < rSpan; r++) {
247 CellStruct& c = cellAt(m_cRow + r, m_cCol);
249 c.cells.append(cell);
250 // If cells overlap then we take the slow path for painting.
251 if (c.cells.size() > 1)
252 m_hasMultipleCellLevels = true;
257 cSpan -= currentSpan;
260 cell->setRow(m_cRow);
261 cell->setCol(table()->effColToCol(col));
264 void RenderTableSection::setCellLogicalWidths()
266 Vector<LayoutUnit>& columnPos = table()->columnPositions();
268 LayoutStateMaintainer statePusher(view());
270 for (int i = 0; i < m_gridRows; i++) {
271 Row& row = *m_grid[i].row;
272 int cols = row.size();
273 for (int j = 0; j < cols; j++) {
274 CellStruct& current = row[j];
275 RenderTableCell* cell = current.primaryCell();
276 if (!cell || current.inColSpan)
279 int cspan = cell->colSpan();
280 while (cspan && endCol < cols) {
281 ASSERT(endCol < (int)table()->columns().size());
282 cspan -= table()->columns()[endCol].span;
285 int w = columnPos[endCol] - columnPos[j] - table()->hBorderSpacing();
286 int oldLogicalWidth = cell->logicalWidth();
287 if (w != oldLogicalWidth) {
288 cell->setNeedsLayout(true);
289 if (!table()->selfNeedsLayout() && cell->checkForRepaintDuringLayout()) {
290 if (!statePusher.didPush()) {
291 // Technically, we should also push state for the row, but since
292 // rows don't push a coordinate transform, that's not necessary.
293 statePusher.push(this, IntSize(x(), y()));
297 cell->updateLogicalWidth(w);
302 statePusher.pop(); // only pops if we pushed
305 LayoutUnit RenderTableSection::calcRowLogicalHeight()
308 setNeedsLayoutIsForbidden(true);
311 ASSERT(!needsLayout());
313 RenderTableCell* cell;
315 LayoutUnit spacing = table()->vBorderSpacing();
317 LayoutStateMaintainer statePusher(view());
319 m_rowPos.resize(m_gridRows + 1);
320 m_rowPos[0] = spacing;
322 for (int r = 0; r < m_gridRows; r++) {
324 m_grid[r].baseline = 0;
325 LayoutUnit baseline = 0;
326 LayoutUnit bdesc = 0;
327 LayoutUnit ch = m_grid[r].logicalHeight.calcMinValue(0);
328 LayoutUnit pos = m_rowPos[r] + ch + (m_grid[r].rowRenderer ? spacing : 0);
330 m_rowPos[r + 1] = max(m_rowPos[r + 1], pos);
332 Row* row = m_grid[r].row;
333 int totalCols = row->size();
335 for (int c = 0; c < totalCols; c++) {
336 CellStruct& current = cellAt(r, c);
337 cell = current.primaryCell();
339 if (!cell || current.inColSpan)
342 if ((cell->row() + cell->rowSpan() - 1) > r)
345 int indx = max(r - cell->rowSpan() + 1, 0);
347 if (cell->hasOverrideHeight()) {
348 if (!statePusher.didPush()) {
349 // Technically, we should also push state for the row, but since
350 // rows don't push a coordinate transform, that's not necessary.
351 statePusher.push(this, locationOffset());
353 cell->clearIntrinsicPadding();
354 cell->clearOverrideSize();
355 cell->setChildNeedsLayout(true, false);
356 cell->layoutIfNeeded();
359 LayoutUnit adjustedPaddingBefore = cell->paddingBefore() - cell->intrinsicPaddingBefore();
360 LayoutUnit adjustedPaddingAfter = cell->paddingAfter() - cell->intrinsicPaddingAfter();
361 LayoutUnit adjustedLogicalHeight = cell->logicalHeight() - (cell->intrinsicPaddingBefore() + cell->intrinsicPaddingAfter());
363 // Explicit heights use the border box in quirks mode. In strict mode do the right
364 // thing and actually add in the border and padding.
365 ch = cell->style()->logicalHeight().calcValue(0) +
366 (document()->inQuirksMode() ? 0 : (adjustedPaddingBefore + adjustedPaddingAfter +
367 cell->borderBefore() + cell->borderAfter()));
368 ch = max(ch, adjustedLogicalHeight);
370 pos = m_rowPos[indx] + ch + (m_grid[r].rowRenderer ? spacing : 0);
372 m_rowPos[r + 1] = max(m_rowPos[r + 1], pos);
374 // find out the baseline
375 EVerticalAlign va = cell->style()->verticalAlign();
376 if (va == BASELINE || va == TEXT_BOTTOM || va == TEXT_TOP || va == SUPER || va == SUB) {
377 LayoutUnit b = cell->cellBaselinePosition();
378 if (b > cell->borderBefore() + cell->paddingBefore()) {
379 baseline = max(baseline, b - cell->intrinsicPaddingBefore());
380 bdesc = max(bdesc, m_rowPos[indx] + ch - (b - cell->intrinsicPaddingBefore()));
385 // do we have baseline aligned elements?
387 // increase rowheight if baseline requires
388 m_rowPos[r + 1] = max(m_rowPos[r + 1], baseline + bdesc + (m_grid[r].rowRenderer ? spacing : 0));
389 m_grid[r].baseline = baseline;
392 m_rowPos[r + 1] = max(m_rowPos[r + 1], m_rowPos[r]);
396 setNeedsLayoutIsForbidden(false);
399 ASSERT(!needsLayout());
403 return m_rowPos[m_gridRows];
406 void RenderTableSection::layout()
408 ASSERT(needsLayout());
410 LayoutStateMaintainer statePusher(view(), this, locationOffset(), style()->isFlippedBlocksWritingMode());
411 for (RenderObject* child = children()->firstChild(); child; child = child->nextSibling()) {
412 if (child->isTableRow()) {
413 child->layoutIfNeeded();
414 ASSERT(!child->needsLayout());
418 setNeedsLayout(false);
421 LayoutUnit RenderTableSection::layoutRows(LayoutUnit toAdd)
424 setNeedsLayoutIsForbidden(true);
427 ASSERT(!needsLayout());
431 int totalRows = m_gridRows;
433 // Set the width of our section now. The rows will also be this width.
434 setLogicalWidth(table()->contentLogicalWidth());
436 m_overflowingCells.clear();
437 m_forceSlowPaintPathWithOverflowingCell = false;
439 if (toAdd && totalRows && (m_rowPos[totalRows] || !nextSibling())) {
440 LayoutUnit totalHeight = m_rowPos[totalRows] + toAdd;
442 LayoutUnit dh = toAdd;
443 int totalPercent = 0;
445 for (int r = 0; r < totalRows; r++) {
446 if (m_grid[r].logicalHeight.isAuto())
448 else if (m_grid[r].logicalHeight.isPercent())
449 totalPercent += m_grid[r].logicalHeight.percent();
452 // try to satisfy percent
454 totalPercent = min(totalPercent, 100);
455 int rh = m_rowPos[1] - m_rowPos[0];
456 for (int r = 0; r < totalRows; r++) {
457 if (totalPercent > 0 && m_grid[r].logicalHeight.isPercent()) {
458 LayoutUnit toAdd = min(dh, static_cast<LayoutUnit>((totalHeight * m_grid[r].logicalHeight.percent() / 100) - rh));
459 // If toAdd is negative, then we don't want to shrink the row (this bug
460 // affected Outlook Web Access).
461 toAdd = max<LayoutUnit>(0, toAdd);
464 totalPercent -= m_grid[r].logicalHeight.percent();
466 if (r < totalRows - 1)
467 rh = m_rowPos[r + 2] - m_rowPos[r + 1];
468 m_rowPos[r + 1] += add;
472 // distribute over variable cols
474 for (int r = 0; r < totalRows; r++) {
475 if (numAuto > 0 && m_grid[r].logicalHeight.isAuto()) {
476 LayoutUnit toAdd = dh / numAuto;
481 m_rowPos[r + 1] += add;
484 if (dh > 0 && m_rowPos[totalRows]) {
485 // if some left overs, distribute equally.
486 LayoutUnit tot = m_rowPos[totalRows];
488 LayoutUnit prev = m_rowPos[0];
489 for (int r = 0; r < totalRows; r++) {
490 // weight with the original height
491 add += dh * (m_rowPos[r + 1] - prev) / tot;
492 prev = m_rowPos[r + 1];
493 m_rowPos[r + 1] += add;
498 LayoutUnit hspacing = table()->hBorderSpacing();
499 LayoutUnit vspacing = table()->vBorderSpacing();
500 LayoutUnit nEffCols = table()->numEffCols();
502 LayoutStateMaintainer statePusher(view(), this, LayoutSize(x(), y()), style()->isFlippedBlocksWritingMode());
504 for (int r = 0; r < totalRows; r++) {
505 // Set the row's x/y position and width/height.
506 if (RenderTableRow* rowRenderer = m_grid[r].rowRenderer) {
507 rowRenderer->setLocation(LayoutPoint(0, m_rowPos[r]));
508 rowRenderer->setLogicalWidth(logicalWidth());
509 rowRenderer->setLogicalHeight(m_rowPos[r + 1] - m_rowPos[r] - vspacing);
510 rowRenderer->updateLayerTransform();
513 for (int c = 0; c < nEffCols; c++) {
514 CellStruct& cs = cellAt(r, c);
515 RenderTableCell* cell = cs.primaryCell();
517 if (!cell || cs.inColSpan)
521 rHeight = m_rowPos[rindx + cell->rowSpan()] - m_rowPos[rindx] - vspacing;
523 // Force percent height children to lay themselves out again.
524 // This will cause these children to grow to fill the cell.
525 // FIXME: There is still more work to do here to fully match WinIE (should
526 // it become necessary to do so). In quirks mode, WinIE behaves like we
527 // do, but it will clip the cells that spill out of the table section. In
528 // strict mode, Mozilla and WinIE both regrow the table to accommodate the
529 // new height of the cell (thus letting the percentages cause growth one
530 // time only). We may also not be handling row-spanning cells correctly.
532 // Note also the oddity where replaced elements always flex, and yet blocks/tables do
533 // not necessarily flex. WinIE is crazy and inconsistent, and we can't hope to
534 // match the behavior perfectly, but we'll continue to refine it as we discover new
536 bool cellChildrenFlex = false;
537 bool flexAllChildren = cell->style()->logicalHeight().isFixed()
538 || (!table()->style()->logicalHeight().isAuto() && rHeight != cell->logicalHeight());
540 for (RenderObject* o = cell->firstChild(); o; o = o->nextSibling()) {
541 if (!o->isText() && o->style()->logicalHeight().isPercent() && (flexAllChildren || o->isReplaced() || (o->isBox() && toRenderBox(o)->scrollsOverflow()))) {
542 // Tables with no sections do not flex.
543 if (!o->isTable() || toRenderTable(o)->hasSections()) {
544 o->setNeedsLayout(true, false);
545 cellChildrenFlex = true;
550 if (HashSet<RenderBox*>* percentHeightDescendants = cell->percentHeightDescendants()) {
551 HashSet<RenderBox*>::iterator end = percentHeightDescendants->end();
552 for (HashSet<RenderBox*>::iterator it = percentHeightDescendants->begin(); it != end; ++it) {
553 RenderBox* box = *it;
554 if (!box->isReplaced() && !box->scrollsOverflow() && !flexAllChildren)
557 while (box != cell) {
558 if (box->normalChildNeedsLayout())
560 box->setChildNeedsLayout(true, false);
561 box = box->containingBlock();
566 cellChildrenFlex = true;
570 if (cellChildrenFlex) {
571 cell->setChildNeedsLayout(true, false);
572 // Alignment within a cell is based off the calculated
573 // height, which becomes irrelevant once the cell has
574 // been resized based off its percentage.
575 cell->setOverrideHeightFromRowHeight(rHeight);
576 cell->layoutIfNeeded();
578 // If the baseline moved, we may have to update the data for our row. Find out the new baseline.
579 EVerticalAlign va = cell->style()->verticalAlign();
580 if (va == BASELINE || va == TEXT_BOTTOM || va == TEXT_TOP || va == SUPER || va == SUB) {
581 LayoutUnit baseline = cell->cellBaselinePosition();
582 if (baseline > cell->borderBefore() + cell->paddingBefore())
583 m_grid[r].baseline = max(m_grid[r].baseline, baseline);
587 LayoutUnit oldIntrinsicPaddingBefore = cell->intrinsicPaddingBefore();
588 LayoutUnit oldIntrinsicPaddingAfter = cell->intrinsicPaddingAfter();
589 LayoutUnit logicalHeightWithoutIntrinsicPadding = cell->logicalHeight() - oldIntrinsicPaddingBefore - oldIntrinsicPaddingAfter;
591 LayoutUnit intrinsicPaddingBefore = 0;
592 switch (cell->style()->verticalAlign()) {
598 LayoutUnit b = cell->cellBaselinePosition();
599 if (b > cell->borderBefore() + cell->paddingBefore())
600 intrinsicPaddingBefore = getBaseline(r) - (b - oldIntrinsicPaddingBefore);
606 intrinsicPaddingBefore = (rHeight - logicalHeightWithoutIntrinsicPadding) / 2;
609 intrinsicPaddingBefore = rHeight - logicalHeightWithoutIntrinsicPadding;
615 LayoutUnit intrinsicPaddingAfter = rHeight - logicalHeightWithoutIntrinsicPadding - intrinsicPaddingBefore;
616 cell->setIntrinsicPaddingBefore(intrinsicPaddingBefore);
617 cell->setIntrinsicPaddingAfter(intrinsicPaddingAfter);
619 LayoutRect oldCellRect(cell->x(), cell->y() , cell->width(), cell->height());
621 LayoutPoint cellLocation(0, m_rowPos[rindx]);
622 if (!style()->isLeftToRightDirection())
623 cellLocation.setX(table()->columnPositions()[nEffCols] - table()->columnPositions()[table()->colToEffCol(cell->col() + cell->colSpan())] + hspacing);
625 cellLocation.setX(table()->columnPositions()[c] + hspacing);
626 cell->setLogicalLocation(cellLocation);
627 view()->addLayoutDelta(oldCellRect.location() - cell->location());
629 if (intrinsicPaddingBefore != oldIntrinsicPaddingBefore || intrinsicPaddingAfter != oldIntrinsicPaddingAfter)
630 cell->setNeedsLayout(true, false);
632 if (!cell->needsLayout() && view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(cell->logicalTop()) != cell->pageLogicalOffset())
633 cell->setChildNeedsLayout(true, false);
635 cell->layoutIfNeeded();
637 // FIXME: Make pagination work with vertical tables.
638 if (style()->isHorizontalWritingMode() && view()->layoutState()->pageLogicalHeight() && cell->height() != rHeight)
639 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.
641 LayoutSize childOffset(cell->location() - oldCellRect.location());
642 if (childOffset.width() || childOffset.height()) {
643 view()->addLayoutDelta(childOffset);
645 // If the child moved, we have to repaint it as well as any floating/positioned
646 // descendants. An exception is if we need a layout. In this case, we know we're going to
647 // repaint ourselves (and the child) anyway.
648 if (!table()->selfNeedsLayout() && cell->checkForRepaintDuringLayout())
649 cell->repaintDuringLayoutIfMoved(oldCellRect);
655 setNeedsLayoutIsForbidden(false);
658 ASSERT(!needsLayout());
660 setLogicalHeight(m_rowPos[totalRows]);
662 unsigned totalCellsCount = nEffCols * totalRows;
663 int maxAllowedOverflowingCellsCount = totalCellsCount < gMinTableSizeToUseFastPaintPathWithOverflowingCell ? 0 : gMaxAllowedOverflowingCellRatioForFastPaintPath * totalCellsCount;
666 bool hasOverflowingCell = false;
668 // Now that our height has been determined, add in overflow from cells.
669 for (int r = 0; r < totalRows; r++) {
670 for (int c = 0; c < nEffCols; c++) {
671 CellStruct& cs = cellAt(r, c);
672 RenderTableCell* cell = cs.primaryCell();
673 if (!cell || cs.inColSpan)
675 if (r < totalRows - 1 && cell == primaryCellAt(r + 1, c))
677 addOverflowFromChild(cell);
679 hasOverflowingCell |= cell->hasVisualOverflow();
681 if (cell->hasVisualOverflow() && !m_forceSlowPaintPathWithOverflowingCell) {
682 m_overflowingCells.add(cell);
683 if (m_overflowingCells.size() > maxAllowedOverflowingCellsCount) {
684 // We need to set m_forcesSlowPaintPath only if there is a least one overflowing cells as the hit testing code rely on this information.
685 m_forceSlowPaintPathWithOverflowingCell = true;
686 // The slow path does not make any use of the overflowing cells info, don't hold on to the memory.
687 m_overflowingCells.clear();
693 ASSERT(hasOverflowingCell == this->hasOverflowingCell());
699 LayoutUnit RenderTableSection::calcOuterBorderBefore() const
701 int totalCols = table()->numEffCols();
702 if (!m_gridRows || !totalCols)
705 unsigned borderWidth = 0;
707 const BorderValue& sb = style()->borderBefore();
708 if (sb.style() == BHIDDEN)
710 if (sb.style() > BHIDDEN)
711 borderWidth = sb.width();
713 const BorderValue& rb = firstChild()->style()->borderBefore();
714 if (rb.style() == BHIDDEN)
716 if (rb.style() > BHIDDEN && rb.width() > borderWidth)
717 borderWidth = rb.width();
719 bool allHidden = true;
720 for (int c = 0; c < totalCols; c++) {
721 const CellStruct& current = cellAt(0, c);
722 if (current.inColSpan || !current.hasCells())
724 const BorderValue& cb = current.primaryCell()->style()->borderBefore(); // FIXME: Make this work with perpendicular and flipped cells.
725 // FIXME: Don't repeat for the same col group
726 RenderTableCol* colGroup = table()->colElement(c);
728 const BorderValue& gb = colGroup->style()->borderBefore();
729 if (gb.style() == BHIDDEN || cb.style() == BHIDDEN)
732 if (gb.style() > BHIDDEN && gb.width() > borderWidth)
733 borderWidth = gb.width();
734 if (cb.style() > BHIDDEN && cb.width() > borderWidth)
735 borderWidth = cb.width();
737 if (cb.style() == BHIDDEN)
740 if (cb.style() > BHIDDEN && cb.width() > borderWidth)
741 borderWidth = cb.width();
747 return borderWidth / 2;
750 LayoutUnit RenderTableSection::calcOuterBorderAfter() const
752 int totalCols = table()->numEffCols();
753 if (!m_gridRows || !totalCols)
756 unsigned borderWidth = 0;
758 const BorderValue& sb = style()->borderAfter();
759 if (sb.style() == BHIDDEN)
761 if (sb.style() > BHIDDEN)
762 borderWidth = sb.width();
764 const BorderValue& rb = lastChild()->style()->borderAfter();
765 if (rb.style() == BHIDDEN)
767 if (rb.style() > BHIDDEN && rb.width() > borderWidth)
768 borderWidth = rb.width();
770 bool allHidden = true;
771 for (int c = 0; c < totalCols; c++) {
772 const CellStruct& current = cellAt(m_gridRows - 1, c);
773 if (current.inColSpan || !current.hasCells())
775 const BorderValue& cb = current.primaryCell()->style()->borderAfter(); // FIXME: Make this work with perpendicular and flipped cells.
776 // FIXME: Don't repeat for the same col group
777 RenderTableCol* colGroup = table()->colElement(c);
779 const BorderValue& gb = colGroup->style()->borderAfter();
780 if (gb.style() == BHIDDEN || cb.style() == BHIDDEN)
783 if (gb.style() > BHIDDEN && gb.width() > borderWidth)
784 borderWidth = gb.width();
785 if (cb.style() > BHIDDEN && cb.width() > borderWidth)
786 borderWidth = cb.width();
788 if (cb.style() == BHIDDEN)
791 if (cb.style() > BHIDDEN && cb.width() > borderWidth)
792 borderWidth = cb.width();
798 return (borderWidth + 1) / 2;
801 LayoutUnit RenderTableSection::calcOuterBorderStart() const
803 int totalCols = table()->numEffCols();
804 if (!m_gridRows || !totalCols)
807 unsigned borderWidth = 0;
809 const BorderValue& sb = style()->borderStart();
810 if (sb.style() == BHIDDEN)
812 if (sb.style() > BHIDDEN)
813 borderWidth = sb.width();
815 if (RenderTableCol* colGroup = table()->colElement(0)) {
816 const BorderValue& gb = colGroup->style()->borderStart();
817 if (gb.style() == BHIDDEN)
819 if (gb.style() > BHIDDEN && gb.width() > borderWidth)
820 borderWidth = gb.width();
823 bool allHidden = true;
824 for (int r = 0; r < m_gridRows; r++) {
825 const CellStruct& current = cellAt(r, 0);
826 if (!current.hasCells())
828 // FIXME: Don't repeat for the same cell
829 const BorderValue& cb = current.primaryCell()->style()->borderStart(); // FIXME: Make this work with perpendicular and flipped cells.
830 const BorderValue& rb = current.primaryCell()->parent()->style()->borderStart();
831 if (cb.style() == BHIDDEN || rb.style() == BHIDDEN)
834 if (cb.style() > BHIDDEN && cb.width() > borderWidth)
835 borderWidth = cb.width();
836 if (rb.style() > BHIDDEN && rb.width() > borderWidth)
837 borderWidth = rb.width();
842 return (borderWidth + (table()->style()->isLeftToRightDirection() ? 0 : 1)) / 2;
845 LayoutUnit RenderTableSection::calcOuterBorderEnd() const
847 int totalCols = table()->numEffCols();
848 if (!m_gridRows || !totalCols)
851 unsigned borderWidth = 0;
853 const BorderValue& sb = style()->borderEnd();
854 if (sb.style() == BHIDDEN)
856 if (sb.style() > BHIDDEN)
857 borderWidth = sb.width();
859 if (RenderTableCol* colGroup = table()->colElement(totalCols - 1)) {
860 const BorderValue& gb = colGroup->style()->borderEnd();
861 if (gb.style() == BHIDDEN)
863 if (gb.style() > BHIDDEN && gb.width() > borderWidth)
864 borderWidth = gb.width();
867 bool allHidden = true;
868 for (int r = 0; r < m_gridRows; r++) {
869 const CellStruct& current = cellAt(r, totalCols - 1);
870 if (!current.hasCells())
872 // FIXME: Don't repeat for the same cell
873 const BorderValue& cb = current.primaryCell()->style()->borderEnd(); // FIXME: Make this work with perpendicular and flipped cells.
874 const BorderValue& rb = current.primaryCell()->parent()->style()->borderEnd();
875 if (cb.style() == BHIDDEN || rb.style() == BHIDDEN)
878 if (cb.style() > BHIDDEN && cb.width() > borderWidth)
879 borderWidth = cb.width();
880 if (rb.style() > BHIDDEN && rb.width() > borderWidth)
881 borderWidth = rb.width();
886 return (borderWidth + (table()->style()->isLeftToRightDirection() ? 1 : 0)) / 2;
889 void RenderTableSection::recalcOuterBorder()
891 m_outerBorderBefore = calcOuterBorderBefore();
892 m_outerBorderAfter = calcOuterBorderAfter();
893 m_outerBorderStart = calcOuterBorderStart();
894 m_outerBorderEnd = calcOuterBorderEnd();
897 LayoutUnit RenderTableSection::firstLineBoxBaseline() const
902 LayoutUnit firstLineBaseline = m_grid[0].baseline;
903 if (firstLineBaseline)
904 return firstLineBaseline + m_rowPos[0];
906 firstLineBaseline = -1;
907 Row* firstRow = m_grid[0].row;
908 for (size_t i = 0; i < firstRow->size(); ++i) {
909 CellStruct& cs = firstRow->at(i);
910 RenderTableCell* cell = cs.primaryCell();
912 firstLineBaseline = max(firstLineBaseline, cell->logicalTop() + cell->paddingBefore() + cell->borderBefore() + cell->contentLogicalHeight());
915 return firstLineBaseline;
918 void RenderTableSection::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
920 // put this back in when all layout tests can handle it
921 // ASSERT(!needsLayout());
922 // avoid crashing on bugs that cause us to paint with dirty layout
926 unsigned totalRows = m_gridRows;
927 unsigned totalCols = table()->columns().size();
929 if (!totalRows || !totalCols)
932 LayoutPoint adjustedPaintOffset = paintOffset + location();
934 PaintPhase phase = paintInfo.phase;
935 bool pushedClip = pushContentsClip(paintInfo, adjustedPaintOffset);
936 paintObject(paintInfo, adjustedPaintOffset);
938 popContentsClip(paintInfo, phase, adjustedPaintOffset);
941 static inline bool compareCellPositions(RenderTableCell* elem1, RenderTableCell* elem2)
943 return elem1->row() < elem2->row();
946 // This comparison is used only when we have overflowing cells as we have an unsorted array to sort. We thus need
947 // to sort both on rows and columns to properly repaint.
948 static inline bool compareCellPositionsWithOverflowingCells(RenderTableCell* elem1, RenderTableCell* elem2)
950 if (elem1->row() != elem2->row())
951 return elem1->row() < elem2->row();
953 return elem1->col() < elem2->col();
956 void RenderTableSection::paintCell(RenderTableCell* cell, PaintInfo& paintInfo, const LayoutPoint& paintOffset)
958 LayoutPoint cellPoint = flipForWritingMode(cell, paintOffset, ParentToChildFlippingAdjustment);
959 PaintPhase paintPhase = paintInfo.phase;
960 RenderTableRow* row = toRenderTableRow(cell->parent());
962 if (paintPhase == PaintPhaseBlockBackground || paintPhase == PaintPhaseChildBlockBackground) {
963 // We need to handle painting a stack of backgrounds. This stack (from bottom to top) consists of
964 // the column group, column, row group, row, and then the cell.
965 RenderObject* col = table()->colElement(cell->col());
966 RenderObject* colGroup = 0;
967 if (col && col->parent()->style()->display() == TABLE_COLUMN_GROUP)
968 colGroup = col->parent();
970 // Column groups and columns first.
971 // FIXME: Columns and column groups do not currently support opacity, and they are being painted "too late" in
972 // the stack, since we have already opened a transparency layer (potentially) for the table row group.
973 // Note that we deliberately ignore whether or not the cell has a layer, since these backgrounds paint "behind" the
975 cell->paintBackgroundsBehindCell(paintInfo, cellPoint, colGroup);
976 cell->paintBackgroundsBehindCell(paintInfo, cellPoint, col);
978 // Paint the row group next.
979 cell->paintBackgroundsBehindCell(paintInfo, cellPoint, this);
981 // Paint the row next, but only if it doesn't have a layer. If a row has a layer, it will be responsible for
982 // painting the row background for the cell.
983 if (!row->hasSelfPaintingLayer())
984 cell->paintBackgroundsBehindCell(paintInfo, cellPoint, row);
986 if ((!cell->hasSelfPaintingLayer() && !row->hasSelfPaintingLayer()) || paintInfo.phase == PaintPhaseCollapsedTableBorders)
987 cell->paint(paintInfo, cellPoint);
990 void RenderTableSection::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
992 // Check which rows and cols are visible and only paint these.
993 unsigned totalRows = m_gridRows;
994 unsigned totalCols = table()->columns().size();
996 PaintPhase paintPhase = paintInfo.phase;
998 LayoutUnit os = 2 * maximalOutlineSize(paintPhase);
999 unsigned startrow = 0;
1000 unsigned endrow = totalRows;
1002 LayoutRect localRepaintRect = paintInfo.rect;
1003 localRepaintRect.moveBy(-paintOffset);
1004 if (style()->isFlippedBlocksWritingMode()) {
1005 if (style()->isHorizontalWritingMode())
1006 localRepaintRect.setY(height() - localRepaintRect.maxY());
1008 localRepaintRect.setX(width() - localRepaintRect.maxX());
1011 if (!m_forceSlowPaintPathWithOverflowingCell) {
1012 LayoutUnit before = (style()->isHorizontalWritingMode() ? localRepaintRect.y() : localRepaintRect.x()) - os;
1013 // binary search to find a row
1014 startrow = std::lower_bound(m_rowPos.begin(), m_rowPos.end(), before) - m_rowPos.begin();
1016 // The binary search above gives us the first row with
1017 // a y position >= the top of the paint rect. Thus, the previous
1018 // may need to be repainted as well.
1019 if (startrow == m_rowPos.size() || (startrow > 0 && (m_rowPos[startrow] > before)))
1022 LayoutUnit after = (style()->isHorizontalWritingMode() ? localRepaintRect.maxY() : localRepaintRect.maxX()) + os;
1023 endrow = std::lower_bound(m_rowPos.begin(), m_rowPos.end(), after) - m_rowPos.begin();
1024 if (endrow == m_rowPos.size())
1027 if (!endrow && m_rowPos[0] - table()->outerBorderBefore() <= after)
1031 unsigned startcol = 0;
1032 unsigned endcol = totalCols;
1033 // FIXME: Implement RTL.
1034 if (!m_forceSlowPaintPathWithOverflowingCell && style()->isLeftToRightDirection()) {
1035 LayoutUnit start = (style()->isHorizontalWritingMode() ? localRepaintRect.x() : localRepaintRect.y()) - os;
1036 Vector<LayoutUnit>& columnPos = table()->columnPositions();
1037 startcol = std::lower_bound(columnPos.begin(), columnPos.end(), start) - columnPos.begin();
1038 if ((startcol == columnPos.size()) || (startcol > 0 && (columnPos[startcol] > start)))
1041 LayoutUnit end = (style()->isHorizontalWritingMode() ? localRepaintRect.maxX() : localRepaintRect.maxY()) + os;
1042 endcol = std::lower_bound(columnPos.begin(), columnPos.end(), end) - columnPos.begin();
1043 if (endcol == columnPos.size())
1046 if (!endcol && columnPos[0] - table()->outerBorderStart() <= end)
1049 if (startcol < endcol) {
1050 if (!m_hasMultipleCellLevels && !m_overflowingCells.size()) {
1051 // Draw the dirty cells in the order that they appear.
1052 for (unsigned r = startrow; r < endrow; r++) {
1053 for (unsigned c = startcol; c < endcol; c++) {
1054 CellStruct& current = cellAt(r, c);
1055 RenderTableCell* cell = current.primaryCell();
1056 if (!cell || (r > startrow && primaryCellAt(r - 1, c) == cell) || (c > startcol && primaryCellAt(r, c - 1) == cell))
1058 paintCell(cell, paintInfo, paintOffset);
1062 // The overflowing cells should be scarce to avoid adding a lot of cells to the HashSet.
1063 ASSERT(m_overflowingCells.size() < totalRows * totalCols * gMaxAllowedOverflowingCellRatioForFastPaintPath);
1065 // To make sure we properly repaint the section, we repaint all the overflowing cells that we collected.
1066 Vector<RenderTableCell*> cells;
1067 copyToVector(m_overflowingCells, cells);
1069 HashSet<RenderTableCell*> spanningCells;
1071 for (unsigned r = startrow; r < endrow; r++) {
1072 for (unsigned c = startcol; c < endcol; c++) {
1073 CellStruct& current = cellAt(r, c);
1074 if (!current.hasCells())
1076 for (unsigned i = 0; i < current.cells.size(); ++i) {
1077 if (m_overflowingCells.contains(current.cells[i]))
1080 if (current.cells[i]->rowSpan() > 1 || current.cells[i]->colSpan() > 1) {
1081 if (spanningCells.contains(current.cells[i]))
1083 spanningCells.add(current.cells[i]);
1086 cells.append(current.cells[i]);
1091 // Sort the dirty cells by paint order.
1092 if (!m_overflowingCells.size())
1093 std::stable_sort(cells.begin(), cells.end(), compareCellPositions);
1095 std::sort(cells.begin(), cells.end(), compareCellPositionsWithOverflowingCells);
1097 int size = cells.size();
1099 for (int i = 0; i < size; ++i)
1100 paintCell(cells[i], paintInfo, paintOffset);
1105 void RenderTableSection::imageChanged(WrappedImagePtr, const IntRect*)
1107 // FIXME: Examine cells and repaint only the rect the image paints in.
1111 void RenderTableSection::recalcCells()
1118 for (RenderObject* row = firstChild(); row; row = row->nextSibling()) {
1119 if (row->isTableRow()) {
1122 if (!ensureRows(m_cRow + 1))
1125 RenderTableRow* tableRow = toRenderTableRow(row);
1126 m_grid[m_cRow].rowRenderer = tableRow;
1127 setRowLogicalHeightToRowStyleLogicalHeightIfNotRelative(&m_grid[m_cRow]);
1129 for (RenderObject* cell = row->firstChild(); cell; cell = cell->nextSibling()) {
1130 if (cell->isTableCell())
1131 addCell(toRenderTableCell(cell), tableRow);
1135 m_needsCellRecalc = false;
1136 setNeedsLayout(true);
1139 void RenderTableSection::setNeedsCellRecalc()
1141 m_needsCellRecalc = true;
1142 if (RenderTable* t = table())
1143 t->setNeedsSectionRecalc();
1146 void RenderTableSection::clearGrid()
1148 int rows = m_gridRows;
1150 delete m_grid[rows].row;
1153 int RenderTableSection::numColumns() const
1157 for (int r = 0; r < m_gridRows; ++r) {
1158 for (int c = result; c < table()->numEffCols(); ++c) {
1159 const CellStruct& cell = cellAt(r, c);
1160 if (cell.hasCells() || cell.inColSpan)
1168 void RenderTableSection::appendColumn(int pos)
1170 for (int row = 0; row < m_gridRows; ++row)
1171 m_grid[row].row->resize(pos + 1);
1174 void RenderTableSection::splitColumn(int pos, int first)
1178 for (int row = 0; row < m_gridRows; ++row) {
1179 Row& r = *m_grid[row].row;
1180 r.insert(pos + 1, CellStruct());
1181 if (r[pos].hasCells()) {
1182 r[pos + 1].cells.append(r[pos].cells);
1183 RenderTableCell* cell = r[pos].primaryCell();
1185 int colleft = cell->colSpan() - r[pos].inColSpan;
1186 if (first > colleft)
1187 r[pos + 1].inColSpan = 0;
1189 r[pos + 1].inColSpan = first + r[pos].inColSpan;
1191 r[pos + 1].inColSpan = 0;
1197 bool RenderTableSection::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
1199 // If we have no children then we have nothing to do.
1203 // Table sections cannot ever be hit tested. Effectively they do not exist.
1204 // Just forward to our children always.
1205 LayoutPoint adjustedLocation = accumulatedOffset + location();
1207 if (hasOverflowClip() && !overflowClipRect(adjustedLocation).intersects(result.rectForPoint(pointInContainer)))
1210 if (hasOverflowingCell()) {
1211 for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
1212 // FIXME: We have to skip over inline flows, since they can show up inside table rows
1213 // at the moment (a demoted inline <form> for example). If we ever implement a
1214 // table-specific hit-test method (which we should do for performance reasons anyway),
1215 // then we can remove this check.
1216 if (child->isBox() && !toRenderBox(child)->hasSelfPaintingLayer()) {
1217 LayoutPoint childPoint = flipForWritingMode(toRenderBox(child), adjustedLocation, ParentToChildFlippingAdjustment);
1218 if (child->nodeAtPoint(request, result, pointInContainer, childPoint, action)) {
1219 updateHitTestResult(result, toLayoutPoint(pointInContainer - childPoint));
1227 LayoutPoint location = pointInContainer - toLayoutSize(adjustedLocation);
1228 if (style()->isFlippedBlocksWritingMode()) {
1229 if (style()->isHorizontalWritingMode())
1230 location.setY(height() - location.y());
1232 location.setX(width() - location.x());
1235 LayoutUnit offsetInColumnDirection = style()->isHorizontalWritingMode() ? location.y() : location.x();
1236 // Find the first row that starts after offsetInColumnDirection.
1237 unsigned nextRow = std::upper_bound(m_rowPos.begin(), m_rowPos.end(), offsetInColumnDirection) - m_rowPos.begin();
1238 if (nextRow == m_rowPos.size())
1240 // Now set hitRow to the index of the hit row, or 0.
1241 unsigned hitRow = nextRow > 0 ? nextRow - 1 : 0;
1243 Vector<LayoutUnit>& columnPos = table()->columnPositions();
1244 LayoutUnit offsetInRowDirection = style()->isHorizontalWritingMode() ? location.x() : location.y();
1245 if (!style()->isLeftToRightDirection())
1246 offsetInRowDirection = columnPos[columnPos.size() - 1] - offsetInRowDirection;
1248 unsigned nextColumn = std::lower_bound(columnPos.begin(), columnPos.end(), offsetInRowDirection) - columnPos.begin();
1249 if (nextColumn == columnPos.size())
1251 unsigned hitColumn = nextColumn > 0 ? nextColumn - 1 : 0;
1253 CellStruct& current = cellAt(hitRow, hitColumn);
1255 // If the cell is empty, there's nothing to do
1256 if (!current.hasCells())
1259 for (int i = current.cells.size() - 1; i >= 0; --i) {
1260 RenderTableCell* cell = current.cells[i];
1261 LayoutPoint cellPoint = flipForWritingMode(cell, adjustedLocation, ParentToChildFlippingAdjustment);
1262 if (static_cast<RenderObject*>(cell)->nodeAtPoint(request, result, pointInContainer, cellPoint, action)) {
1263 updateHitTestResult(result, toLayoutPoint(pointInContainer - cellPoint));
1271 } // namespace WebCore