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