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