Fix assertions triggered by CSS calc changes in r166860
[WebKit-https.git] / Source / WebCore / rendering / RenderTableSection.cpp
1 /*
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)
9  *
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.
14  *
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.
19  *
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.
24  */
25
26 #include "config.h"
27 #include "RenderTableSection.h"
28 #include "Document.h"
29 #include "HitTestResult.h"
30 #include "HTMLNames.h"
31 #include "PaintInfo.h"
32 #include "RenderTableCell.h"
33 #include "RenderTableCol.h"
34 #include "RenderTableRow.h"
35 #include "RenderView.h"
36 #include "StyleInheritedData.h"
37 #include <limits>
38 #include <wtf/HashSet.h>
39 #include <wtf/StackStats.h>
40
41 namespace WebCore {
42
43 using namespace HTMLNames;
44
45 // Those 2 variables are used to balance the memory consumption vs the repaint time on big tables.
46 static unsigned gMinTableSizeToUseFastPaintPathWithOverflowingCell = 75 * 75;
47 static float gMaxAllowedOverflowingCellRatioForFastPaintPath = 0.1f;
48
49 static inline void setRowLogicalHeightToRowStyleLogicalHeightIfNotRelative(RenderTableSection::RowStruct& row)
50 {
51     ASSERT(row.rowRenderer);
52     row.logicalHeight = row.rowRenderer->style().logicalHeight();
53     if (row.logicalHeight.isRelative())
54         row.logicalHeight = Length();
55 }
56
57 static inline void updateLogicalHeightForCell(RenderTableSection::RowStruct& row, const RenderTableCell* cell)
58 {
59     // We ignore height settings on rowspan cells.
60     if (cell->rowSpan() != 1)
61         return;
62
63     Length logicalHeight = cell->style().logicalHeight();
64     if (logicalHeight.isPositive() || (logicalHeight.isRelative() && logicalHeight.value() >= 0)) {
65         Length cRowLogicalHeight = row.logicalHeight;
66         switch (logicalHeight.type()) {
67         case Percent:
68             if (!cRowLogicalHeight.isPercentNotCalculated() || cRowLogicalHeight.percent() < logicalHeight.percent())
69                 row.logicalHeight = logicalHeight;
70             break;
71         case Fixed:
72             if (cRowLogicalHeight.isAuto() || cRowLogicalHeight.isRelative()
73                 || (cRowLogicalHeight.isFixed() && cRowLogicalHeight.value() < logicalHeight.value()))
74                 row.logicalHeight = logicalHeight;
75             break;
76         case Relative:
77         default:
78             break;
79         }
80     }
81 }
82
83 RenderTableSection::RenderTableSection(Element& element, PassRef<RenderStyle> style)
84     : RenderBox(element, std::move(style), 0)
85     , m_cCol(0)
86     , m_cRow(0)
87     , m_outerBorderStart(0)
88     , m_outerBorderEnd(0)
89     , m_outerBorderBefore(0)
90     , m_outerBorderAfter(0)
91     , m_needsCellRecalc(false)
92     , m_hasMultipleCellLevels(false)
93 {
94     setInline(false);
95 }
96
97 RenderTableSection::RenderTableSection(Document& document, PassRef<RenderStyle> style)
98     : RenderBox(document, std::move(style), 0)
99     , m_cCol(0)
100     , m_cRow(0)
101     , m_outerBorderStart(0)
102     , m_outerBorderEnd(0)
103     , m_outerBorderBefore(0)
104     , m_outerBorderAfter(0)
105     , m_needsCellRecalc(false)
106     , m_hasMultipleCellLevels(false)
107 {
108     setInline(false);
109 }
110
111 RenderTableSection::~RenderTableSection()
112 {
113 }
114
115 void RenderTableSection::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
116 {
117     RenderBox::styleDidChange(diff, oldStyle);
118     propagateStyleToAnonymousChildren(PropagateToAllChildren);
119
120     // If border was changed, notify table.
121     RenderTable* table = this->table();
122     if (table && !table->selfNeedsLayout() && !table->normalChildNeedsLayout() && oldStyle && oldStyle->border() != style().border())
123         table->invalidateCollapsedBorders();
124 }
125
126 void RenderTableSection::willBeRemovedFromTree()
127 {
128     RenderBox::willBeRemovedFromTree();
129
130     // Preventively invalidate our cells as we may be re-inserted into
131     // a new table which would require us to rebuild our structure.
132     setNeedsCellRecalc();
133 }
134
135 void RenderTableSection::addChild(RenderObject* child, RenderObject* beforeChild)
136 {
137     if (!child->isTableRow()) {
138         RenderObject* last = beforeChild;
139         if (!last)
140             last = lastRow();
141         if (last && last->isAnonymous() && !last->isBeforeOrAfterContent()) {
142             RenderTableRow* row = toRenderTableRow(last);
143             if (beforeChild == row)
144                 beforeChild = row->firstCell();
145             row->addChild(child, beforeChild);
146             return;
147         }
148
149         if (beforeChild && !beforeChild->isAnonymous() && beforeChild->parent() == this) {
150             RenderObject* row = beforeChild->previousSibling();
151             if (row && row->isTableRow() && row->isAnonymous()) {
152                 toRenderTableRow(row)->addChild(child);
153                 return;
154             }
155         }
156
157         // If beforeChild is inside an anonymous cell/row, insert into the cell or into
158         // the anonymous row containing it, if there is one.
159         RenderObject* lastBox = last;
160         while (lastBox && lastBox->parent()->isAnonymous() && !lastBox->isTableRow())
161             lastBox = lastBox->parent();
162         if (lastBox && lastBox->isAnonymous() && !lastBox->isBeforeOrAfterContent()) {
163             toRenderTableRow(lastBox)->addChild(child, beforeChild);
164             return;
165         }
166
167         RenderTableRow* row = RenderTableRow::createAnonymousWithParentRenderer(this);
168         addChild(row, beforeChild);
169         row->addChild(child);
170         return;
171     }
172
173     if (beforeChild)
174         setNeedsCellRecalc();
175
176     unsigned insertionRow = m_cRow;
177     ++m_cRow;
178     m_cCol = 0;
179
180     ensureRows(m_cRow);
181
182     RenderTableRow* row = toRenderTableRow(child);
183     m_grid[insertionRow].rowRenderer = row;
184     row->setRowIndex(insertionRow);
185
186     if (!beforeChild)
187         setRowLogicalHeightToRowStyleLogicalHeightIfNotRelative(m_grid[insertionRow]);
188
189     if (beforeChild && beforeChild->parent() != this)
190         beforeChild = splitAnonymousBoxesAroundChild(beforeChild);
191
192     ASSERT(!beforeChild || beforeChild->isTableRow());
193     RenderBox::addChild(child, beforeChild);
194 }
195
196 void RenderTableSection::ensureRows(unsigned numRows)
197 {
198     if (numRows <= m_grid.size())
199         return;
200
201     unsigned oldSize = m_grid.size();
202     m_grid.grow(numRows);
203
204     unsigned effectiveColumnCount = std::max(1u, table()->numEffCols());
205     for (unsigned row = oldSize; row < m_grid.size(); ++row)
206         m_grid[row].row.resizeToFit(effectiveColumnCount);
207 }
208
209 void RenderTableSection::addCell(RenderTableCell* cell, RenderTableRow* row)
210 {
211     // We don't insert the cell if we need cell recalc as our internal columns' representation
212     // will have drifted from the table's representation. Also recalcCells will call addCell
213     // at a later time after sync'ing our columns' with the table's.
214     if (needsCellRecalc())
215         return;
216
217     unsigned rSpan = cell->rowSpan();
218     unsigned cSpan = cell->colSpan();
219     const Vector<RenderTable::ColumnStruct>& columns = table()->columns();
220     unsigned nCols = columns.size();
221     unsigned insertionRow = row->rowIndex();
222
223     // ### mozilla still seems to do the old HTML way, even for strict DTD
224     // (see the annotation on table cell layouting in the CSS specs and the testcase below:
225     // <TABLE border>
226     // <TR><TD>1 <TD rowspan="2">2 <TD>3 <TD>4
227     // <TR><TD colspan="2">5
228     // </TABLE>
229     while (m_cCol < nCols && (cellAt(insertionRow, m_cCol).hasCells() || cellAt(insertionRow, m_cCol).inColSpan))
230         m_cCol++;
231
232     updateLogicalHeightForCell(m_grid[insertionRow], cell);
233
234     ensureRows(insertionRow + rSpan);
235
236     m_grid[insertionRow].rowRenderer = row;
237
238     unsigned col = m_cCol;
239     // tell the cell where it is
240     bool inColSpan = false;
241     while (cSpan) {
242         unsigned currentSpan;
243         if (m_cCol >= nCols) {
244             table()->appendColumn(cSpan);
245             currentSpan = cSpan;
246         } else {
247             if (cSpan < columns[m_cCol].span)
248                 table()->splitColumn(m_cCol, cSpan);
249             currentSpan = columns[m_cCol].span;
250         }
251         for (unsigned r = 0; r < rSpan; r++) {
252             CellStruct& c = cellAt(insertionRow + r, m_cCol);
253             ASSERT(cell);
254             c.cells.append(cell);
255             // If cells overlap then we take the slow path for painting.
256             if (c.cells.size() > 1)
257                 m_hasMultipleCellLevels = true;
258             if (inColSpan)
259                 c.inColSpan = true;
260         }
261         m_cCol++;
262         cSpan -= currentSpan;
263         inColSpan = true;
264     }
265     cell->setCol(table()->effColToCol(col));
266 }
267
268 int RenderTableSection::calcRowLogicalHeight()
269 {
270 #ifndef NDEBUG
271     SetLayoutNeededForbiddenScope layoutForbiddenScope(this);
272 #endif
273
274     ASSERT(!needsLayout());
275
276     RenderTableCell* cell;
277
278     // We ignore the border-spacing on any non-top section as it is already included in the previous section's last row position.
279     int spacing = 0;
280     if (this == table()->topSection())
281         spacing = table()->vBorderSpacing();
282
283     LayoutStateMaintainer statePusher(view());
284
285     m_rowPos.resize(m_grid.size() + 1);
286     m_rowPos[0] = spacing;
287
288     unsigned totalRows = m_grid.size();
289
290     for (unsigned r = 0; r < totalRows; r++) {
291         m_grid[r].baseline = 0;
292         LayoutUnit baselineDescent = 0;
293
294         // Our base size is the biggest logical height from our cells' styles (excluding row spanning cells).
295         m_rowPos[r + 1] = std::max(m_rowPos[r] + minimumValueForLength(m_grid[r].logicalHeight, 0).round(), 0);
296
297         Row& row = m_grid[r].row;
298         unsigned totalCols = row.size();
299
300         for (unsigned c = 0; c < totalCols; c++) {
301             CellStruct& current = cellAt(r, c);
302             for (unsigned i = 0; i < current.cells.size(); i++) {
303                 cell = current.cells[i];
304                 if (current.inColSpan && cell->rowSpan() == 1)
305                     continue;
306
307                 // FIXME: We are always adding the height of a rowspan to the last rows which doesn't match
308                 // other browsers. See webkit.org/b/52185 for example.
309                 if ((cell->rowIndex() + cell->rowSpan() - 1) != r) {
310                     // We will apply the height of the rowspan to the current row if next row is not valid.
311                     if ((r + 1) < totalRows) {
312                         unsigned col = 0;
313                         CellStruct nextRowCell = cellAt(r + 1, col);
314
315                         // We are trying to find that next row is valid or not.
316                         while (nextRowCell.cells.size() && nextRowCell.cells[0]->rowSpan() > 1 && nextRowCell.cells[0]->rowIndex() < (r + 1)) {
317                             col++;
318                             if (col < totalCols)
319                                 nextRowCell = cellAt(r + 1, col);
320                             else
321                                 break;
322                         }
323
324                         // We are adding the height of the rowspan to the current row if next row is not valid.
325                         if (col < totalCols && nextRowCell.cells.size())
326                             continue;
327                     }
328                 }
329
330                 // For row spanning cells, |r| is the last row in the span.
331                 unsigned cellStartRow = cell->rowIndex();
332
333                 if (cell->hasOverrideHeight()) {
334                     if (!statePusher.didPush()) {
335                         // Technically, we should also push state for the row, but since
336                         // rows don't push a coordinate transform, that's not necessary.
337                         statePusher.push(*this, locationOffset());
338                     }
339                     cell->clearIntrinsicPadding();
340                     cell->clearOverrideSize();
341                     cell->setChildNeedsLayout(MarkOnlyThis);
342                     cell->layoutIfNeeded();
343                 }
344
345                 int cellLogicalHeight = cell->logicalHeightForRowSizing();
346                 m_rowPos[r + 1] = std::max(m_rowPos[r + 1], m_rowPos[cellStartRow] + cellLogicalHeight);
347
348                 // Find out the baseline. The baseline is set on the first row in a rowspan.
349                 if (cell->isBaselineAligned()) {
350                     LayoutUnit baselinePosition = cell->cellBaselinePosition();
351                     if (baselinePosition > cell->borderAndPaddingBefore()) {
352                         m_grid[cellStartRow].baseline = std::max(m_grid[cellStartRow].baseline, baselinePosition);
353                         // The descent of a cell that spans multiple rows does not affect the height of the first row it spans, so don't let it
354                         // become the baseline descent applied to the rest of the row. Also we don't account for the baseline descent of
355                         // non-spanning cells when computing a spanning cell's extent.
356                         int cellStartRowBaselineDescent = 0;
357                         if (cell->rowSpan() == 1) {
358                             baselineDescent = std::max(baselineDescent, cellLogicalHeight - (baselinePosition - cell->intrinsicPaddingBefore()));
359                             cellStartRowBaselineDescent = baselineDescent;
360                         }
361                         m_rowPos[cellStartRow + 1] = std::max<int>(m_rowPos[cellStartRow + 1], m_rowPos[cellStartRow] + m_grid[cellStartRow].baseline + cellStartRowBaselineDescent);
362                     }
363                 }
364             }
365         }
366
367         // Add the border-spacing to our final position.
368         // Use table border-spacing even in non-top sections
369         spacing = table()->vBorderSpacing();
370         m_rowPos[r + 1] += m_grid[r].rowRenderer ? spacing : 0;
371         m_rowPos[r + 1] = std::max(m_rowPos[r + 1], m_rowPos[r]);
372     }
373
374     ASSERT(!needsLayout());
375
376     statePusher.pop();
377
378     return m_rowPos[m_grid.size()];
379 }
380
381 void RenderTableSection::layout()
382 {
383     StackStats::LayoutCheckPoint layoutCheckPoint;
384     ASSERT(needsLayout());
385     ASSERT(!needsCellRecalc());
386     ASSERT(!table()->needsSectionRecalc());
387
388     // addChild may over-grow m_grid but we don't want to throw away the memory too early as addChild
389     // can be called in a loop (e.g during parsing). Doing it now ensures we have a stable-enough structure.
390     m_grid.shrinkToFit();
391
392     LayoutStateMaintainer statePusher(view(), *this, locationOffset(), hasTransform() || hasReflection() || style().isFlippedBlocksWritingMode());
393
394     const Vector<int>& columnPos = table()->columnPositions();
395
396     for (unsigned r = 0; r < m_grid.size(); ++r) {
397         Row& row = m_grid[r].row;
398         unsigned cols = row.size();
399         // First, propagate our table layout's information to the cells. This will mark the row as needing layout
400         // if there was a column logical width change.
401         for (unsigned startColumn = 0; startColumn < cols; ++startColumn) {
402             CellStruct& current = row[startColumn];
403             RenderTableCell* cell = current.primaryCell();
404             if (!cell || current.inColSpan)
405                 continue;
406
407             unsigned endCol = startColumn;
408             unsigned cspan = cell->colSpan();
409             while (cspan && endCol < cols) {
410                 ASSERT(endCol < table()->columns().size());
411                 cspan -= table()->columns()[endCol].span;
412                 endCol++;
413             }
414             int tableLayoutLogicalWidth = columnPos[endCol] - columnPos[startColumn] - table()->hBorderSpacing();
415             cell->setCellLogicalWidth(tableLayoutLogicalWidth);
416         }
417
418         if (RenderTableRow* rowRenderer = m_grid[r].rowRenderer)
419             rowRenderer->layoutIfNeeded();
420     }
421
422     statePusher.pop();
423     clearNeedsLayout();
424 }
425
426 void RenderTableSection::distributeExtraLogicalHeightToPercentRows(int& extraLogicalHeight, int totalPercent)
427 {
428     if (!totalPercent)
429         return;
430
431     unsigned totalRows = m_grid.size();
432     int totalHeight = m_rowPos[totalRows] + extraLogicalHeight;
433     int totalLogicalHeightAdded = 0;
434     totalPercent = std::min(totalPercent, 100);
435     int rowHeight = m_rowPos[1] - m_rowPos[0];
436     for (unsigned r = 0; r < totalRows; ++r) {
437         if (totalPercent > 0 && m_grid[r].logicalHeight.isPercentNotCalculated()) {
438             int toAdd = std::min<int>(extraLogicalHeight, (totalHeight * m_grid[r].logicalHeight.percent() / 100) - rowHeight);
439             // If toAdd is negative, then we don't want to shrink the row (this bug
440             // affected Outlook Web Access).
441             toAdd = std::max(0, toAdd);
442             totalLogicalHeightAdded += toAdd;
443             extraLogicalHeight -= toAdd;
444             totalPercent -= m_grid[r].logicalHeight.percent();
445         }
446         ASSERT(totalRows >= 1);
447         if (r < totalRows - 1)
448             rowHeight = m_rowPos[r + 2] - m_rowPos[r + 1];
449         m_rowPos[r + 1] += totalLogicalHeightAdded;
450     }
451 }
452
453 void RenderTableSection::distributeExtraLogicalHeightToAutoRows(int& extraLogicalHeight, unsigned autoRowsCount)
454 {
455     if (!autoRowsCount)
456         return;
457
458     int totalLogicalHeightAdded = 0;
459     for (unsigned r = 0; r < m_grid.size(); ++r) {
460         if (autoRowsCount > 0 && m_grid[r].logicalHeight.isAuto()) {
461             // Recomputing |extraLogicalHeightForRow| guarantees that we properly ditribute round |extraLogicalHeight|.
462             int extraLogicalHeightForRow = extraLogicalHeight / autoRowsCount;
463             totalLogicalHeightAdded += extraLogicalHeightForRow;
464             extraLogicalHeight -= extraLogicalHeightForRow;
465             --autoRowsCount;
466         }
467         m_rowPos[r + 1] += totalLogicalHeightAdded;
468     }
469 }
470
471 void RenderTableSection::distributeRemainingExtraLogicalHeight(int& extraLogicalHeight)
472 {
473     unsigned totalRows = m_grid.size();
474
475     if (extraLogicalHeight <= 0 || !m_rowPos[totalRows])
476         return;
477
478     // FIXME: m_rowPos[totalRows] - m_rowPos[0] is the total rows' size.
479     int totalRowSize = m_rowPos[totalRows];
480     int totalLogicalHeightAdded = 0;
481     int previousRowPosition = m_rowPos[0];
482     for (unsigned r = 0; r < totalRows; r++) {
483         // weight with the original height
484         totalLogicalHeightAdded += extraLogicalHeight * (m_rowPos[r + 1] - previousRowPosition) / totalRowSize;
485         previousRowPosition = m_rowPos[r + 1];
486         m_rowPos[r + 1] += totalLogicalHeightAdded;
487     }
488
489     extraLogicalHeight -= totalLogicalHeightAdded;
490 }
491
492 int RenderTableSection::distributeExtraLogicalHeightToRows(int extraLogicalHeight)
493 {
494     if (!extraLogicalHeight)
495         return extraLogicalHeight;
496
497     unsigned totalRows = m_grid.size();
498     if (!totalRows)
499         return extraLogicalHeight;
500
501     if (!m_rowPos[totalRows] && nextSibling())
502         return extraLogicalHeight;
503
504     unsigned autoRowsCount = 0;
505     int totalPercent = 0;
506     for (unsigned r = 0; r < totalRows; r++) {
507         if (m_grid[r].logicalHeight.isAuto())
508             ++autoRowsCount;
509         else if (m_grid[r].logicalHeight.isPercentNotCalculated())
510             totalPercent += m_grid[r].logicalHeight.percent();
511     }
512
513     int remainingExtraLogicalHeight = extraLogicalHeight;
514     distributeExtraLogicalHeightToPercentRows(remainingExtraLogicalHeight, totalPercent);
515     distributeExtraLogicalHeightToAutoRows(remainingExtraLogicalHeight, autoRowsCount);
516     distributeRemainingExtraLogicalHeight(remainingExtraLogicalHeight);
517     return extraLogicalHeight - remainingExtraLogicalHeight;
518 }
519
520 void RenderTableSection::layoutRows()
521 {
522 #ifndef NDEBUG
523     SetLayoutNeededForbiddenScope layoutForbiddenScope(this);
524 #endif
525
526     ASSERT(!needsLayout());
527
528     unsigned totalRows = m_grid.size();
529
530     // Set the width of our section now.  The rows will also be this width.
531     setLogicalWidth(table()->contentLogicalWidth());
532     m_forceSlowPaintPathWithOverflowingCell = false;
533
534     int vspacing = table()->vBorderSpacing();
535     unsigned nEffCols = table()->numEffCols();
536
537     LayoutStateMaintainer statePusher(view(), *this, locationOffset(), hasTransform() || style().isFlippedBlocksWritingMode());
538
539     for (unsigned r = 0; r < totalRows; r++) {
540         // Set the row's x/y position and width/height.
541         if (RenderTableRow* rowRenderer = m_grid[r].rowRenderer) {
542             // FIXME: the x() position of the row should be table()->hBorderSpacing() so that it can 
543             // report the correct offsetLeft. However, that will require a lot of rebaselining of test results.
544             rowRenderer->setLocation(LayoutPoint(0, m_rowPos[r]));
545             rowRenderer->setLogicalWidth(logicalWidth());
546             rowRenderer->setLogicalHeight(m_rowPos[r + 1] - m_rowPos[r] - vspacing);
547             rowRenderer->updateLayerTransform();
548         }
549
550         int rowHeightIncreaseForPagination = 0;
551
552         for (unsigned c = 0; c < nEffCols; c++) {
553             CellStruct& cs = cellAt(r, c);
554             RenderTableCell* cell = cs.primaryCell();
555
556             if (!cell || cs.inColSpan)
557                 continue;
558
559             int rowIndex = cell->rowIndex();
560             int rHeight = m_rowPos[rowIndex + cell->rowSpan()] - m_rowPos[rowIndex] - vspacing;
561
562             // Force percent height children to lay themselves out again.
563             // This will cause these children to grow to fill the cell.
564             // FIXME: There is still more work to do here to fully match WinIE (should
565             // it become necessary to do so).  In quirks mode, WinIE behaves like we
566             // do, but it will clip the cells that spill out of the table section.  In
567             // strict mode, Mozilla and WinIE both regrow the table to accommodate the
568             // new height of the cell (thus letting the percentages cause growth one
569             // time only).  We may also not be handling row-spanning cells correctly.
570             //
571             // Note also the oddity where replaced elements always flex, and yet blocks/tables do
572             // not necessarily flex.  WinIE is crazy and inconsistent, and we can't hope to
573             // match the behavior perfectly, but we'll continue to refine it as we discover new
574             // bugs. :)
575             bool cellChildrenFlex = false;
576             bool flexAllChildren = cell->style().logicalHeight().isFixed()
577                 || (!table()->style().logicalHeight().isAuto() && rHeight != cell->logicalHeight());
578
579             for (RenderObject* o = cell->firstChild(); o; o = o->nextSibling()) {
580                 if (!o->isText() && o->style().logicalHeight().isPercent() && (flexAllChildren || ((o->isReplaced() || (o->isBox() && toRenderBox(o)->scrollsOverflow())) && !o->isTextControl()))) {
581                     // Tables with no sections do not flex.
582                     if (!o->isTable() || toRenderTable(o)->hasSections()) {
583                         o->setNeedsLayout(MarkOnlyThis);
584                         cellChildrenFlex = true;
585                     }
586                 }
587             }
588
589             if (TrackedRendererListHashSet* percentHeightDescendants = cell->percentHeightDescendants()) {
590                 TrackedRendererListHashSet::iterator end = percentHeightDescendants->end();
591                 for (TrackedRendererListHashSet::iterator it = percentHeightDescendants->begin(); it != end; ++it) {
592                     RenderBox* box = *it;
593                     if (!box->isReplaced() && !box->scrollsOverflow() && !flexAllChildren)
594                         continue;
595
596                     while (box != cell) {
597                         if (box->normalChildNeedsLayout())
598                             break;
599                         box->setChildNeedsLayout(MarkOnlyThis);
600                         box = box->containingBlock();
601                         ASSERT(box);
602                         if (!box)
603                             break;
604                     }
605                     cellChildrenFlex = true;
606                 }
607             }
608
609             if (cellChildrenFlex) {
610                 cell->setChildNeedsLayout(MarkOnlyThis);
611                 // Alignment within a cell is based off the calculated
612                 // height, which becomes irrelevant once the cell has
613                 // been resized based off its percentage.
614                 cell->setOverrideLogicalContentHeightFromRowHeight(rHeight);
615                 cell->layoutIfNeeded();
616
617                 // If the baseline moved, we may have to update the data for our row. Find out the new baseline.
618                 if (cell->isBaselineAligned()) {
619                     LayoutUnit baseline = cell->cellBaselinePosition();
620                     if (baseline > cell->borderAndPaddingBefore())
621                         m_grid[r].baseline = std::max(m_grid[r].baseline, baseline);
622                 }
623             }
624
625             cell->computeIntrinsicPadding(rHeight);
626
627             LayoutRect oldCellRect = cell->frameRect();
628
629             setLogicalPositionForCell(cell, c);
630
631             if (!cell->needsLayout() && view().layoutState()->pageLogicalHeight() && view().layoutState()->pageLogicalOffset(cell, cell->logicalTop()) != cell->pageLogicalOffset())
632                 cell->setChildNeedsLayout(MarkOnlyThis);
633
634             cell->layoutIfNeeded();
635
636             // FIXME: Make pagination work with vertical tables.
637             if (view().layoutState()->pageLogicalHeight() && cell->logicalHeight() != rHeight) {
638                 // FIXME: Pagination might have made us change size. For now just shrink or grow the cell to fit without doing a relayout.
639                 // We'll also do a basic increase of the row height to accommodate the cell if it's bigger, but this isn't quite right
640                 // either. It's at least stable though and won't result in an infinite # of relayouts that may never stabilize.
641                 if (cell->logicalHeight() > rHeight)
642                     rowHeightIncreaseForPagination = std::max<int>(rowHeightIncreaseForPagination, cell->logicalHeight() - rHeight);
643                 cell->setLogicalHeight(rHeight);
644             }
645
646             LayoutSize childOffset(cell->location() - oldCellRect.location());
647             if (childOffset.width() || childOffset.height()) {
648                 view().addLayoutDelta(childOffset);
649
650                 // If the child moved, we have to repaint it as well as any floating/positioned
651                 // descendants.  An exception is if we need a layout.  In this case, we know we're going to
652                 // repaint ourselves (and the child) anyway.
653                 if (!table()->selfNeedsLayout() && cell->checkForRepaintDuringLayout())
654                     cell->repaintDuringLayoutIfMoved(oldCellRect);
655             }
656         }
657         if (rowHeightIncreaseForPagination) {
658             for (unsigned rowIndex = r + 1; rowIndex <= totalRows; rowIndex++)
659                 m_rowPos[rowIndex] += rowHeightIncreaseForPagination;
660             for (unsigned c = 0; c < nEffCols; ++c) {
661                 Vector<RenderTableCell*, 1>& cells = cellAt(r, c).cells;
662                 for (size_t i = 0; i < cells.size(); ++i)
663                     cells[i]->setLogicalHeight(cells[i]->logicalHeight() + rowHeightIncreaseForPagination);
664             }
665         }
666     }
667
668     ASSERT(!needsLayout());
669
670     setLogicalHeight(m_rowPos[totalRows]);
671
672     computeOverflowFromCells(totalRows, nEffCols);
673
674     statePusher.pop();
675 }
676
677 void RenderTableSection::computeOverflowFromCells()
678 {
679     unsigned totalRows = m_grid.size();
680     unsigned nEffCols = table()->numEffCols();
681     computeOverflowFromCells(totalRows, nEffCols);
682 }
683
684 void RenderTableSection::computeOverflowFromCells(unsigned totalRows, unsigned nEffCols)
685 {
686     clearOverflow();
687     m_overflowingCells.clear();
688     unsigned totalCellsCount = nEffCols * totalRows;
689     int maxAllowedOverflowingCellsCount = totalCellsCount < gMinTableSizeToUseFastPaintPathWithOverflowingCell ? 0 : gMaxAllowedOverflowingCellRatioForFastPaintPath * totalCellsCount;
690
691 #ifndef NDEBUG
692     bool hasOverflowingCell = false;
693 #endif
694     // Now that our height has been determined, add in overflow from cells.
695     for (unsigned r = 0; r < totalRows; r++) {
696         for (unsigned c = 0; c < nEffCols; c++) {
697             CellStruct& cs = cellAt(r, c);
698             RenderTableCell* cell = cs.primaryCell();
699             if (!cell || cs.inColSpan)
700                 continue;
701             if (r < totalRows - 1 && cell == primaryCellAt(r + 1, c))
702                 continue;
703             addOverflowFromChild(cell);
704 #ifndef NDEBUG
705             hasOverflowingCell |= cell->hasVisualOverflow();
706 #endif
707             if (cell->hasVisualOverflow() && !m_forceSlowPaintPathWithOverflowingCell) {
708                 m_overflowingCells.add(cell);
709                 if (m_overflowingCells.size() > maxAllowedOverflowingCellsCount) {
710                     // We need to set m_forcesSlowPaintPath only if there is a least one overflowing cells as the hit testing code rely on this information.
711                     m_forceSlowPaintPathWithOverflowingCell = true;
712                     // The slow path does not make any use of the overflowing cells info, don't hold on to the memory.
713                     m_overflowingCells.clear();
714                 }
715             }
716         }
717     }
718
719     ASSERT(hasOverflowingCell == this->hasOverflowingCell());
720 }
721
722 int RenderTableSection::calcOuterBorderBefore() const
723 {
724     unsigned totalCols = table()->numEffCols();
725     if (!m_grid.size() || !totalCols)
726         return 0;
727
728     unsigned borderWidth = 0;
729
730     const BorderValue& sb = style().borderBefore();
731     if (sb.style() == BHIDDEN)
732         return -1;
733     if (sb.style() > BHIDDEN)
734         borderWidth = sb.width();
735
736     const BorderValue& rb = firstRow()->style().borderBefore();
737     if (rb.style() == BHIDDEN)
738         return -1;
739     if (rb.style() > BHIDDEN && rb.width() > borderWidth)
740         borderWidth = rb.width();
741
742     bool allHidden = true;
743     for (unsigned c = 0; c < totalCols; c++) {
744         const CellStruct& current = cellAt(0, c);
745         if (current.inColSpan || !current.hasCells())
746             continue;
747         const BorderValue& cb = current.primaryCell()->style().borderBefore(); // FIXME: Make this work with perpendicular and flipped cells.
748         // FIXME: Don't repeat for the same col group
749         RenderTableCol* colGroup = table()->colElement(c);
750         if (colGroup) {
751             const BorderValue& gb = colGroup->style().borderBefore();
752             if (gb.style() == BHIDDEN || cb.style() == BHIDDEN)
753                 continue;
754             allHidden = false;
755             if (gb.style() > BHIDDEN && gb.width() > borderWidth)
756                 borderWidth = gb.width();
757             if (cb.style() > BHIDDEN && cb.width() > borderWidth)
758                 borderWidth = cb.width();
759         } else {
760             if (cb.style() == BHIDDEN)
761                 continue;
762             allHidden = false;
763             if (cb.style() > BHIDDEN && cb.width() > borderWidth)
764                 borderWidth = cb.width();
765         }
766     }
767     if (allHidden)
768         return -1;
769
770     return borderWidth / 2;
771 }
772
773 int RenderTableSection::calcOuterBorderAfter() const
774 {
775     unsigned totalCols = table()->numEffCols();
776     if (!m_grid.size() || !totalCols)
777         return 0;
778
779     unsigned borderWidth = 0;
780
781     const BorderValue& sb = style().borderAfter();
782     if (sb.style() == BHIDDEN)
783         return -1;
784     if (sb.style() > BHIDDEN)
785         borderWidth = sb.width();
786
787     const BorderValue& rb = lastRow()->style().borderAfter();
788     if (rb.style() == BHIDDEN)
789         return -1;
790     if (rb.style() > BHIDDEN && rb.width() > borderWidth)
791         borderWidth = rb.width();
792
793     bool allHidden = true;
794     for (unsigned c = 0; c < totalCols; c++) {
795         const CellStruct& current = cellAt(m_grid.size() - 1, c);
796         if (current.inColSpan || !current.hasCells())
797             continue;
798         const BorderValue& cb = current.primaryCell()->style().borderAfter(); // FIXME: Make this work with perpendicular and flipped cells.
799         // FIXME: Don't repeat for the same col group
800         RenderTableCol* colGroup = table()->colElement(c);
801         if (colGroup) {
802             const BorderValue& gb = colGroup->style().borderAfter();
803             if (gb.style() == BHIDDEN || cb.style() == BHIDDEN)
804                 continue;
805             allHidden = false;
806             if (gb.style() > BHIDDEN && gb.width() > borderWidth)
807                 borderWidth = gb.width();
808             if (cb.style() > BHIDDEN && cb.width() > borderWidth)
809                 borderWidth = cb.width();
810         } else {
811             if (cb.style() == BHIDDEN)
812                 continue;
813             allHidden = false;
814             if (cb.style() > BHIDDEN && cb.width() > borderWidth)
815                 borderWidth = cb.width();
816         }
817     }
818     if (allHidden)
819         return -1;
820
821     return (borderWidth + 1) / 2;
822 }
823
824 int RenderTableSection::calcOuterBorderStart() const
825 {
826     unsigned totalCols = table()->numEffCols();
827     if (!m_grid.size() || !totalCols)
828         return 0;
829
830     unsigned borderWidth = 0;
831
832     const BorderValue& sb = style().borderStart();
833     if (sb.style() == BHIDDEN)
834         return -1;
835     if (sb.style() > BHIDDEN)
836         borderWidth = sb.width();
837
838     if (RenderTableCol* colGroup = table()->colElement(0)) {
839         const BorderValue& gb = colGroup->style().borderStart();
840         if (gb.style() == BHIDDEN)
841             return -1;
842         if (gb.style() > BHIDDEN && gb.width() > borderWidth)
843             borderWidth = gb.width();
844     }
845
846     bool allHidden = true;
847     for (unsigned r = 0; r < m_grid.size(); r++) {
848         const CellStruct& current = cellAt(r, 0);
849         if (!current.hasCells())
850             continue;
851         // FIXME: Don't repeat for the same cell
852         const BorderValue& cb = current.primaryCell()->style().borderStart(); // FIXME: Make this work with perpendicular and flipped cells.
853         const BorderValue& rb = current.primaryCell()->parent()->style().borderStart();
854         if (cb.style() == BHIDDEN || rb.style() == BHIDDEN)
855             continue;
856         allHidden = false;
857         if (cb.style() > BHIDDEN && cb.width() > borderWidth)
858             borderWidth = cb.width();
859         if (rb.style() > BHIDDEN && rb.width() > borderWidth)
860             borderWidth = rb.width();
861     }
862     if (allHidden)
863         return -1;
864
865     return (borderWidth + (table()->style().isLeftToRightDirection() ? 0 : 1)) / 2;
866 }
867
868 int RenderTableSection::calcOuterBorderEnd() const
869 {
870     unsigned totalCols = table()->numEffCols();
871     if (!m_grid.size() || !totalCols)
872         return 0;
873
874     unsigned borderWidth = 0;
875
876     const BorderValue& sb = style().borderEnd();
877     if (sb.style() == BHIDDEN)
878         return -1;
879     if (sb.style() > BHIDDEN)
880         borderWidth = sb.width();
881
882     if (RenderTableCol* colGroup = table()->colElement(totalCols - 1)) {
883         const BorderValue& gb = colGroup->style().borderEnd();
884         if (gb.style() == BHIDDEN)
885             return -1;
886         if (gb.style() > BHIDDEN && gb.width() > borderWidth)
887             borderWidth = gb.width();
888     }
889
890     bool allHidden = true;
891     for (unsigned r = 0; r < m_grid.size(); r++) {
892         const CellStruct& current = cellAt(r, totalCols - 1);
893         if (!current.hasCells())
894             continue;
895         // FIXME: Don't repeat for the same cell
896         const BorderValue& cb = current.primaryCell()->style().borderEnd(); // FIXME: Make this work with perpendicular and flipped cells.
897         const BorderValue& rb = current.primaryCell()->parent()->style().borderEnd();
898         if (cb.style() == BHIDDEN || rb.style() == BHIDDEN)
899             continue;
900         allHidden = false;
901         if (cb.style() > BHIDDEN && cb.width() > borderWidth)
902             borderWidth = cb.width();
903         if (rb.style() > BHIDDEN && rb.width() > borderWidth)
904             borderWidth = rb.width();
905     }
906     if (allHidden)
907         return -1;
908
909     return (borderWidth + (table()->style().isLeftToRightDirection() ? 1 : 0)) / 2;
910 }
911
912 void RenderTableSection::recalcOuterBorder()
913 {
914     m_outerBorderBefore = calcOuterBorderBefore();
915     m_outerBorderAfter = calcOuterBorderAfter();
916     m_outerBorderStart = calcOuterBorderStart();
917     m_outerBorderEnd = calcOuterBorderEnd();
918 }
919
920 int RenderTableSection::firstLineBaseline() const
921 {
922     if (!m_grid.size())
923         return -1;
924
925     int firstLineBaseline = m_grid[0].baseline;
926     if (firstLineBaseline)
927         return firstLineBaseline + m_rowPos[0];
928
929     firstLineBaseline = -1;
930     const Row& firstRow = m_grid[0].row;
931     for (size_t i = 0; i < firstRow.size(); ++i) {
932         const CellStruct& cs = firstRow.at(i);
933         const RenderTableCell* cell = cs.primaryCell();
934         // Only cells with content have a baseline
935         if (cell && cell->contentLogicalHeight())
936             firstLineBaseline = std::max<int>(firstLineBaseline, cell->logicalTop() + cell->borderAndPaddingBefore() + cell->contentLogicalHeight());
937     }
938
939     return firstLineBaseline;
940 }
941
942 void RenderTableSection::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
943 {
944     // put this back in when all layout tests can handle it
945     // ASSERT(!needsLayout());
946     // avoid crashing on bugs that cause us to paint with dirty layout
947     if (needsLayout())
948         return;
949     
950     unsigned totalRows = m_grid.size();
951     unsigned totalCols = table()->columns().size();
952
953     if (!totalRows || !totalCols)
954         return;
955
956     LayoutPoint adjustedPaintOffset = paintOffset + location();
957
958     PaintPhase phase = paintInfo.phase;
959     bool pushedClip = pushContentsClip(paintInfo, adjustedPaintOffset);
960     paintObject(paintInfo, adjustedPaintOffset);
961     if (pushedClip)
962         popContentsClip(paintInfo, phase, adjustedPaintOffset);
963
964     if ((phase == PaintPhaseOutline || phase == PaintPhaseSelfOutline) && style().visibility() == VISIBLE)
965         paintOutline(paintInfo, LayoutRect(adjustedPaintOffset, size()));
966 }
967
968 static inline bool compareCellPositions(RenderTableCell* elem1, RenderTableCell* elem2)
969 {
970     return elem1->rowIndex() < elem2->rowIndex();
971 }
972
973 // This comparison is used only when we have overflowing cells as we have an unsorted array to sort. We thus need
974 // to sort both on rows and columns to properly repaint.
975 static inline bool compareCellPositionsWithOverflowingCells(RenderTableCell* elem1, RenderTableCell* elem2)
976 {
977     if (elem1->rowIndex() != elem2->rowIndex())
978         return elem1->rowIndex() < elem2->rowIndex();
979
980     return elem1->col() < elem2->col();
981 }
982
983 void RenderTableSection::paintCell(RenderTableCell* cell, PaintInfo& paintInfo, const LayoutPoint& paintOffset)
984 {
985     LayoutPoint cellPoint = flipForWritingModeForChild(cell, paintOffset);
986     PaintPhase paintPhase = paintInfo.phase;
987     RenderTableRow* row = toRenderTableRow(cell->parent());
988
989     if (paintPhase == PaintPhaseBlockBackground || paintPhase == PaintPhaseChildBlockBackground) {
990         // We need to handle painting a stack of backgrounds.  This stack (from bottom to top) consists of
991         // the column group, column, row group, row, and then the cell.
992         RenderTableCol* column = table()->colElement(cell->col());
993         RenderTableCol* columnGroup = column ? column->enclosingColumnGroup() : 0;
994
995         // Column groups and columns first.
996         // FIXME: Columns and column groups do not currently support opacity, and they are being painted "too late" in
997         // the stack, since we have already opened a transparency layer (potentially) for the table row group.
998         // Note that we deliberately ignore whether or not the cell has a layer, since these backgrounds paint "behind" the
999         // cell.
1000         cell->paintBackgroundsBehindCell(paintInfo, cellPoint, columnGroup);
1001         cell->paintBackgroundsBehindCell(paintInfo, cellPoint, column);
1002
1003         // Paint the row group next.
1004         cell->paintBackgroundsBehindCell(paintInfo, cellPoint, this);
1005
1006         // Paint the row next, but only if it doesn't have a layer.  If a row has a layer, it will be responsible for
1007         // painting the row background for the cell.
1008         if (!row->hasSelfPaintingLayer())
1009             cell->paintBackgroundsBehindCell(paintInfo, cellPoint, row);
1010     }
1011     if ((!cell->hasSelfPaintingLayer() && !row->hasSelfPaintingLayer()))
1012         cell->paint(paintInfo, cellPoint);
1013 }
1014
1015 LayoutRect RenderTableSection::logicalRectForWritingModeAndDirection(const LayoutRect& rect) const
1016 {
1017     LayoutRect tableAlignedRect(rect);
1018
1019     flipForWritingMode(tableAlignedRect);
1020
1021     if (!style().isHorizontalWritingMode())
1022         tableAlignedRect = tableAlignedRect.transposedRect();
1023
1024     const Vector<int>& columnPos = table()->columnPositions();
1025     // FIXME: The table's direction should determine our row's direction, not the section's (see bug 96691).
1026     if (!style().isLeftToRightDirection())
1027         tableAlignedRect.setX(columnPos[columnPos.size() - 1] - tableAlignedRect.maxX());
1028
1029     return tableAlignedRect;
1030 }
1031
1032 CellSpan RenderTableSection::dirtiedRows(const LayoutRect& damageRect) const
1033 {
1034     if (m_forceSlowPaintPathWithOverflowingCell) 
1035         return fullTableRowSpan();
1036
1037     CellSpan coveredRows = spannedRows(damageRect);
1038
1039     // To repaint the border we might need to repaint first or last row even if they are not spanned themselves.
1040     if (coveredRows.start() >= m_rowPos.size() - 1 && m_rowPos[m_rowPos.size() - 1] + table()->outerBorderAfter() >= damageRect.y())
1041         --coveredRows.start();
1042
1043     if (!coveredRows.end() && m_rowPos[0] - table()->outerBorderBefore() <= damageRect.maxY())
1044         ++coveredRows.end();
1045
1046     return coveredRows;
1047 }
1048
1049 CellSpan RenderTableSection::dirtiedColumns(const LayoutRect& damageRect) const
1050 {
1051     if (m_forceSlowPaintPathWithOverflowingCell) 
1052         return fullTableColumnSpan();
1053
1054     CellSpan coveredColumns = spannedColumns(damageRect);
1055
1056     const Vector<int>& columnPos = table()->columnPositions();
1057     // To repaint the border we might need to repaint first or last column even if they are not spanned themselves.
1058     if (coveredColumns.start() >= columnPos.size() - 1 && columnPos[columnPos.size() - 1] + table()->outerBorderEnd() >= damageRect.x())
1059         --coveredColumns.start();
1060
1061     if (!coveredColumns.end() && columnPos[0] - table()->outerBorderStart() <= damageRect.maxX())
1062         ++coveredColumns.end();
1063
1064     return coveredColumns;
1065 }
1066
1067 CellSpan RenderTableSection::spannedRows(const LayoutRect& flippedRect) const
1068 {
1069     // Find the first row that starts after rect top.
1070     unsigned nextRow = std::upper_bound(m_rowPos.begin(), m_rowPos.end(), flippedRect.y()) - m_rowPos.begin();
1071
1072     if (nextRow == m_rowPos.size())
1073         return CellSpan(m_rowPos.size() - 1, m_rowPos.size() - 1); // After all rows.
1074
1075     unsigned startRow = nextRow > 0 ? nextRow - 1 : 0;
1076
1077     // Find the first row that starts after rect bottom.
1078     unsigned endRow;
1079     if (m_rowPos[nextRow] >= flippedRect.maxY())
1080         endRow = nextRow;
1081     else {
1082         endRow = std::upper_bound(m_rowPos.begin() + nextRow, m_rowPos.end(), flippedRect.maxY()) - m_rowPos.begin();
1083         if (endRow == m_rowPos.size())
1084             endRow = m_rowPos.size() - 1;
1085     }
1086
1087     return CellSpan(startRow, endRow);
1088 }
1089
1090 CellSpan RenderTableSection::spannedColumns(const LayoutRect& flippedRect) const
1091 {
1092     const Vector<int>& columnPos = table()->columnPositions();
1093
1094     // Find the first column that starts after rect left.
1095     // lower_bound doesn't handle the edge between two cells properly as it would wrongly return the
1096     // cell on the logical top/left.
1097     // upper_bound on the other hand properly returns the cell on the logical bottom/right, which also
1098     // matches the behavior of other browsers.
1099     unsigned nextColumn = std::upper_bound(columnPos.begin(), columnPos.end(), flippedRect.x()) - columnPos.begin();
1100
1101     if (nextColumn == columnPos.size())
1102         return CellSpan(columnPos.size() - 1, columnPos.size() - 1); // After all columns.
1103
1104     unsigned startColumn = nextColumn > 0 ? nextColumn - 1 : 0;
1105
1106     // Find the first column that starts after rect right.
1107     unsigned endColumn;
1108     if (columnPos[nextColumn] >= flippedRect.maxX())
1109         endColumn = nextColumn;
1110     else {
1111         endColumn = std::upper_bound(columnPos.begin() + nextColumn, columnPos.end(), flippedRect.maxX()) - columnPos.begin();
1112         if (endColumn == columnPos.size())
1113             endColumn = columnPos.size() - 1;
1114     }
1115
1116     return CellSpan(startColumn, endColumn);
1117 }
1118
1119 void RenderTableSection::paintRowGroupBorder(const PaintInfo& paintInfo, bool antialias, LayoutRect rect, BoxSide side, CSSPropertyID borderColor, EBorderStyle borderStyle, EBorderStyle tableBorderStyle)
1120 {
1121     if (tableBorderStyle == BHIDDEN)
1122         return;
1123     rect.intersect(paintInfo.rect);
1124     if (rect.isEmpty())
1125         return;
1126     drawLineForBoxSide(paintInfo.context, rect.x(), rect.y(), rect.x() + rect.width(), rect.y() + rect.height(), side, style().visitedDependentColor(borderColor), borderStyle, 0, 0, antialias);
1127 }
1128
1129 int RenderTableSection::offsetLeftForRowGroupBorder(RenderTableCell* cell, const LayoutRect& rowGroupRect, unsigned row)
1130 {
1131     if (style().isHorizontalWritingMode()) {
1132         if (style().isLeftToRightDirection())
1133             return cell ? cell->x().toInt() + cell->width().toInt() : 0; 
1134         return -outerBorderLeft(&style());
1135     }
1136     bool isLastRow = row + 1 == m_grid.size();
1137     return rowGroupRect.width().toInt() - m_rowPos[row + 1] + (isLastRow ? -outerBorderLeft(&style()) : 0);
1138 }
1139
1140 int RenderTableSection::offsetTopForRowGroupBorder(RenderTableCell* cell, BoxSide borderSide, unsigned row)
1141 {
1142     bool isLastRow = row + 1 == m_grid.size();
1143     if (style().isHorizontalWritingMode())
1144         return m_rowPos[row] + (!row && borderSide == BSRight ? -outerBorderTop(&style()) : isLastRow && borderSide == BSLeft ? outerBorderTop(&style()) : 0);
1145     if (style().isLeftToRightDirection())
1146         return (cell ? cell->y().toInt() + cell->height().toInt() : 0) + (borderSide == BSLeft ? outerBorderTop(&style()) : 0);
1147     return borderSide == BSRight ? -outerBorderTop(&style()) : 0;
1148 }
1149
1150 int RenderTableSection::verticalRowGroupBorderHeight(RenderTableCell* cell, const LayoutRect& rowGroupRect, unsigned row)
1151 {
1152     bool isLastRow = row + 1 == m_grid.size();
1153     if (style().isHorizontalWritingMode())
1154         return m_rowPos[row + 1] - m_rowPos[row] + (!row ? outerBorderTop(&style()) : isLastRow ? outerBorderBottom(&style()) : 0);
1155     if (style().isLeftToRightDirection())
1156         return rowGroupRect.height().toInt() - (cell ? cell->y().toInt() + cell->height().toInt() : 0) + outerBorderBottom(&style());
1157     return cell ? rowGroupRect.height().toInt() - (cell->y().toInt() - cell->height().toInt()) : 0;
1158 }
1159
1160 int RenderTableSection::horizontalRowGroupBorderWidth(RenderTableCell* cell, const LayoutRect& rowGroupRect, unsigned row, unsigned column)
1161 {
1162     if (style().isHorizontalWritingMode()) {
1163         if (style().isLeftToRightDirection())
1164             return rowGroupRect.width().toInt() - (cell ? cell->x().toInt() + cell->width().toInt() : 0) + (!column ? outerBorderLeft(&style()) : column == table()->numEffCols() ? outerBorderRight(&style()) : 0);
1165         return cell ? rowGroupRect.width().toInt() - (cell->x().toInt() - cell->width().toInt()) : 0;
1166     }
1167     bool isLastRow = row + 1 == m_grid.size();
1168     return m_rowPos[row + 1] - m_rowPos[row] + (isLastRow ? outerBorderLeft(&style()) : !row ? outerBorderRight(&style()) : 0);
1169 }
1170
1171 void RenderTableSection::paintRowGroupBorderIfRequired(const PaintInfo& paintInfo, const LayoutPoint& paintOffset, unsigned row, unsigned column, BoxSide borderSide, RenderTableCell* cell)
1172 {
1173     if (table()->currentBorderValue()->precedence() > BROWGROUP)
1174         return;
1175     if (paintInfo.context->paintingDisabled())
1176         return;
1177
1178     const RenderStyle& style = this->style();
1179     bool antialias = shouldAntialiasLines(paintInfo.context);
1180     LayoutRect rowGroupRect = LayoutRect(paintOffset, size());
1181     rowGroupRect.moveBy(-LayoutPoint(outerBorderLeft(&style), (borderSide == BSRight) ? 0 : outerBorderTop(&style)));
1182
1183     switch (borderSide) {
1184     case BSTop:
1185         paintRowGroupBorder(paintInfo, antialias, LayoutRect(paintOffset.x() + offsetLeftForRowGroupBorder(cell, rowGroupRect, row), rowGroupRect.y(), 
1186             horizontalRowGroupBorderWidth(cell, rowGroupRect, row, column), style.borderTop().width()), BSTop, CSSPropertyBorderTopColor, style.borderTopStyle(), table()->style().borderTopStyle());
1187         break;
1188     case BSBottom:
1189         paintRowGroupBorder(paintInfo, antialias, LayoutRect(paintOffset.x() + offsetLeftForRowGroupBorder(cell, rowGroupRect, row), rowGroupRect.y() + rowGroupRect.height(), 
1190             horizontalRowGroupBorderWidth(cell, rowGroupRect, row, column), style.borderBottom().width()), BSBottom, CSSPropertyBorderBottomColor, style.borderBottomStyle(), table()->style().borderBottomStyle());
1191         break;
1192     case BSLeft:
1193         paintRowGroupBorder(paintInfo, antialias, LayoutRect(rowGroupRect.x(), rowGroupRect.y() + offsetTopForRowGroupBorder(cell, borderSide, row), style.borderLeft().width(),
1194             verticalRowGroupBorderHeight(cell, rowGroupRect, row)), BSLeft, CSSPropertyBorderLeftColor, style.borderLeftStyle(), table()->style().borderLeftStyle());
1195         break;
1196     case BSRight:
1197         paintRowGroupBorder(paintInfo, antialias, LayoutRect(rowGroupRect.x() + rowGroupRect.width(), rowGroupRect.y() + offsetTopForRowGroupBorder(cell, borderSide, row), style.borderRight().width(),
1198             verticalRowGroupBorderHeight(cell, rowGroupRect, row)), BSRight, CSSPropertyBorderRightColor, style.borderRightStyle(), table()->style().borderRightStyle());
1199         break;
1200     default:
1201         break;
1202     }
1203
1204 }
1205
1206 static BoxSide physicalBorderForDirection(RenderStyle* styleForCellFlow, CollapsedBorderSide side)
1207 {
1208
1209     switch (side) {
1210     case CBSStart:
1211         if (styleForCellFlow->isHorizontalWritingMode())
1212             return styleForCellFlow->isLeftToRightDirection() ? BSLeft : BSRight;
1213         return styleForCellFlow->isLeftToRightDirection() ? BSTop : BSBottom;
1214     case CBSEnd:
1215         if (styleForCellFlow->isHorizontalWritingMode())
1216             return styleForCellFlow->isLeftToRightDirection() ? BSRight : BSLeft;
1217         return styleForCellFlow->isLeftToRightDirection() ? BSBottom : BSTop;
1218     case CBSBefore:
1219         if (styleForCellFlow->isHorizontalWritingMode())
1220             return BSTop;
1221         return styleForCellFlow->isLeftToRightDirection() ? BSRight : BSLeft;
1222     case CBSAfter:
1223         if (styleForCellFlow->isHorizontalWritingMode())
1224             return BSBottom;
1225         return styleForCellFlow->isLeftToRightDirection() ? BSLeft : BSRight;
1226     default:
1227         ASSERT_NOT_REACHED();
1228         return BSLeft;
1229     }
1230 }
1231
1232 void RenderTableSection::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1233 {
1234     PaintPhase paintPhase = paintInfo.phase;
1235
1236     LayoutRect localRepaintRect = paintInfo.rect;
1237     localRepaintRect.moveBy(-paintOffset);
1238     localRepaintRect.inflate(maximalOutlineSize(paintPhase));
1239
1240     LayoutRect tableAlignedRect = logicalRectForWritingModeAndDirection(localRepaintRect);
1241
1242     CellSpan dirtiedRows = this->dirtiedRows(tableAlignedRect);
1243     CellSpan dirtiedColumns = this->dirtiedColumns(tableAlignedRect);
1244
1245     if (dirtiedColumns.start() < dirtiedColumns.end()) {
1246         if (!m_hasMultipleCellLevels && !m_overflowingCells.size()) {
1247             if (paintInfo.phase == PaintPhaseCollapsedTableBorders) {
1248                 // Collapsed borders are painted from the bottom right to the top left so that precedence
1249                 // due to cell position is respected. We need to paint one row beyond the topmost dirtied
1250                 // row to calculate its collapsed border value.
1251                 unsigned startRow = dirtiedRows.start() ? dirtiedRows.start() - 1 : 0;
1252                 for (unsigned r = dirtiedRows.end(); r > startRow; r--) {
1253                     unsigned row = r - 1;
1254                     bool shouldPaintRowGroupBorder = false;
1255                     for (unsigned c = dirtiedColumns.end(); c > dirtiedColumns.start(); c--) {
1256                         unsigned col = c - 1;
1257                         CellStruct& current = cellAt(row, col);
1258                         RenderTableCell* cell = current.primaryCell();
1259                         if (!cell) {
1260                             if (!c)
1261                                 paintRowGroupBorderIfRequired(paintInfo, paintOffset, row, col, physicalBorderForDirection(&style(), CBSStart));
1262                             else if (c == table()->numEffCols())
1263                                 paintRowGroupBorderIfRequired(paintInfo, paintOffset, row, col, physicalBorderForDirection(&style(), CBSEnd));
1264                             shouldPaintRowGroupBorder = true;
1265                             continue;
1266                         }
1267                         if ((row > dirtiedRows.start() && primaryCellAt(row - 1, col) == cell) || (col > dirtiedColumns.start() && primaryCellAt(row, col - 1) == cell))
1268                             continue;
1269                         
1270                         // If we had a run of null cells paint their corresponding section of the row group's border if necessary. Note that
1271                         // this will only happen once within a row as the null cells will always be clustered together on one end of the row.
1272                         if (shouldPaintRowGroupBorder) {
1273                             if (r == m_grid.size())
1274                                 paintRowGroupBorderIfRequired(paintInfo, paintOffset, row, col, physicalBorderForDirection(&style(), CBSAfter), cell);
1275                             else if (!row && !table()->sectionAbove(this))
1276                                 paintRowGroupBorderIfRequired(paintInfo, paintOffset, row, col, physicalBorderForDirection(&style(), CBSBefore), cell);
1277                             shouldPaintRowGroupBorder = false;
1278                         }
1279
1280                         LayoutPoint cellPoint = flipForWritingModeForChild(cell, paintOffset);
1281                         cell->paintCollapsedBorders(paintInfo, cellPoint);
1282                     }
1283                 }
1284             } else {
1285                 // Draw the dirty cells in the order that they appear.
1286                 for (unsigned r = dirtiedRows.start(); r < dirtiedRows.end(); r++) {
1287                     RenderTableRow* row = m_grid[r].rowRenderer;
1288                     if (row && !row->hasSelfPaintingLayer())
1289                         row->paintOutlineForRowIfNeeded(paintInfo, paintOffset);
1290                     for (unsigned c = dirtiedColumns.start(); c < dirtiedColumns.end(); c++) {
1291                         CellStruct& current = cellAt(r, c);
1292                         RenderTableCell* cell = current.primaryCell();
1293                         if (!cell || (r > dirtiedRows.start() && primaryCellAt(r - 1, c) == cell) || (c > dirtiedColumns.start() && primaryCellAt(r, c - 1) == cell))
1294                             continue;
1295                         paintCell(cell, paintInfo, paintOffset);
1296                     }
1297                 }
1298             }
1299         } else {
1300             // The overflowing cells should be scarce to avoid adding a lot of cells to the HashSet.
1301 #ifndef NDEBUG
1302             unsigned totalRows = m_grid.size();
1303             unsigned totalCols = table()->columns().size();
1304             ASSERT(m_overflowingCells.size() < totalRows * totalCols * gMaxAllowedOverflowingCellRatioForFastPaintPath);
1305 #endif
1306
1307             // To make sure we properly repaint the section, we repaint all the overflowing cells that we collected.
1308             Vector<RenderTableCell*> cells;
1309             copyToVector(m_overflowingCells, cells);
1310
1311             HashSet<RenderTableCell*> spanningCells;
1312
1313             for (unsigned r = dirtiedRows.start(); r < dirtiedRows.end(); r++) {
1314                 RenderTableRow* row = m_grid[r].rowRenderer;
1315                 if (row && !row->hasSelfPaintingLayer())
1316                     row->paintOutlineForRowIfNeeded(paintInfo, paintOffset);
1317                 for (unsigned c = dirtiedColumns.start(); c < dirtiedColumns.end(); c++) {
1318                     CellStruct& current = cellAt(r, c);
1319                     if (!current.hasCells())
1320                         continue;
1321                     for (unsigned i = 0; i < current.cells.size(); ++i) {
1322                         if (m_overflowingCells.contains(current.cells[i]))
1323                             continue;
1324
1325                         if (current.cells[i]->rowSpan() > 1 || current.cells[i]->colSpan() > 1) {
1326                             if (!spanningCells.add(current.cells[i]).isNewEntry)
1327                                 continue;
1328                         }
1329
1330                         cells.append(current.cells[i]);
1331                     }
1332                 }
1333             }
1334
1335             // Sort the dirty cells by paint order.
1336             if (!m_overflowingCells.size())
1337                 std::stable_sort(cells.begin(), cells.end(), compareCellPositions);
1338             else
1339                 std::sort(cells.begin(), cells.end(), compareCellPositionsWithOverflowingCells);
1340
1341             if (paintInfo.phase == PaintPhaseCollapsedTableBorders) {
1342                 for (unsigned i = cells.size(); i > 0; --i) {
1343                     LayoutPoint cellPoint = flipForWritingModeForChild(cells[i - 1], paintOffset);
1344                     cells[i - 1]->paintCollapsedBorders(paintInfo, cellPoint);
1345                 }
1346             } else {
1347                 for (unsigned i = 0; i < cells.size(); ++i)
1348                     paintCell(cells[i], paintInfo, paintOffset);
1349             }
1350         }
1351     }
1352 }
1353
1354 void RenderTableSection::imageChanged(WrappedImagePtr, const IntRect*)
1355 {
1356     // FIXME: Examine cells and repaint only the rect the image paints in.
1357     repaint();
1358 }
1359
1360 void RenderTableSection::recalcCells()
1361 {
1362     ASSERT(m_needsCellRecalc);
1363     // We reset the flag here to ensure that addCell() works. This is safe to do because we clear the grid
1364     // and update its dimensions to be consistent with the table's column representation before we rebuild
1365     // the grid using addCell().
1366     m_needsCellRecalc = false;
1367
1368     m_cCol = 0;
1369     m_cRow = 0;
1370     m_grid.clear();
1371
1372     for (RenderTableRow* row = firstRow(); row; row = row->nextRow()) {
1373         unsigned insertionRow = m_cRow;
1374         m_cRow++;
1375         m_cCol = 0;
1376         ensureRows(m_cRow);
1377
1378         m_grid[insertionRow].rowRenderer = row;
1379         row->setRowIndex(insertionRow);
1380         setRowLogicalHeightToRowStyleLogicalHeightIfNotRelative(m_grid[insertionRow]);
1381
1382         for (RenderTableCell* cell = row->firstCell(); cell; cell = cell->nextCell())
1383             addCell(cell, row);
1384     }
1385
1386     m_grid.shrinkToFit();
1387     setNeedsLayout();
1388 }
1389
1390 // FIXME: This function could be made O(1) in certain cases (like for the non-most-constrainive cells' case).
1391 void RenderTableSection::rowLogicalHeightChanged(unsigned rowIndex)
1392 {
1393     if (needsCellRecalc())
1394         return;
1395
1396     setRowLogicalHeightToRowStyleLogicalHeightIfNotRelative(m_grid[rowIndex]);
1397
1398     for (RenderTableCell* cell = m_grid[rowIndex].rowRenderer->firstCell(); cell; cell = cell->nextCell())
1399         updateLogicalHeightForCell(m_grid[rowIndex], cell);
1400 }
1401
1402 void RenderTableSection::setNeedsCellRecalc()
1403 {
1404     m_needsCellRecalc = true;
1405
1406     // Clear the grid now to ensure that we don't hold onto any stale pointers (e.g. a cell renderer that is being removed).
1407     m_grid.clear();
1408
1409     if (RenderTable* t = table())
1410         t->setNeedsSectionRecalc();
1411 }
1412
1413 unsigned RenderTableSection::numColumns() const
1414 {
1415     ASSERT(!m_needsCellRecalc);
1416     unsigned result = 0;
1417     
1418     for (unsigned r = 0; r < m_grid.size(); ++r) {
1419         for (unsigned c = result; c < table()->numEffCols(); ++c) {
1420             const CellStruct& cell = cellAt(r, c);
1421             if (cell.hasCells() || cell.inColSpan)
1422                 result = c;
1423         }
1424     }
1425     
1426     return result + 1;
1427 }
1428
1429 const BorderValue& RenderTableSection::borderAdjoiningStartCell(const RenderTableCell* cell) const
1430 {
1431     ASSERT(cell->isFirstOrLastCellInRow());
1432     return hasSameDirectionAs(cell) ? style().borderStart() : style().borderEnd();
1433 }
1434
1435 const BorderValue& RenderTableSection::borderAdjoiningEndCell(const RenderTableCell* cell) const
1436 {
1437     ASSERT(cell->isFirstOrLastCellInRow());
1438     return hasSameDirectionAs(cell) ? style().borderEnd() : style().borderStart();
1439 }
1440
1441 const RenderTableCell* RenderTableSection::firstRowCellAdjoiningTableStart() const
1442 {
1443     unsigned adjoiningStartCellColumnIndex = hasSameDirectionAs(table()) ? 0 : table()->lastColumnIndex();
1444     return cellAt(0, adjoiningStartCellColumnIndex).primaryCell();
1445 }
1446
1447 const RenderTableCell* RenderTableSection::firstRowCellAdjoiningTableEnd() const
1448 {
1449     unsigned adjoiningEndCellColumnIndex = hasSameDirectionAs(table()) ? table()->lastColumnIndex() : 0;
1450     return cellAt(0, adjoiningEndCellColumnIndex).primaryCell();
1451 }
1452
1453 void RenderTableSection::appendColumn(unsigned pos)
1454 {
1455     ASSERT(!m_needsCellRecalc);
1456
1457     for (unsigned row = 0; row < m_grid.size(); ++row)
1458         m_grid[row].row.resize(pos + 1);
1459 }
1460
1461 void RenderTableSection::splitColumn(unsigned pos, unsigned first)
1462 {
1463     ASSERT(!m_needsCellRecalc);
1464
1465     if (m_cCol > pos)
1466         m_cCol++;
1467     for (unsigned row = 0; row < m_grid.size(); ++row) {
1468         Row& r = m_grid[row].row;
1469         r.insert(pos + 1, CellStruct());
1470         if (r[pos].hasCells()) {
1471             r[pos + 1].cells.appendVector(r[pos].cells);
1472             RenderTableCell* cell = r[pos].primaryCell();
1473             ASSERT(cell);
1474             ASSERT(cell->colSpan() >= (r[pos].inColSpan ? 1u : 0));
1475             unsigned colleft = cell->colSpan() - r[pos].inColSpan;
1476             if (first > colleft)
1477               r[pos + 1].inColSpan = 0;
1478             else
1479               r[pos + 1].inColSpan = first + r[pos].inColSpan;
1480         } else {
1481             r[pos + 1].inColSpan = 0;
1482         }
1483     }
1484 }
1485
1486 // Hit Testing
1487 bool RenderTableSection::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
1488 {
1489     // If we have no children then we have nothing to do.
1490     if (!firstRow())
1491         return false;
1492
1493     // Table sections cannot ever be hit tested.  Effectively they do not exist.
1494     // Just forward to our children always.
1495     LayoutPoint adjustedLocation = accumulatedOffset + location();
1496
1497     if (hasOverflowClip() && !locationInContainer.intersects(overflowClipRect(adjustedLocation, locationInContainer.region())))
1498         return false;
1499
1500     if (hasOverflowingCell()) {
1501         for (RenderTableRow* row = lastRow(); row; row = row->previousRow()) {
1502             // FIXME: We have to skip over inline flows, since they can show up inside table rows
1503             // at the moment (a demoted inline <form> for example). If we ever implement a
1504             // table-specific hit-test method (which we should do for performance reasons anyway),
1505             // then we can remove this check.
1506             if (!row->hasSelfPaintingLayer()) {
1507                 LayoutPoint childPoint = flipForWritingModeForChild(row, adjustedLocation);
1508                 if (row->nodeAtPoint(request, result, locationInContainer, childPoint, action)) {
1509                     updateHitTestResult(result, toLayoutPoint(locationInContainer.point() - childPoint));
1510                     return true;
1511                 }
1512             }
1513         }
1514         return false;
1515     }
1516
1517     recalcCellsIfNeeded();
1518
1519     LayoutRect hitTestRect = locationInContainer.boundingBox();
1520     hitTestRect.moveBy(-adjustedLocation);
1521
1522     LayoutRect tableAlignedRect = logicalRectForWritingModeAndDirection(hitTestRect);
1523     CellSpan rowSpan = spannedRows(tableAlignedRect);
1524     CellSpan columnSpan = spannedColumns(tableAlignedRect);
1525
1526     // Now iterate over the spanned rows and columns.
1527     for (unsigned hitRow = rowSpan.start(); hitRow < rowSpan.end(); ++hitRow) {
1528         for (unsigned hitColumn = columnSpan.start(); hitColumn < columnSpan.end(); ++hitColumn) {
1529             CellStruct& current = cellAt(hitRow, hitColumn);
1530
1531             // If the cell is empty, there's nothing to do
1532             if (!current.hasCells())
1533                 continue;
1534
1535             for (unsigned i = current.cells.size() ; i; ) {
1536                 --i;
1537                 RenderTableCell* cell = current.cells[i];
1538                 LayoutPoint cellPoint = flipForWritingModeForChild(cell, adjustedLocation);
1539                 if (static_cast<RenderObject*>(cell)->nodeAtPoint(request, result, locationInContainer, cellPoint, action)) {
1540                     updateHitTestResult(result, locationInContainer.point() - toLayoutSize(cellPoint));
1541                     return true;
1542                 }
1543             }
1544             if (!result.isRectBasedTest())
1545                 break;
1546         }
1547         if (!result.isRectBasedTest())
1548             break;
1549     }
1550
1551     return false;
1552 }
1553
1554 void RenderTableSection::removeCachedCollapsedBorders(const RenderTableCell* cell)
1555 {
1556     if (!table()->collapseBorders())
1557         return;
1558     
1559     for (int side = CBSBefore; side <= CBSEnd; ++side)
1560         m_cellsCollapsedBorders.remove(std::make_pair(cell, side));
1561 }
1562
1563 void RenderTableSection::setCachedCollapsedBorder(const RenderTableCell* cell, CollapsedBorderSide side, CollapsedBorderValue border)
1564 {
1565     ASSERT(table()->collapseBorders());
1566     m_cellsCollapsedBorders.set(std::make_pair(cell, side), border);
1567 }
1568
1569 CollapsedBorderValue& RenderTableSection::cachedCollapsedBorder(const RenderTableCell* cell, CollapsedBorderSide side)
1570 {
1571     ASSERT(table()->collapseBorders());
1572     HashMap<std::pair<const RenderTableCell*, int>, CollapsedBorderValue>::iterator it = m_cellsCollapsedBorders.find(std::make_pair(cell, side));
1573     ASSERT(it != m_cellsCollapsedBorders.end());
1574     return it->value;
1575 }
1576
1577 RenderTableSection* RenderTableSection::createAnonymousWithParentRenderer(const RenderObject* parent)
1578 {
1579     auto section = new RenderTableSection(parent->document(), RenderStyle::createAnonymousStyleWithDisplay(&parent->style(), TABLE_ROW_GROUP));
1580     section->initializeStyle();
1581     return section;
1582 }
1583
1584 void RenderTableSection::setLogicalPositionForCell(RenderTableCell* cell, unsigned effectiveColumn) const
1585 {
1586     LayoutPoint oldCellLocation = cell->location();
1587
1588     LayoutPoint cellLocation(0, m_rowPos[cell->rowIndex()]);
1589     int horizontalBorderSpacing = table()->hBorderSpacing();
1590
1591     // FIXME: The table's direction should determine our row's direction, not the section's (see bug 96691).
1592     if (!style().isLeftToRightDirection())
1593         cellLocation.setX(table()->columnPositions()[table()->numEffCols()] - table()->columnPositions()[table()->colToEffCol(cell->col() + cell->colSpan())] + horizontalBorderSpacing);
1594     else
1595         cellLocation.setX(table()->columnPositions()[effectiveColumn] + horizontalBorderSpacing);
1596
1597     cell->setLogicalLocation(cellLocation);
1598     view().addLayoutDelta(oldCellLocation - cell->location());
1599 }
1600
1601 } // namespace WebCore