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