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