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