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