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