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