1a13d8c4f015c453874d2f5dc079b42de9881a85
[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] + minimumValueForLength(m_grid[r].logicalHeight, 0, viewRenderer).round(), 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[cellStartRow].baseline = max(m_grid[cellStartRow].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     ASSERT(!needsCellRecalc());
407     ASSERT(!table()->needsSectionRecalc());
408
409     // addChild may over-grow m_grid but we don't want to throw away the memory too early as addChild
410     // can be called in a loop (e.g during parsing). Doing it now ensures we have a stable-enough structure.
411     m_grid.shrinkToFit();
412
413     LayoutStateMaintainer statePusher(view(), this, locationOffset(), style()->isFlippedBlocksWritingMode());
414     for (RenderObject* child = children()->firstChild(); child; child = child->nextSibling()) {
415         if (child->isTableRow()) {
416             child->layoutIfNeeded();
417             ASSERT(!child->needsLayout());
418         }
419     }
420     statePusher.pop();
421     setNeedsLayout(false);
422 }
423
424 void RenderTableSection::distributeExtraLogicalHeightToPercentRows(int& extraLogicalHeight, int totalPercent)
425 {
426     if (!totalPercent)
427         return;
428
429     unsigned totalRows = m_grid.size();
430     int totalHeight = m_rowPos[totalRows] + extraLogicalHeight;
431     int totalLogicalHeightAdded = 0;
432     totalPercent = min(totalPercent, 100);
433     int rowHeight = m_rowPos[1] - m_rowPos[0];
434     for (unsigned r = 0; r < totalRows; ++r) {
435         if (totalPercent > 0 && m_grid[r].logicalHeight.isPercent()) {
436             int toAdd = min<int>(extraLogicalHeight, (totalHeight * m_grid[r].logicalHeight.percent() / 100) - rowHeight);
437             // If toAdd is negative, then we don't want to shrink the row (this bug
438             // affected Outlook Web Access).
439             toAdd = max(0, toAdd);
440             totalLogicalHeightAdded += toAdd;
441             extraLogicalHeight -= toAdd;
442             totalPercent -= m_grid[r].logicalHeight.percent();
443         }
444         ASSERT(totalRows >= 1);
445         if (r < totalRows - 1)
446             rowHeight = m_rowPos[r + 2] - m_rowPos[r + 1];
447         m_rowPos[r + 1] += totalLogicalHeightAdded;
448     }
449 }
450
451 void RenderTableSection::distributeExtraLogicalHeightToAutoRows(int& extraLogicalHeight, unsigned autoRowsCount)
452 {
453     if (!autoRowsCount)
454         return;
455
456     int totalLogicalHeightAdded = 0;
457     for (unsigned r = 0; r < m_grid.size(); ++r) {
458         if (autoRowsCount > 0 && m_grid[r].logicalHeight.isAuto()) {
459             // Recomputing |extraLogicalHeightForRow| guarantees that we properly ditribute round |extraLogicalHeight|.
460             int extraLogicalHeightForRow = extraLogicalHeight / autoRowsCount;
461             totalLogicalHeightAdded += extraLogicalHeightForRow;
462             extraLogicalHeight -= extraLogicalHeightForRow;
463             --autoRowsCount;
464         }
465         m_rowPos[r + 1] += totalLogicalHeightAdded;
466     }
467 }
468
469 void RenderTableSection::distributeRemainingExtraLogicalHeight(int& extraLogicalHeight)
470 {
471     unsigned totalRows = m_grid.size();
472
473     if (extraLogicalHeight <= 0 || !m_rowPos[totalRows])
474         return;
475
476     // FIXME: m_rowPos[totalRows] - m_rowPos[0] is the total rows' size.
477     int totalRowSize = m_rowPos[totalRows];
478     int totalLogicalHeightAdded = 0;
479     int previousRowPosition = m_rowPos[0];
480     for (unsigned r = 0; r < totalRows; r++) {
481         // weight with the original height
482         totalLogicalHeightAdded += extraLogicalHeight * (m_rowPos[r + 1] - previousRowPosition) / totalRowSize;
483         previousRowPosition = m_rowPos[r + 1];
484         m_rowPos[r + 1] += totalLogicalHeightAdded;
485     }
486
487     extraLogicalHeight -= totalLogicalHeightAdded;
488 }
489
490 int RenderTableSection::distributeExtraLogicalHeightToRows(int extraLogicalHeight)
491 {
492     if (!extraLogicalHeight)
493         return extraLogicalHeight;
494
495     unsigned totalRows = m_grid.size();
496     if (!totalRows)
497         return extraLogicalHeight;
498
499     if (!m_rowPos[totalRows] && nextSibling())
500         return extraLogicalHeight;
501
502     unsigned autoRowsCount = 0;
503     int totalPercent = 0;
504     for (unsigned r = 0; r < totalRows; r++) {
505         if (m_grid[r].logicalHeight.isAuto())
506             ++autoRowsCount;
507         else if (m_grid[r].logicalHeight.isPercent())
508             totalPercent += m_grid[r].logicalHeight.percent();
509     }
510
511     int remainingExtraLogicalHeight = extraLogicalHeight;
512     distributeExtraLogicalHeightToPercentRows(remainingExtraLogicalHeight, totalPercent);
513     distributeExtraLogicalHeightToAutoRows(remainingExtraLogicalHeight, autoRowsCount);
514     distributeRemainingExtraLogicalHeight(remainingExtraLogicalHeight);
515     return extraLogicalHeight - remainingExtraLogicalHeight;
516 }
517
518 void RenderTableSection::layoutRows()
519 {
520 #ifndef NDEBUG
521     setNeedsLayoutIsForbidden(true);
522 #endif
523
524     ASSERT(!needsLayout());
525
526     int rHeight;
527     unsigned rindx;
528     unsigned totalRows = m_grid.size();
529
530     // Set the width of our section now.  The rows will also be this width.
531     setLogicalWidth(table()->contentLogicalWidth());
532     m_overflow.clear();
533     m_overflowingCells.clear();
534     m_forceSlowPaintPathWithOverflowingCell = false;
535
536     int vspacing = table()->vBorderSpacing();
537     unsigned nEffCols = table()->numEffCols();
538
539     LayoutStateMaintainer statePusher(view(), this, locationOffset(), style()->isFlippedBlocksWritingMode());
540
541     for (unsigned r = 0; r < totalRows; r++) {
542         // Set the row's x/y position and width/height.
543         if (RenderTableRow* rowRenderer = m_grid[r].rowRenderer) {
544             rowRenderer->setLocation(LayoutPoint(0, m_rowPos[r]));
545             rowRenderer->setLogicalWidth(logicalWidth());
546             rowRenderer->setLogicalHeight(m_rowPos[r + 1] - m_rowPos[r] - vspacing);
547             rowRenderer->updateLayerTransform();
548         }
549
550         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 (HashSet<RenderBox*>* percentHeightDescendants = cell->percentHeightDescendants()) {
588                 HashSet<RenderBox*>::iterator end = percentHeightDescendants->end();
589                 for (HashSet<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->x(), cell->y() , cell->width(), cell->height());
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                     unsigned delta = cell->logicalHeight() - rHeight;
676                     for (unsigned rowIndex = rindx + cell->rowSpan(); rowIndex <= totalRows; rowIndex++)
677                         m_rowPos[rowIndex] += delta;
678                     rHeight = cell->logicalHeight();
679                 } else
680                     cell->setLogicalHeight(rHeight);
681             }
682
683             LayoutSize childOffset(cell->location() - oldCellRect.location());
684             if (childOffset.width() || childOffset.height()) {
685                 view()->addLayoutDelta(childOffset);
686
687                 // If the child moved, we have to repaint it as well as any floating/positioned
688                 // descendants.  An exception is if we need a layout.  In this case, we know we're going to
689                 // repaint ourselves (and the child) anyway.
690                 if (!table()->selfNeedsLayout() && cell->checkForRepaintDuringLayout())
691                     cell->repaintDuringLayoutIfMoved(oldCellRect);
692             }
693         }
694     }
695
696 #ifndef NDEBUG
697     setNeedsLayoutIsForbidden(false);
698 #endif
699
700     ASSERT(!needsLayout());
701
702     setLogicalHeight(m_rowPos[totalRows]);
703
704     unsigned totalCellsCount = nEffCols * totalRows;
705     int maxAllowedOverflowingCellsCount = totalCellsCount < gMinTableSizeToUseFastPaintPathWithOverflowingCell ? 0 : gMaxAllowedOverflowingCellRatioForFastPaintPath * totalCellsCount;
706
707 #ifndef NDEBUG
708     bool hasOverflowingCell = false;
709 #endif
710     // Now that our height has been determined, add in overflow from cells.
711     for (unsigned r = 0; r < totalRows; r++) {
712         for (unsigned c = 0; c < nEffCols; c++) {
713             CellStruct& cs = cellAt(r, c);
714             RenderTableCell* cell = cs.primaryCell();
715             if (!cell || cs.inColSpan)
716                 continue;
717             if (r < totalRows - 1 && cell == primaryCellAt(r + 1, c))
718                 continue;
719             addOverflowFromChild(cell);
720 #ifndef NDEBUG
721             hasOverflowingCell |= cell->hasVisualOverflow();
722 #endif
723             if (cell->hasVisualOverflow() && !m_forceSlowPaintPathWithOverflowingCell) {
724                 m_overflowingCells.add(cell);
725                 if (m_overflowingCells.size() > maxAllowedOverflowingCellsCount) {
726                     // We need to set m_forcesSlowPaintPath only if there is a least one overflowing cells as the hit testing code rely on this information.
727                     m_forceSlowPaintPathWithOverflowingCell = true;
728                     // The slow path does not make any use of the overflowing cells info, don't hold on to the memory.
729                     m_overflowingCells.clear();
730                 }
731             }
732         }
733     }
734
735     ASSERT(hasOverflowingCell == this->hasOverflowingCell());
736
737     statePusher.pop();
738 }
739
740 int RenderTableSection::calcOuterBorderBefore() const
741 {
742     unsigned totalCols = table()->numEffCols();
743     if (!m_grid.size() || !totalCols)
744         return 0;
745
746     unsigned borderWidth = 0;
747
748     const BorderValue& sb = style()->borderBefore();
749     if (sb.style() == BHIDDEN)
750         return -1;
751     if (sb.style() > BHIDDEN)
752         borderWidth = sb.width();
753
754     const BorderValue& rb = firstChild()->style()->borderBefore();
755     if (rb.style() == BHIDDEN)
756         return -1;
757     if (rb.style() > BHIDDEN && rb.width() > borderWidth)
758         borderWidth = rb.width();
759
760     bool allHidden = true;
761     for (unsigned c = 0; c < totalCols; c++) {
762         const CellStruct& current = cellAt(0, c);
763         if (current.inColSpan || !current.hasCells())
764             continue;
765         const BorderValue& cb = current.primaryCell()->style()->borderBefore(); // FIXME: Make this work with perpendicular and flipped cells.
766         // FIXME: Don't repeat for the same col group
767         RenderTableCol* colGroup = table()->colElement(c);
768         if (colGroup) {
769             const BorderValue& gb = colGroup->style()->borderBefore();
770             if (gb.style() == BHIDDEN || cb.style() == BHIDDEN)
771                 continue;
772             allHidden = false;
773             if (gb.style() > BHIDDEN && gb.width() > borderWidth)
774                 borderWidth = gb.width();
775             if (cb.style() > BHIDDEN && cb.width() > borderWidth)
776                 borderWidth = cb.width();
777         } else {
778             if (cb.style() == BHIDDEN)
779                 continue;
780             allHidden = false;
781             if (cb.style() > BHIDDEN && cb.width() > borderWidth)
782                 borderWidth = cb.width();
783         }
784     }
785     if (allHidden)
786         return -1;
787
788     return borderWidth / 2;
789 }
790
791 int RenderTableSection::calcOuterBorderAfter() const
792 {
793     unsigned totalCols = table()->numEffCols();
794     if (!m_grid.size() || !totalCols)
795         return 0;
796
797     unsigned borderWidth = 0;
798
799     const BorderValue& sb = style()->borderAfter();
800     if (sb.style() == BHIDDEN)
801         return -1;
802     if (sb.style() > BHIDDEN)
803         borderWidth = sb.width();
804
805     const BorderValue& rb = lastChild()->style()->borderAfter();
806     if (rb.style() == BHIDDEN)
807         return -1;
808     if (rb.style() > BHIDDEN && rb.width() > borderWidth)
809         borderWidth = rb.width();
810
811     bool allHidden = true;
812     for (unsigned c = 0; c < totalCols; c++) {
813         const CellStruct& current = cellAt(m_grid.size() - 1, c);
814         if (current.inColSpan || !current.hasCells())
815             continue;
816         const BorderValue& cb = current.primaryCell()->style()->borderAfter(); // FIXME: Make this work with perpendicular and flipped cells.
817         // FIXME: Don't repeat for the same col group
818         RenderTableCol* colGroup = table()->colElement(c);
819         if (colGroup) {
820             const BorderValue& gb = colGroup->style()->borderAfter();
821             if (gb.style() == BHIDDEN || cb.style() == BHIDDEN)
822                 continue;
823             allHidden = false;
824             if (gb.style() > BHIDDEN && gb.width() > borderWidth)
825                 borderWidth = gb.width();
826             if (cb.style() > BHIDDEN && cb.width() > borderWidth)
827                 borderWidth = cb.width();
828         } else {
829             if (cb.style() == BHIDDEN)
830                 continue;
831             allHidden = false;
832             if (cb.style() > BHIDDEN && cb.width() > borderWidth)
833                 borderWidth = cb.width();
834         }
835     }
836     if (allHidden)
837         return -1;
838
839     return (borderWidth + 1) / 2;
840 }
841
842 int RenderTableSection::calcOuterBorderStart() const
843 {
844     unsigned totalCols = table()->numEffCols();
845     if (!m_grid.size() || !totalCols)
846         return 0;
847
848     unsigned borderWidth = 0;
849
850     const BorderValue& sb = style()->borderStart();
851     if (sb.style() == BHIDDEN)
852         return -1;
853     if (sb.style() > BHIDDEN)
854         borderWidth = sb.width();
855
856     if (RenderTableCol* colGroup = table()->colElement(0)) {
857         const BorderValue& gb = colGroup->style()->borderStart();
858         if (gb.style() == BHIDDEN)
859             return -1;
860         if (gb.style() > BHIDDEN && gb.width() > borderWidth)
861             borderWidth = gb.width();
862     }
863
864     bool allHidden = true;
865     for (unsigned r = 0; r < m_grid.size(); r++) {
866         const CellStruct& current = cellAt(r, 0);
867         if (!current.hasCells())
868             continue;
869         // FIXME: Don't repeat for the same cell
870         const BorderValue& cb = current.primaryCell()->style()->borderStart(); // FIXME: Make this work with perpendicular and flipped cells.
871         const BorderValue& rb = current.primaryCell()->parent()->style()->borderStart();
872         if (cb.style() == BHIDDEN || rb.style() == BHIDDEN)
873             continue;
874         allHidden = false;
875         if (cb.style() > BHIDDEN && cb.width() > borderWidth)
876             borderWidth = cb.width();
877         if (rb.style() > BHIDDEN && rb.width() > borderWidth)
878             borderWidth = rb.width();
879     }
880     if (allHidden)
881         return -1;
882
883     return (borderWidth + (table()->style()->isLeftToRightDirection() ? 0 : 1)) / 2;
884 }
885
886 int RenderTableSection::calcOuterBorderEnd() const
887 {
888     unsigned totalCols = table()->numEffCols();
889     if (!m_grid.size() || !totalCols)
890         return 0;
891
892     unsigned borderWidth = 0;
893
894     const BorderValue& sb = style()->borderEnd();
895     if (sb.style() == BHIDDEN)
896         return -1;
897     if (sb.style() > BHIDDEN)
898         borderWidth = sb.width();
899
900     if (RenderTableCol* colGroup = table()->colElement(totalCols - 1)) {
901         const BorderValue& gb = colGroup->style()->borderEnd();
902         if (gb.style() == BHIDDEN)
903             return -1;
904         if (gb.style() > BHIDDEN && gb.width() > borderWidth)
905             borderWidth = gb.width();
906     }
907
908     bool allHidden = true;
909     for (unsigned r = 0; r < m_grid.size(); r++) {
910         const CellStruct& current = cellAt(r, totalCols - 1);
911         if (!current.hasCells())
912             continue;
913         // FIXME: Don't repeat for the same cell
914         const BorderValue& cb = current.primaryCell()->style()->borderEnd(); // FIXME: Make this work with perpendicular and flipped cells.
915         const BorderValue& rb = current.primaryCell()->parent()->style()->borderEnd();
916         if (cb.style() == BHIDDEN || rb.style() == BHIDDEN)
917             continue;
918         allHidden = false;
919         if (cb.style() > BHIDDEN && cb.width() > borderWidth)
920             borderWidth = cb.width();
921         if (rb.style() > BHIDDEN && rb.width() > borderWidth)
922             borderWidth = rb.width();
923     }
924     if (allHidden)
925         return -1;
926
927     return (borderWidth + (table()->style()->isLeftToRightDirection() ? 1 : 0)) / 2;
928 }
929
930 void RenderTableSection::recalcOuterBorder()
931 {
932     m_outerBorderBefore = calcOuterBorderBefore();
933     m_outerBorderAfter = calcOuterBorderAfter();
934     m_outerBorderStart = calcOuterBorderStart();
935     m_outerBorderEnd = calcOuterBorderEnd();
936 }
937
938 LayoutUnit RenderTableSection::firstLineBoxBaseline() const
939 {
940     if (!m_grid.size())
941         return -1;
942
943     LayoutUnit firstLineBaseline = m_grid[0].baseline;
944     if (firstLineBaseline)
945         return firstLineBaseline + m_rowPos[0];
946
947     firstLineBaseline = -1;
948     const Row& firstRow = m_grid[0].row;
949     for (size_t i = 0; i < firstRow.size(); ++i) {
950         const CellStruct& cs = firstRow.at(i);
951         const RenderTableCell* cell = cs.primaryCell();
952         // Only cells with content have a baseline
953         if (cell && cell->contentLogicalHeight())
954             firstLineBaseline = max(firstLineBaseline, cell->logicalTop() + cell->paddingBefore() + cell->borderBefore() + cell->contentLogicalHeight());
955     }
956
957     return firstLineBaseline;
958 }
959
960 void RenderTableSection::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
961 {
962     // put this back in when all layout tests can handle it
963     // ASSERT(!needsLayout());
964     // avoid crashing on bugs that cause us to paint with dirty layout
965     if (needsLayout())
966         return;
967     
968     unsigned totalRows = m_grid.size();
969     unsigned totalCols = table()->columns().size();
970
971     if (!totalRows || !totalCols)
972         return;
973
974     LayoutPoint adjustedPaintOffset = paintOffset + location();
975
976     PaintPhase phase = paintInfo.phase;
977     bool pushedClip = pushContentsClip(paintInfo, adjustedPaintOffset);
978     paintObject(paintInfo, adjustedPaintOffset);
979     if (pushedClip)
980         popContentsClip(paintInfo, phase, adjustedPaintOffset);
981
982     if ((phase == PaintPhaseOutline || phase == PaintPhaseSelfOutline) && style()->visibility() == VISIBLE)
983         paintOutline(paintInfo.context, LayoutRect(adjustedPaintOffset, size()));
984 }
985
986 static inline bool compareCellPositions(RenderTableCell* elem1, RenderTableCell* elem2)
987 {
988     return elem1->rowIndex() < elem2->rowIndex();
989 }
990
991 // This comparison is used only when we have overflowing cells as we have an unsorted array to sort. We thus need
992 // to sort both on rows and columns to properly repaint.
993 static inline bool compareCellPositionsWithOverflowingCells(RenderTableCell* elem1, RenderTableCell* elem2)
994 {
995     if (elem1->rowIndex() != elem2->rowIndex())
996         return elem1->rowIndex() < elem2->rowIndex();
997
998     return elem1->col() < elem2->col();
999 }
1000
1001 void RenderTableSection::paintCell(RenderTableCell* cell, PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1002 {
1003     LayoutPoint cellPoint = flipForWritingModeForChild(cell, paintOffset);
1004     PaintPhase paintPhase = paintInfo.phase;
1005     RenderTableRow* row = toRenderTableRow(cell->parent());
1006
1007     if (paintPhase == PaintPhaseBlockBackground || paintPhase == PaintPhaseChildBlockBackground) {
1008         // We need to handle painting a stack of backgrounds.  This stack (from bottom to top) consists of
1009         // the column group, column, row group, row, and then the cell.
1010         RenderTableCol* column = table()->colElement(cell->col());
1011         RenderTableCol* columnGroup = column ? column->enclosingColumnGroup() : 0;
1012
1013         // Column groups and columns first.
1014         // FIXME: Columns and column groups do not currently support opacity, and they are being painted "too late" in
1015         // the stack, since we have already opened a transparency layer (potentially) for the table row group.
1016         // Note that we deliberately ignore whether or not the cell has a layer, since these backgrounds paint "behind" the
1017         // cell.
1018         cell->paintBackgroundsBehindCell(paintInfo, cellPoint, columnGroup);
1019         cell->paintBackgroundsBehindCell(paintInfo, cellPoint, column);
1020
1021         // Paint the row group next.
1022         cell->paintBackgroundsBehindCell(paintInfo, cellPoint, this);
1023
1024         // Paint the row next, but only if it doesn't have a layer.  If a row has a layer, it will be responsible for
1025         // painting the row background for the cell.
1026         if (!row->hasSelfPaintingLayer())
1027             cell->paintBackgroundsBehindCell(paintInfo, cellPoint, row);
1028     }
1029     if ((!cell->hasSelfPaintingLayer() && !row->hasSelfPaintingLayer()))
1030         cell->paint(paintInfo, cellPoint);
1031 }
1032
1033 LayoutRect RenderTableSection::logicalRectForWritingModeAndDirection(const LayoutRect& rect) const
1034 {
1035     LayoutRect tableAlignedRect(rect);
1036
1037     flipForWritingMode(tableAlignedRect);
1038
1039     if (!style()->isHorizontalWritingMode())
1040         tableAlignedRect = tableAlignedRect.transposedRect();
1041
1042     const Vector<int>& columnPos = table()->columnPositions();
1043     if (!style()->isLeftToRightDirection())
1044         tableAlignedRect.setX(columnPos[columnPos.size() - 1] - tableAlignedRect.maxX());
1045
1046     return tableAlignedRect;
1047 }
1048
1049 CellSpan RenderTableSection::dirtiedRows(const LayoutRect& damageRect) const
1050 {
1051     if (m_forceSlowPaintPathWithOverflowingCell) 
1052         return fullTableRowSpan();
1053
1054     CellSpan coveredRows = spannedRows(damageRect);
1055
1056     // To repaint the border we might need to repaint first or last row even if they are not spanned themselves.
1057     if (coveredRows.start() >= m_rowPos.size() - 1 && m_rowPos[m_rowPos.size() - 1] + table()->outerBorderAfter() >= damageRect.y())
1058         --coveredRows.start();
1059
1060     if (!coveredRows.end() && m_rowPos[0] - table()->outerBorderBefore() <= damageRect.maxY())
1061         ++coveredRows.end();
1062
1063     return coveredRows;
1064 }
1065
1066 CellSpan RenderTableSection::dirtiedColumns(const LayoutRect& damageRect) const
1067 {
1068     if (m_forceSlowPaintPathWithOverflowingCell) 
1069         return fullTableColumnSpan();
1070
1071     CellSpan coveredColumns = spannedColumns(damageRect);
1072
1073     Vector<int>& columnPos = table()->columnPositions();
1074     // To repaint the border we might need to repaint first or last column even if they are not spanned themselves.
1075     if (coveredColumns.start() >= columnPos.size() - 1 && columnPos[columnPos.size() - 1] + table()->outerBorderEnd() >= damageRect.x())
1076         --coveredColumns.start();
1077
1078     if (!coveredColumns.end() && columnPos[0] - table()->outerBorderStart() <= damageRect.maxX())
1079         ++coveredColumns.end();
1080
1081     return coveredColumns;
1082 }
1083
1084 CellSpan RenderTableSection::spannedRows(const LayoutRect& flippedRect) const
1085 {
1086     // Find the first row that starts after rect top.
1087     // FIXME: Upper_bound might not be the correct algorithm here since it might skip empty rows, but it is
1088     // consistent with behavior in the former point based hit-testing (but inconsistent with spannedColumns).
1089     unsigned nextRow = std::upper_bound(m_rowPos.begin(), m_rowPos.end(), flippedRect.y()) - m_rowPos.begin();
1090
1091     if (nextRow == m_rowPos.size())
1092         return CellSpan(m_rowPos.size() - 1, m_rowPos.size() - 1); // After all rows.
1093
1094     unsigned startRow = nextRow > 0 ? nextRow - 1 : 0;
1095
1096     // Find the first row that starts after rect bottom.
1097     unsigned endRow;
1098     if (m_rowPos[nextRow] >= flippedRect.maxY())
1099         endRow = nextRow;
1100     else {
1101         endRow = std::upper_bound(m_rowPos.begin() + nextRow, m_rowPos.end(), flippedRect.maxY()) - m_rowPos.begin();
1102         if (endRow == m_rowPos.size())
1103             endRow = m_rowPos.size() - 1;
1104     }
1105
1106     return CellSpan(startRow, endRow);
1107 }
1108
1109 CellSpan RenderTableSection::spannedColumns(const LayoutRect& flippedRect) const
1110 {
1111     const Vector<int>& columnPos = table()->columnPositions();
1112
1113     // Find the first columnt that starts after rect left.
1114     unsigned nextColumn = std::lower_bound(columnPos.begin(), columnPos.end(), flippedRect.x()) - columnPos.begin();
1115
1116     if (nextColumn == columnPos.size())
1117         return CellSpan(columnPos.size() - 1, columnPos.size() - 1); // After all columns.
1118
1119     unsigned startColumn = nextColumn > 0 ? nextColumn - 1 : 0;
1120
1121     // Find the first row that starts after rect right.
1122     unsigned endColumn;
1123     if (columnPos[nextColumn] >= flippedRect.maxX())
1124         endColumn = nextColumn;
1125     else {
1126         endColumn = std::lower_bound(columnPos.begin() + nextColumn, columnPos.end(), flippedRect.maxX()) - columnPos.begin();
1127         if (endColumn == columnPos.size())
1128             endColumn = columnPos.size() - 1;
1129     }
1130
1131     return CellSpan(startColumn, endColumn);
1132 }
1133
1134
1135 void RenderTableSection::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
1136 {
1137     PaintPhase paintPhase = paintInfo.phase;
1138
1139     LayoutRect localRepaintRect = paintInfo.rect;
1140     localRepaintRect.moveBy(-paintOffset);
1141     localRepaintRect.inflate(maximalOutlineSize(paintPhase));
1142
1143     LayoutRect tableAlignedRect = logicalRectForWritingModeAndDirection(localRepaintRect);
1144
1145     CellSpan dirtiedRows = this->dirtiedRows(tableAlignedRect);
1146     CellSpan dirtiedColumns = this->dirtiedColumns(tableAlignedRect);
1147
1148     if (dirtiedColumns.start() < dirtiedColumns.end()) {
1149         if (!m_hasMultipleCellLevels && !m_overflowingCells.size()) {
1150             if (paintInfo.phase == PaintPhaseCollapsedTableBorders) {
1151                 // Collapsed borders are painted from the bottom right to the top left so that precedence
1152                 // due to cell position is respected.
1153                 for (unsigned r = dirtiedRows.end(); r > dirtiedRows.start(); r--) {
1154                     unsigned row = r - 1;
1155                     for (unsigned c = dirtiedColumns.end(); c > dirtiedColumns.start(); c--) {
1156                         unsigned col = c - 1;
1157                         CellStruct& current = cellAt(row, col);
1158                         RenderTableCell* cell = current.primaryCell();
1159                         if (!cell || (row > dirtiedRows.start() && primaryCellAt(row - 1, col) == cell) || (col > dirtiedColumns.start() && primaryCellAt(row, col - 1) == cell))
1160                             continue;
1161                         LayoutPoint cellPoint = flipForWritingModeForChild(cell, paintOffset);
1162                         cell->paintCollapsedBorders(paintInfo, cellPoint);
1163                     }
1164                 }
1165             } else {
1166                 // Draw the dirty cells in the order that they appear.
1167                 for (unsigned r = dirtiedRows.start(); r < dirtiedRows.end(); r++) {
1168                     RenderTableRow* row = m_grid[r].rowRenderer;
1169                     if (row && !row->hasSelfPaintingLayer())
1170                         row->paintOutlineForRowIfNeeded(paintInfo, paintOffset);
1171                     for (unsigned c = dirtiedColumns.start(); c < dirtiedColumns.end(); c++) {
1172                         CellStruct& current = cellAt(r, c);
1173                         RenderTableCell* cell = current.primaryCell();
1174                         if (!cell || (r > dirtiedRows.start() && primaryCellAt(r - 1, c) == cell) || (c > dirtiedColumns.start() && primaryCellAt(r, c - 1) == cell))
1175                             continue;
1176                         paintCell(cell, paintInfo, paintOffset);
1177                     }
1178                 }
1179             }
1180         } else {
1181             // The overflowing cells should be scarce to avoid adding a lot of cells to the HashSet.
1182 #ifndef NDEBUG
1183             unsigned totalRows = m_grid.size();
1184             unsigned totalCols = table()->columns().size();
1185             ASSERT(m_overflowingCells.size() < totalRows * totalCols * gMaxAllowedOverflowingCellRatioForFastPaintPath);
1186 #endif
1187
1188             // To make sure we properly repaint the section, we repaint all the overflowing cells that we collected.
1189             Vector<RenderTableCell*> cells;
1190             copyToVector(m_overflowingCells, cells);
1191
1192             HashSet<RenderTableCell*> spanningCells;
1193
1194             for (unsigned r = dirtiedRows.start(); r < dirtiedRows.end(); r++) {
1195                 RenderTableRow* row = m_grid[r].rowRenderer;
1196                 if (row && !row->hasSelfPaintingLayer())
1197                     row->paintOutlineForRowIfNeeded(paintInfo, paintOffset);
1198                 for (unsigned c = dirtiedColumns.start(); c < dirtiedColumns.end(); c++) {
1199                     CellStruct& current = cellAt(r, c);
1200                     if (!current.hasCells())
1201                         continue;
1202                     for (unsigned i = 0; i < current.cells.size(); ++i) {
1203                         if (m_overflowingCells.contains(current.cells[i]))
1204                             continue;
1205
1206                         if (current.cells[i]->rowSpan() > 1 || current.cells[i]->colSpan() > 1) {
1207                             if (spanningCells.contains(current.cells[i]))
1208                                 continue;
1209                             spanningCells.add(current.cells[i]);
1210                         }
1211
1212                         cells.append(current.cells[i]);
1213                     }
1214                 }
1215             }
1216
1217             // Sort the dirty cells by paint order.
1218             if (!m_overflowingCells.size())
1219                 std::stable_sort(cells.begin(), cells.end(), compareCellPositions);
1220             else
1221                 std::sort(cells.begin(), cells.end(), compareCellPositionsWithOverflowingCells);
1222
1223             if (paintInfo.phase == PaintPhaseCollapsedTableBorders) {
1224                 for (unsigned i = cells.size(); i > 0; --i) {
1225                     LayoutPoint cellPoint = flipForWritingModeForChild(cells[i - 1], paintOffset);
1226                     cells[i - 1]->paintCollapsedBorders(paintInfo, cellPoint);
1227                 }
1228             } else {
1229                 for (unsigned i = 0; i < cells.size(); ++i)
1230                     paintCell(cells[i], paintInfo, paintOffset);
1231             }
1232         }
1233     }
1234 }
1235
1236 void RenderTableSection::imageChanged(WrappedImagePtr, const IntRect*)
1237 {
1238     // FIXME: Examine cells and repaint only the rect the image paints in.
1239     repaint();
1240 }
1241
1242 void RenderTableSection::recalcCells()
1243 {
1244     ASSERT(m_needsCellRecalc);
1245     // We reset the flag here to ensure that |addCell| works. This is safe to do as
1246     // fillRowsWithDefaultStartingAtPosition makes sure we match the table's columns
1247     // representation.
1248     m_needsCellRecalc = false;
1249
1250     m_cCol = 0;
1251     m_cRow = 0;
1252     m_grid.clear();
1253
1254     for (RenderObject* row = firstChild(); row; row = row->nextSibling()) {
1255         if (row->isTableRow()) {
1256             unsigned insertionRow = m_cRow;
1257             m_cRow++;
1258             m_cCol = 0;
1259             ensureRows(m_cRow);
1260
1261             RenderTableRow* tableRow = toRenderTableRow(row);
1262             m_grid[insertionRow].rowRenderer = tableRow;
1263             tableRow->setRowIndex(insertionRow);
1264             setRowLogicalHeightToRowStyleLogicalHeightIfNotRelative(m_grid[insertionRow]);
1265
1266             for (RenderObject* cell = row->firstChild(); cell; cell = cell->nextSibling()) {
1267                 if (!cell->isTableCell())
1268                     continue;
1269
1270                 RenderTableCell* tableCell = toRenderTableCell(cell);
1271                 addCell(tableCell, tableRow);
1272             }
1273         }
1274     }
1275
1276     m_grid.shrinkToFit();
1277     setNeedsLayout(true);
1278 }
1279
1280 // FIXME: This function could be made O(1) in certain cases (like for the non-most-constrainive cells' case).
1281 void RenderTableSection::rowLogicalHeightChanged(unsigned rowIndex)
1282 {
1283     if (needsCellRecalc())
1284         return;
1285
1286     setRowLogicalHeightToRowStyleLogicalHeightIfNotRelative(m_grid[rowIndex]);
1287
1288     for (RenderObject* cell = m_grid[rowIndex].rowRenderer->firstChild(); cell; cell = cell->nextSibling()) {
1289         if (!cell->isTableCell())
1290             continue;
1291
1292         updateLogicalHeightForCell(m_grid[rowIndex], toRenderTableCell(cell));
1293     }
1294 }
1295
1296 void RenderTableSection::setNeedsCellRecalc()
1297 {
1298     m_needsCellRecalc = true;
1299     if (RenderTable* t = table())
1300         t->setNeedsSectionRecalc();
1301 }
1302
1303 unsigned RenderTableSection::numColumns() const
1304 {
1305     unsigned result = 0;
1306     
1307     for (unsigned r = 0; r < m_grid.size(); ++r) {
1308         for (unsigned c = result; c < table()->numEffCols(); ++c) {
1309             const CellStruct& cell = cellAt(r, c);
1310             if (cell.hasCells() || cell.inColSpan)
1311                 result = c;
1312         }
1313     }
1314     
1315     return result + 1;
1316 }
1317
1318 const RenderTableCell* RenderTableSection::firstRowCellAdjoiningTableStart() const
1319 {
1320     unsigned adjoiningStartCellColumnIndex = hasSameDirectionAsTable() ? 0 : table()->lastColumnIndex();
1321     return cellAt(0, adjoiningStartCellColumnIndex).primaryCell();
1322 }
1323
1324 const RenderTableCell* RenderTableSection::firstRowCellAdjoiningTableEnd() const
1325 {
1326     unsigned adjoiningEndCellColumnIndex = hasSameDirectionAsTable() ? table()->lastColumnIndex() : 0;
1327     return cellAt(0, adjoiningEndCellColumnIndex).primaryCell();
1328 }
1329
1330 void RenderTableSection::appendColumn(unsigned pos)
1331 {
1332     ASSERT(!m_needsCellRecalc);
1333
1334     for (unsigned row = 0; row < m_grid.size(); ++row)
1335         m_grid[row].row.resize(pos + 1);
1336 }
1337
1338 void RenderTableSection::splitColumn(unsigned pos, unsigned first)
1339 {
1340     ASSERT(!m_needsCellRecalc);
1341
1342     if (m_cCol > pos)
1343         m_cCol++;
1344     for (unsigned row = 0; row < m_grid.size(); ++row) {
1345         Row& r = m_grid[row].row;
1346         r.insert(pos + 1, CellStruct());
1347         if (r[pos].hasCells()) {
1348             r[pos + 1].cells.append(r[pos].cells);
1349             RenderTableCell* cell = r[pos].primaryCell();
1350             ASSERT(cell);
1351             ASSERT(cell->colSpan() >= (r[pos].inColSpan ? 1u : 0));
1352             unsigned colleft = cell->colSpan() - r[pos].inColSpan;
1353             if (first > colleft)
1354               r[pos + 1].inColSpan = 0;
1355             else
1356               r[pos + 1].inColSpan = first + r[pos].inColSpan;
1357         } else {
1358             r[pos + 1].inColSpan = 0;
1359         }
1360     }
1361 }
1362
1363 // Hit Testing
1364 bool RenderTableSection::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestPoint& pointInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
1365 {
1366     // If we have no children then we have nothing to do.
1367     if (!firstChild())
1368         return false;
1369
1370     // Table sections cannot ever be hit tested.  Effectively they do not exist.
1371     // Just forward to our children always.
1372     LayoutPoint adjustedLocation = accumulatedOffset + location();
1373
1374     if (hasOverflowClip() && !pointInContainer.intersects(overflowClipRect(adjustedLocation, result.region())))
1375         return false;
1376
1377     if (hasOverflowingCell()) {
1378         for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
1379             // FIXME: We have to skip over inline flows, since they can show up inside table rows
1380             // at the moment (a demoted inline <form> for example). If we ever implement a
1381             // table-specific hit-test method (which we should do for performance reasons anyway),
1382             // then we can remove this check.
1383             if (child->isBox() && !toRenderBox(child)->hasSelfPaintingLayer()) {
1384                 LayoutPoint childPoint = flipForWritingModeForChild(toRenderBox(child), adjustedLocation);
1385                 if (child->nodeAtPoint(request, result, pointInContainer, childPoint, action)) {
1386                     updateHitTestResult(result, toLayoutPoint(pointInContainer.point() - childPoint));
1387                     return true;
1388                 }
1389             }
1390         }
1391         return false;
1392     }
1393
1394     recalcCellsIfNeeded();
1395
1396     LayoutRect hitTestRect = result.rectForPoint(pointInContainer.point());
1397     hitTestRect.moveBy(-adjustedLocation);
1398
1399     LayoutRect tableAlignedRect = logicalRectForWritingModeAndDirection(hitTestRect);
1400     CellSpan rowSpan = spannedRows(tableAlignedRect);
1401     CellSpan columnSpan = spannedColumns(tableAlignedRect);
1402
1403     // Now iterate over the spanned rows and columns.
1404     for (unsigned hitRow = rowSpan.start(); hitRow < rowSpan.end(); ++hitRow) {
1405         for (unsigned hitColumn = columnSpan.start(); hitColumn < columnSpan.end(); ++hitColumn) {
1406             CellStruct& current = cellAt(hitRow, hitColumn);
1407
1408             // If the cell is empty, there's nothing to do
1409             if (!current.hasCells())
1410                 continue;
1411
1412             for (unsigned i = current.cells.size() ; i; ) {
1413                 --i;
1414                 RenderTableCell* cell = current.cells[i];
1415                 LayoutPoint cellPoint = flipForWritingModeForChild(cell, adjustedLocation);
1416                 if (static_cast<RenderObject*>(cell)->nodeAtPoint(request, result, pointInContainer, cellPoint, action)) {
1417                     updateHitTestResult(result, pointInContainer.point() - toLayoutSize(cellPoint));
1418                     return true;
1419                 }
1420             }
1421             if (!result.isRectBasedTest())
1422                 break;
1423         }
1424         if (!result.isRectBasedTest())
1425             break;
1426     }
1427
1428     return false;
1429 }
1430
1431 void RenderTableSection::removeCachedCollapsedBorders(const RenderTableCell* cell)
1432 {
1433     if (!table()->collapseBorders())
1434         return;
1435     
1436     for (int side = CBSBefore; side <= CBSEnd; ++side)
1437         m_cellsCollapsedBorders.remove(make_pair(cell, side));
1438 }
1439
1440 void RenderTableSection::setCachedCollapsedBorder(const RenderTableCell* cell, CollapsedBorderSide side, CollapsedBorderValue border)
1441 {
1442     ASSERT(table()->collapseBorders());
1443     m_cellsCollapsedBorders.set(make_pair(cell, side), border);
1444 }
1445
1446 CollapsedBorderValue& RenderTableSection::cachedCollapsedBorder(const RenderTableCell* cell, CollapsedBorderSide side)
1447 {
1448     ASSERT(table()->collapseBorders());
1449     HashMap<pair<const RenderTableCell*, int>, CollapsedBorderValue>::iterator it = m_cellsCollapsedBorders.find(make_pair(cell, side));
1450     ASSERT(it != m_cellsCollapsedBorders.end());
1451     return it->second;
1452 }
1453
1454 RenderTableSection* RenderTableSection::createAnonymousWithParentRenderer(const RenderObject* parent)
1455 {
1456     RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parent->style(), TABLE_ROW_GROUP);
1457     RenderTableSection* newSection = new (parent->renderArena()) RenderTableSection(parent->document() /* is anonymous */);
1458     newSection->setStyle(newStyle.release());
1459     return newSection;
1460 }
1461
1462 void RenderTableSection::setLogicalPositionForCell(RenderTableCell* cell, unsigned effectiveColumn) const
1463 {
1464     LayoutPoint oldCellLocation(cell->x(), cell->y());
1465
1466     LayoutPoint cellLocation(0, m_rowPos[cell->rowIndex()]);
1467     int horizontalBorderSpacing = table()->hBorderSpacing();
1468
1469     if (!cell->styleForCellFlow()->isLeftToRightDirection())
1470         cellLocation.setX(table()->columnPositions()[table()->numEffCols()] - table()->columnPositions()[table()->colToEffCol(cell->col() + cell->colSpan())] + horizontalBorderSpacing);
1471     else
1472         cellLocation.setX(table()->columnPositions()[effectiveColumn] + horizontalBorderSpacing);
1473
1474     cell->setLogicalLocation(cellLocation);
1475     view()->addLayoutDelta(oldCellLocation - cell->location());
1476 }
1477
1478 } // namespace WebCore