dc44094bff29bca5331afff43ba0c4ed63076087
[WebKit.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 && row->rowRenderer);
54     row->logicalHeight = row->rowRenderer->style()->logicalHeight();
55     if (row->logicalHeight.isRelative())
56         row->logicalHeight = Length();
57 }
58
59 RenderTableSection::RenderTableSection(Node* node)
60     : RenderBox(node)
61     , m_gridRows(0)
62     , m_cCol(0)
63     , m_cRow(-1)
64     , m_outerBorderStart(0)
65     , m_outerBorderEnd(0)
66     , m_outerBorderBefore(0)
67     , m_outerBorderAfter(0)
68     , m_needsCellRecalc(false)
69     , m_hasMultipleCellLevels(false)
70 {
71     // init RenderObject attributes
72     setInline(false); // our object is not Inline
73 }
74
75 RenderTableSection::~RenderTableSection()
76 {
77     clearGrid();
78 }
79
80 void RenderTableSection::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
81 {
82     RenderBox::styleDidChange(diff, oldStyle);
83     propagateStyleToAnonymousChildren();
84 }
85
86 void RenderTableSection::willBeDestroyed()
87 {
88     RenderTable* recalcTable = table();
89     
90     RenderBox::willBeDestroyed();
91     
92     // recalc cell info because RenderTable has unguarded pointers
93     // stored that point to this RenderTableSection.
94     if (recalcTable)
95         recalcTable->setNeedsSectionRecalc();
96 }
97
98 void RenderTableSection::addChild(RenderObject* child, RenderObject* beforeChild)
99 {
100     // Make sure we don't append things after :after-generated content if we have it.
101     if (!beforeChild && isAfterContent(lastChild()))
102         beforeChild = lastChild();
103
104     if (!child->isTableRow()) {
105         RenderObject* last = beforeChild;
106         if (!last)
107             last = lastChild();
108         if (last && last->isAnonymous() && !last->isBeforeOrAfterContent()) {
109             if (beforeChild == last)
110                 beforeChild = last->firstChild();
111             last->addChild(child, beforeChild);
112             return;
113         }
114
115         // If beforeChild is inside an anonymous cell/row, insert into the cell or into
116         // the anonymous row containing it, if there is one.
117         RenderObject* lastBox = last;
118         while (lastBox && lastBox->parent()->isAnonymous() && !lastBox->isTableRow())
119             lastBox = lastBox->parent();
120         if (lastBox && lastBox->isAnonymous() && !lastBox->isBeforeOrAfterContent()) {
121             lastBox->addChild(child, beforeChild);
122             return;
123         }
124
125         RenderObject* row = new (renderArena()) RenderTableRow(document() /* anonymous table row */);
126         RefPtr<RenderStyle> newStyle = RenderStyle::create();
127         newStyle->inheritFrom(style());
128         newStyle->setDisplay(TABLE_ROW);
129         row->setStyle(newStyle.release());
130         addChild(row, beforeChild);
131         row->addChild(child);
132         return;
133     }
134
135     if (beforeChild)
136         setNeedsCellRecalc();
137
138     ++m_cRow;
139     m_cCol = 0;
140
141     // make sure we have enough rows
142     if (!ensureRows(m_cRow + 1))
143         return;
144
145     m_grid[m_cRow].rowRenderer = toRenderTableRow(child);
146
147     if (!beforeChild)
148         setRowLogicalHeightToRowStyleLogicalHeightIfNotRelative(&m_grid[m_cRow]);
149
150     // If the next renderer is actually wrapped in an anonymous table row, we need to go up and find that.
151     while (beforeChild && beforeChild->parent() != this)
152         beforeChild = beforeChild->parent();
153
154     ASSERT(!beforeChild || beforeChild->isTableRow());
155     RenderBox::addChild(child, beforeChild);
156     toRenderTableRow(child)->updateBeforeAndAfterContent();
157 }
158
159 void RenderTableSection::removeChild(RenderObject* oldChild)
160 {
161     setNeedsCellRecalc();
162     RenderBox::removeChild(oldChild);
163 }
164
165 bool RenderTableSection::ensureRows(int numRows)
166 {
167     int nRows = m_gridRows;
168     if (numRows > nRows) {
169         if (numRows > static_cast<int>(m_grid.size())) {
170             size_t maxSize = numeric_limits<size_t>::max() / sizeof(RowStruct);
171             if (static_cast<size_t>(numRows) > maxSize)
172                 return false;
173             m_grid.grow(numRows);
174         }
175         m_gridRows = numRows;
176         int nCols = max(1, table()->numEffCols());
177         for (int r = nRows; r < numRows; r++) {
178             m_grid[r].row = new Row(nCols);
179             m_grid[r].rowRenderer = 0;
180             m_grid[r].baseline = 0;
181             m_grid[r].logicalHeight = Length();
182         }
183     }
184
185     return true;
186 }
187
188 void RenderTableSection::addCell(RenderTableCell* cell, RenderTableRow* row)
189 {
190     int rSpan = cell->rowSpan();
191     int cSpan = cell->colSpan();
192     Vector<RenderTable::ColumnStruct>& columns = table()->columns();
193     int nCols = columns.size();
194
195     // ### mozilla still seems to do the old HTML way, even for strict DTD
196     // (see the annotation on table cell layouting in the CSS specs and the testcase below:
197     // <TABLE border>
198     // <TR><TD>1 <TD rowspan="2">2 <TD>3 <TD>4
199     // <TR><TD colspan="2">5
200     // </TABLE>
201     while (m_cCol < nCols && (cellAt(m_cRow, m_cCol).hasCells() || cellAt(m_cRow, m_cCol).inColSpan))
202         m_cCol++;
203
204     if (rSpan == 1) {
205         // we ignore height settings on rowspan cells
206         Length logicalHeight = cell->style()->logicalHeight();
207         if (logicalHeight.isPositive() || (logicalHeight.isRelative() && logicalHeight.value() >= 0)) {
208             Length cRowLogicalHeight = m_grid[m_cRow].logicalHeight;
209             switch (logicalHeight.type()) {
210                 case Percent:
211                     if (!(cRowLogicalHeight.isPercent()) ||
212                         (cRowLogicalHeight.isPercent() && cRowLogicalHeight.percent() < logicalHeight.percent()))
213                         m_grid[m_cRow].logicalHeight = logicalHeight;
214                         break;
215                 case Fixed:
216                     if (cRowLogicalHeight.type() < Percent ||
217                         (cRowLogicalHeight.isFixed() && cRowLogicalHeight.value() < logicalHeight.value()))
218                         m_grid[m_cRow].logicalHeight = logicalHeight;
219                     break;
220                 case Relative:
221                 default:
222                     break;
223             }
224         }
225     }
226
227     // make sure we have enough rows
228     if (!ensureRows(m_cRow + rSpan))
229         return;
230
231     m_grid[m_cRow].rowRenderer = row;
232
233     int col = m_cCol;
234     // tell the cell where it is
235     bool inColSpan = false;
236     while (cSpan) {
237         int currentSpan;
238         if (m_cCol >= nCols) {
239             table()->appendColumn(cSpan);
240             currentSpan = cSpan;
241         } else {
242             if (cSpan < (int)columns[m_cCol].span)
243                 table()->splitColumn(m_cCol, cSpan);
244             currentSpan = columns[m_cCol].span;
245         }
246         for (int r = 0; r < rSpan; r++) {
247             CellStruct& c = cellAt(m_cRow + r, m_cCol);
248             ASSERT(cell);
249             c.cells.append(cell);
250             // If cells overlap then we take the slow path for painting.
251             if (c.cells.size() > 1)
252                 m_hasMultipleCellLevels = true;
253             if (inColSpan)
254                 c.inColSpan = true;
255         }
256         m_cCol++;
257         cSpan -= currentSpan;
258         inColSpan = true;
259     }
260     cell->setRow(m_cRow);
261     cell->setCol(table()->effColToCol(col));
262 }
263
264 void RenderTableSection::setCellLogicalWidths()
265 {
266     Vector<LayoutUnit>& columnPos = table()->columnPositions();
267
268     LayoutStateMaintainer statePusher(view());
269     
270     for (int i = 0; i < m_gridRows; i++) {
271         Row& row = *m_grid[i].row;
272         int cols = row.size();
273         for (int j = 0; j < cols; j++) {
274             CellStruct& current = row[j];
275             RenderTableCell* cell = current.primaryCell();
276             if (!cell || current.inColSpan)
277               continue;
278             int endCol = j;
279             int cspan = cell->colSpan();
280             while (cspan && endCol < cols) {
281                 ASSERT(endCol < (int)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, IntSize(x(), y()));
294                     }
295                     cell->repaint();
296                 }
297                 cell->updateLogicalWidth(w);
298             }
299         }
300     }
301     
302     statePusher.pop(); // only pops if we pushed
303 }
304
305 LayoutUnit RenderTableSection::calcRowLogicalHeight()
306 {
307 #ifndef NDEBUG
308     setNeedsLayoutIsForbidden(true);
309 #endif
310
311     ASSERT(!needsLayout());
312
313     RenderTableCell* cell;
314
315     LayoutUnit spacing = table()->vBorderSpacing();
316
317     LayoutStateMaintainer statePusher(view());
318
319     m_rowPos.resize(m_gridRows + 1);
320     m_rowPos[0] = spacing;
321
322     for (int r = 0; r < m_gridRows; r++) {
323         m_rowPos[r + 1] = 0;
324         m_grid[r].baseline = 0;
325         LayoutUnit baseline = 0;
326         LayoutUnit bdesc = 0;
327         LayoutUnit ch = m_grid[r].logicalHeight.calcMinValue(0);
328         LayoutUnit pos = m_rowPos[r] + ch + (m_grid[r].rowRenderer ? spacing : 0);
329
330         m_rowPos[r + 1] = max(m_rowPos[r + 1], pos);
331
332         Row* row = m_grid[r].row;
333         int totalCols = row->size();
334
335         for (int c = 0; c < totalCols; c++) {
336             CellStruct& current = cellAt(r, c);
337             cell = current.primaryCell();
338
339             if (!cell || current.inColSpan)
340                 continue;
341
342             if ((cell->row() + cell->rowSpan() - 1) > r)
343                 continue;
344
345             int indx = max(r - cell->rowSpan() + 1, 0);
346
347             if (cell->hasOverrideHeight()) {
348                 if (!statePusher.didPush()) {
349                     // Technically, we should also push state for the row, but since
350                     // rows don't push a coordinate transform, that's not necessary.
351                     statePusher.push(this, locationOffset());
352                 }
353                 cell->clearIntrinsicPadding();
354                 cell->clearOverrideSize();
355                 cell->setChildNeedsLayout(true, false);
356                 cell->layoutIfNeeded();
357             }
358
359             LayoutUnit adjustedPaddingBefore = cell->paddingBefore() - cell->intrinsicPaddingBefore();
360             LayoutUnit adjustedPaddingAfter = cell->paddingAfter() - cell->intrinsicPaddingAfter();
361             LayoutUnit adjustedLogicalHeight = cell->logicalHeight() - (cell->intrinsicPaddingBefore() + cell->intrinsicPaddingAfter());
362
363             // Explicit heights use the border box in quirks mode.  In strict mode do the right
364             // thing and actually add in the border and padding.
365             ch = cell->style()->logicalHeight().calcValue(0) + 
366                 (document()->inQuirksMode() ? 0 : (adjustedPaddingBefore + adjustedPaddingAfter +
367                                                    cell->borderBefore() + cell->borderAfter()));
368             ch = max(ch, adjustedLogicalHeight);
369
370             pos = m_rowPos[indx] + ch + (m_grid[r].rowRenderer ? spacing : 0);
371
372             m_rowPos[r + 1] = max(m_rowPos[r + 1], pos);
373
374             // find out the baseline
375             EVerticalAlign va = cell->style()->verticalAlign();
376             if (va == BASELINE || va == TEXT_BOTTOM || va == TEXT_TOP || va == SUPER || va == SUB) {
377                 LayoutUnit b = cell->cellBaselinePosition();
378                 if (b > cell->borderBefore() + cell->paddingBefore()) {
379                     baseline = max(baseline, b - cell->intrinsicPaddingBefore());
380                     bdesc = max(bdesc, m_rowPos[indx] + ch - (b - cell->intrinsicPaddingBefore()));
381                 }
382             }
383         }
384
385         // do we have baseline aligned elements?
386         if (baseline) {
387             // increase rowheight if baseline requires
388             m_rowPos[r + 1] = max(m_rowPos[r + 1], baseline + bdesc + (m_grid[r].rowRenderer ? spacing : 0));
389             m_grid[r].baseline = baseline;
390         }
391
392         m_rowPos[r + 1] = max(m_rowPos[r + 1], m_rowPos[r]);
393     }
394
395 #ifndef NDEBUG
396     setNeedsLayoutIsForbidden(false);
397 #endif
398
399     ASSERT(!needsLayout());
400
401     statePusher.pop();
402
403     return m_rowPos[m_gridRows];
404 }
405
406 void RenderTableSection::layout()
407 {
408     ASSERT(needsLayout());
409
410     LayoutStateMaintainer statePusher(view(), this, locationOffset(), style()->isFlippedBlocksWritingMode());
411     for (RenderObject* child = children()->firstChild(); child; child = child->nextSibling()) {
412         if (child->isTableRow()) {
413             child->layoutIfNeeded();
414             ASSERT(!child->needsLayout());
415         }
416     }
417     statePusher.pop();
418     setNeedsLayout(false);
419 }
420
421 LayoutUnit RenderTableSection::layoutRows(LayoutUnit toAdd)
422 {
423 #ifndef NDEBUG
424     setNeedsLayoutIsForbidden(true);
425 #endif
426
427     ASSERT(!needsLayout());
428
429     LayoutUnit rHeight;
430     int rindx;
431     int totalRows = m_gridRows;
432     
433     // Set the width of our section now.  The rows will also be this width.
434     setLogicalWidth(table()->contentLogicalWidth());
435     m_overflow.clear();
436     m_overflowingCells.clear();
437     m_forceSlowPaintPathWithOverflowingCell = false;
438
439     if (toAdd && totalRows && (m_rowPos[totalRows] || !nextSibling())) {
440         LayoutUnit totalHeight = m_rowPos[totalRows] + toAdd;
441
442         LayoutUnit dh = toAdd;
443         int totalPercent = 0;
444         int numAuto = 0;
445         for (int r = 0; r < totalRows; r++) {
446             if (m_grid[r].logicalHeight.isAuto())
447                 numAuto++;
448             else if (m_grid[r].logicalHeight.isPercent())
449                 totalPercent += m_grid[r].logicalHeight.percent();
450         }
451         if (totalPercent) {
452             // try to satisfy percent
453             LayoutUnit add = 0;
454             totalPercent = min(totalPercent, 100);
455             int rh = m_rowPos[1] - m_rowPos[0];
456             for (int r = 0; r < totalRows; r++) {
457                 if (totalPercent > 0 && m_grid[r].logicalHeight.isPercent()) {
458                     LayoutUnit toAdd = min(dh, static_cast<LayoutUnit>((totalHeight * m_grid[r].logicalHeight.percent() / 100) - rh));
459                     // If toAdd is negative, then we don't want to shrink the row (this bug
460                     // affected Outlook Web Access).
461                     toAdd = max<LayoutUnit>(0, toAdd);
462                     add += toAdd;
463                     dh -= toAdd;
464                     totalPercent -= m_grid[r].logicalHeight.percent();
465                 }
466                 if (r < totalRows - 1)
467                     rh = m_rowPos[r + 2] - m_rowPos[r + 1];
468                 m_rowPos[r + 1] += add;
469             }
470         }
471         if (numAuto) {
472             // distribute over variable cols
473             LayoutUnit add = 0;
474             for (int r = 0; r < totalRows; r++) {
475                 if (numAuto > 0 && m_grid[r].logicalHeight.isAuto()) {
476                     LayoutUnit toAdd = dh / numAuto;
477                     add += toAdd;
478                     dh -= toAdd;
479                     numAuto--;
480                 }
481                 m_rowPos[r + 1] += add;
482             }
483         }
484         if (dh > 0 && m_rowPos[totalRows]) {
485             // if some left overs, distribute equally.
486             LayoutUnit tot = m_rowPos[totalRows];
487             LayoutUnit add = 0;
488             LayoutUnit prev = m_rowPos[0];
489             for (int r = 0; r < totalRows; r++) {
490                 // weight with the original height
491                 add += dh * (m_rowPos[r + 1] - prev) / tot;
492                 prev = m_rowPos[r + 1];
493                 m_rowPos[r + 1] += add;
494             }
495         }
496     }
497
498     LayoutUnit hspacing = table()->hBorderSpacing();
499     LayoutUnit vspacing = table()->vBorderSpacing();
500     LayoutUnit nEffCols = table()->numEffCols();
501
502     LayoutStateMaintainer statePusher(view(), this, LayoutSize(x(), y()), style()->isFlippedBlocksWritingMode());
503
504     for (int r = 0; r < totalRows; r++) {
505         // Set the row's x/y position and width/height.
506         if (RenderTableRow* rowRenderer = m_grid[r].rowRenderer) {
507             rowRenderer->setLocation(LayoutPoint(0, m_rowPos[r]));
508             rowRenderer->setLogicalWidth(logicalWidth());
509             rowRenderer->setLogicalHeight(m_rowPos[r + 1] - m_rowPos[r] - vspacing);
510             rowRenderer->updateLayerTransform();
511         }
512
513         for (int c = 0; c < nEffCols; c++) {
514             CellStruct& cs = cellAt(r, c);
515             RenderTableCell* cell = cs.primaryCell();
516
517             if (!cell || cs.inColSpan)
518                 continue;
519
520             rindx = cell->row();
521             rHeight = m_rowPos[rindx + cell->rowSpan()] - m_rowPos[rindx] - vspacing;
522             
523             // Force percent height children to lay themselves out again.
524             // This will cause these children to grow to fill the cell.
525             // FIXME: There is still more work to do here to fully match WinIE (should
526             // it become necessary to do so).  In quirks mode, WinIE behaves like we
527             // do, but it will clip the cells that spill out of the table section.  In
528             // strict mode, Mozilla and WinIE both regrow the table to accommodate the
529             // new height of the cell (thus letting the percentages cause growth one
530             // time only).  We may also not be handling row-spanning cells correctly.
531             //
532             // Note also the oddity where replaced elements always flex, and yet blocks/tables do
533             // not necessarily flex.  WinIE is crazy and inconsistent, and we can't hope to
534             // match the behavior perfectly, but we'll continue to refine it as we discover new
535             // bugs. :)
536             bool cellChildrenFlex = false;
537             bool flexAllChildren = cell->style()->logicalHeight().isFixed()
538                 || (!table()->style()->logicalHeight().isAuto() && rHeight != cell->logicalHeight());
539
540             for (RenderObject* o = cell->firstChild(); o; o = o->nextSibling()) {
541                 if (!o->isText() && o->style()->logicalHeight().isPercent() && (flexAllChildren || o->isReplaced() || (o->isBox() && toRenderBox(o)->scrollsOverflow()))) {
542                     // Tables with no sections do not flex.
543                     if (!o->isTable() || toRenderTable(o)->hasSections()) {
544                         o->setNeedsLayout(true, false);
545                         cellChildrenFlex = true;
546                     }
547                 }
548             }
549
550             if (HashSet<RenderBox*>* percentHeightDescendants = cell->percentHeightDescendants()) {
551                 HashSet<RenderBox*>::iterator end = percentHeightDescendants->end();
552                 for (HashSet<RenderBox*>::iterator it = percentHeightDescendants->begin(); it != end; ++it) {
553                     RenderBox* box = *it;
554                     if (!box->isReplaced() && !box->scrollsOverflow() && !flexAllChildren)
555                         continue;
556
557                     while (box != cell) {
558                         if (box->normalChildNeedsLayout())
559                             break;
560                         box->setChildNeedsLayout(true, false);
561                         box = box->containingBlock();
562                         ASSERT(box);
563                         if (!box)
564                             break;
565                     }
566                     cellChildrenFlex = true;
567                 }
568             }
569
570             if (cellChildrenFlex) {
571                 cell->setChildNeedsLayout(true, false);
572                 // Alignment within a cell is based off the calculated
573                 // height, which becomes irrelevant once the cell has
574                 // been resized based off its percentage.
575                 cell->setOverrideHeightFromRowHeight(rHeight);
576                 cell->layoutIfNeeded();
577
578                 // If the baseline moved, we may have to update the data for our row. Find out the new baseline.
579                 EVerticalAlign va = cell->style()->verticalAlign();
580                 if (va == BASELINE || va == TEXT_BOTTOM || va == TEXT_TOP || va == SUPER || va == SUB) {
581                     LayoutUnit baseline = cell->cellBaselinePosition();
582                     if (baseline > cell->borderBefore() + cell->paddingBefore())
583                         m_grid[r].baseline = max(m_grid[r].baseline, baseline);
584                 }
585             }
586
587             LayoutUnit oldIntrinsicPaddingBefore = cell->intrinsicPaddingBefore();
588             LayoutUnit oldIntrinsicPaddingAfter = cell->intrinsicPaddingAfter();
589             LayoutUnit logicalHeightWithoutIntrinsicPadding = cell->logicalHeight() - oldIntrinsicPaddingBefore - oldIntrinsicPaddingAfter;
590
591             LayoutUnit intrinsicPaddingBefore = 0;
592             switch (cell->style()->verticalAlign()) {
593                 case SUB:
594                 case SUPER:
595                 case TEXT_TOP:
596                 case TEXT_BOTTOM:
597                 case BASELINE: {
598                     LayoutUnit b = cell->cellBaselinePosition();
599                     if (b > cell->borderBefore() + cell->paddingBefore())
600                         intrinsicPaddingBefore = getBaseline(r) - (b - oldIntrinsicPaddingBefore);
601                     break;
602                 }
603                 case TOP:
604                     break;
605                 case MIDDLE:
606                     intrinsicPaddingBefore = (rHeight - logicalHeightWithoutIntrinsicPadding) / 2;
607                     break;
608                 case BOTTOM:
609                     intrinsicPaddingBefore = rHeight - logicalHeightWithoutIntrinsicPadding;
610                     break;
611                 default:
612                     break;
613             }
614             
615             LayoutUnit intrinsicPaddingAfter = rHeight - logicalHeightWithoutIntrinsicPadding - intrinsicPaddingBefore;
616             cell->setIntrinsicPaddingBefore(intrinsicPaddingBefore);
617             cell->setIntrinsicPaddingAfter(intrinsicPaddingAfter);
618
619             LayoutRect oldCellRect(cell->x(), cell->y() , cell->width(), cell->height());
620
621             LayoutPoint cellLocation(0, m_rowPos[rindx]);
622             if (!style()->isLeftToRightDirection())
623                 cellLocation.setX(table()->columnPositions()[nEffCols] - table()->columnPositions()[table()->colToEffCol(cell->col() + cell->colSpan())] + hspacing);
624             else
625                 cellLocation.setX(table()->columnPositions()[c] + hspacing);
626             cell->setLogicalLocation(cellLocation);
627             view()->addLayoutDelta(oldCellRect.location() - cell->location());
628
629             if (intrinsicPaddingBefore != oldIntrinsicPaddingBefore || intrinsicPaddingAfter != oldIntrinsicPaddingAfter)
630                 cell->setNeedsLayout(true, false);
631
632             if (!cell->needsLayout() && view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(cell->logicalTop()) != cell->pageLogicalOffset())
633                 cell->setChildNeedsLayout(true, false);
634
635             cell->layoutIfNeeded();
636
637             // FIXME: Make pagination work with vertical tables.
638             if (style()->isHorizontalWritingMode() && view()->layoutState()->pageLogicalHeight() && cell->height() != rHeight)
639                 cell->setHeight(rHeight); // FIXME: Pagination might have made us change size.  For now just shrink or grow the cell to fit without doing a relayout.
640
641             LayoutSize childOffset(cell->location() - oldCellRect.location());
642             if (childOffset.width() || childOffset.height()) {
643                 view()->addLayoutDelta(childOffset);
644
645                 // If the child moved, we have to repaint it as well as any floating/positioned
646                 // descendants.  An exception is if we need a layout.  In this case, we know we're going to
647                 // repaint ourselves (and the child) anyway.
648                 if (!table()->selfNeedsLayout() && cell->checkForRepaintDuringLayout())
649                     cell->repaintDuringLayoutIfMoved(oldCellRect);
650             }
651         }
652     }
653
654 #ifndef NDEBUG
655     setNeedsLayoutIsForbidden(false);
656 #endif
657
658     ASSERT(!needsLayout());
659
660     setLogicalHeight(m_rowPos[totalRows]);
661
662     unsigned totalCellsCount = nEffCols * totalRows;
663     int maxAllowedOverflowingCellsCount = totalCellsCount < gMinTableSizeToUseFastPaintPathWithOverflowingCell ? 0 : gMaxAllowedOverflowingCellRatioForFastPaintPath * totalCellsCount;
664
665 #ifndef NDEBUG
666     bool hasOverflowingCell = false;
667 #endif
668     // Now that our height has been determined, add in overflow from cells.
669     for (int r = 0; r < totalRows; r++) {
670         for (int c = 0; c < nEffCols; c++) {
671             CellStruct& cs = cellAt(r, c);
672             RenderTableCell* cell = cs.primaryCell();
673             if (!cell || cs.inColSpan)
674                 continue;
675             if (r < totalRows - 1 && cell == primaryCellAt(r + 1, c))
676                 continue;
677             addOverflowFromChild(cell);
678 #ifndef NDEBUG
679             hasOverflowingCell |= cell->hasVisualOverflow();
680 #endif
681             if (cell->hasVisualOverflow() && !m_forceSlowPaintPathWithOverflowingCell) {
682                 m_overflowingCells.add(cell);
683                 if (m_overflowingCells.size() > maxAllowedOverflowingCellsCount) {
684                     // We need to set m_forcesSlowPaintPath only if there is a least one overflowing cells as the hit testing code rely on this information.
685                     m_forceSlowPaintPathWithOverflowingCell = true;
686                     // The slow path does not make any use of the overflowing cells info, don't hold on to the memory.
687                     m_overflowingCells.clear();
688                 }
689             }
690         }
691     }
692
693     ASSERT(hasOverflowingCell == this->hasOverflowingCell());
694
695     statePusher.pop();
696     return height();
697 }
698
699 LayoutUnit RenderTableSection::calcOuterBorderBefore() const
700 {
701     int totalCols = table()->numEffCols();
702     if (!m_gridRows || !totalCols)
703         return 0;
704
705     unsigned borderWidth = 0;
706
707     const BorderValue& sb = style()->borderBefore();
708     if (sb.style() == BHIDDEN)
709         return -1;
710     if (sb.style() > BHIDDEN)
711         borderWidth = sb.width();
712
713     const BorderValue& rb = firstChild()->style()->borderBefore();
714     if (rb.style() == BHIDDEN)
715         return -1;
716     if (rb.style() > BHIDDEN && rb.width() > borderWidth)
717         borderWidth = rb.width();
718
719     bool allHidden = true;
720     for (int c = 0; c < totalCols; c++) {
721         const CellStruct& current = cellAt(0, c);
722         if (current.inColSpan || !current.hasCells())
723             continue;
724         const BorderValue& cb = current.primaryCell()->style()->borderBefore(); // FIXME: Make this work with perpendicular and flipped cells.
725         // FIXME: Don't repeat for the same col group
726         RenderTableCol* colGroup = table()->colElement(c);
727         if (colGroup) {
728             const BorderValue& gb = colGroup->style()->borderBefore();
729             if (gb.style() == BHIDDEN || cb.style() == BHIDDEN)
730                 continue;
731             allHidden = false;
732             if (gb.style() > BHIDDEN && gb.width() > borderWidth)
733                 borderWidth = gb.width();
734             if (cb.style() > BHIDDEN && cb.width() > borderWidth)
735                 borderWidth = cb.width();
736         } else {
737             if (cb.style() == BHIDDEN)
738                 continue;
739             allHidden = false;
740             if (cb.style() > BHIDDEN && cb.width() > borderWidth)
741                 borderWidth = cb.width();
742         }
743     }
744     if (allHidden)
745         return -1;
746
747     return borderWidth / 2;
748 }
749
750 LayoutUnit RenderTableSection::calcOuterBorderAfter() const
751 {
752     int totalCols = table()->numEffCols();
753     if (!m_gridRows || !totalCols)
754         return 0;
755
756     unsigned borderWidth = 0;
757
758     const BorderValue& sb = style()->borderAfter();
759     if (sb.style() == BHIDDEN)
760         return -1;
761     if (sb.style() > BHIDDEN)
762         borderWidth = sb.width();
763
764     const BorderValue& rb = lastChild()->style()->borderAfter();
765     if (rb.style() == BHIDDEN)
766         return -1;
767     if (rb.style() > BHIDDEN && rb.width() > borderWidth)
768         borderWidth = rb.width();
769
770     bool allHidden = true;
771     for (int c = 0; c < totalCols; c++) {
772         const CellStruct& current = cellAt(m_gridRows - 1, c);
773         if (current.inColSpan || !current.hasCells())
774             continue;
775         const BorderValue& cb = current.primaryCell()->style()->borderAfter(); // FIXME: Make this work with perpendicular and flipped cells.
776         // FIXME: Don't repeat for the same col group
777         RenderTableCol* colGroup = table()->colElement(c);
778         if (colGroup) {
779             const BorderValue& gb = colGroup->style()->borderAfter();
780             if (gb.style() == BHIDDEN || cb.style() == BHIDDEN)
781                 continue;
782             allHidden = false;
783             if (gb.style() > BHIDDEN && gb.width() > borderWidth)
784                 borderWidth = gb.width();
785             if (cb.style() > BHIDDEN && cb.width() > borderWidth)
786                 borderWidth = cb.width();
787         } else {
788             if (cb.style() == BHIDDEN)
789                 continue;
790             allHidden = false;
791             if (cb.style() > BHIDDEN && cb.width() > borderWidth)
792                 borderWidth = cb.width();
793         }
794     }
795     if (allHidden)
796         return -1;
797
798     return (borderWidth + 1) / 2;
799 }
800
801 LayoutUnit RenderTableSection::calcOuterBorderStart() const
802 {
803     int totalCols = table()->numEffCols();
804     if (!m_gridRows || !totalCols)
805         return 0;
806
807     unsigned borderWidth = 0;
808
809     const BorderValue& sb = style()->borderStart();
810     if (sb.style() == BHIDDEN)
811         return -1;
812     if (sb.style() > BHIDDEN)
813         borderWidth = sb.width();
814
815     if (RenderTableCol* colGroup = table()->colElement(0)) {
816         const BorderValue& gb = colGroup->style()->borderStart();
817         if (gb.style() == BHIDDEN)
818             return -1;
819         if (gb.style() > BHIDDEN && gb.width() > borderWidth)
820             borderWidth = gb.width();
821     }
822
823     bool allHidden = true;
824     for (int r = 0; r < m_gridRows; r++) {
825         const CellStruct& current = cellAt(r, 0);
826         if (!current.hasCells())
827             continue;
828         // FIXME: Don't repeat for the same cell
829         const BorderValue& cb = current.primaryCell()->style()->borderStart(); // FIXME: Make this work with perpendicular and flipped cells.
830         const BorderValue& rb = current.primaryCell()->parent()->style()->borderStart();
831         if (cb.style() == BHIDDEN || rb.style() == BHIDDEN)
832             continue;
833         allHidden = false;
834         if (cb.style() > BHIDDEN && cb.width() > borderWidth)
835             borderWidth = cb.width();
836         if (rb.style() > BHIDDEN && rb.width() > borderWidth)
837             borderWidth = rb.width();
838     }
839     if (allHidden)
840         return -1;
841
842     return (borderWidth + (table()->style()->isLeftToRightDirection() ? 0 : 1)) / 2;
843 }
844
845 LayoutUnit RenderTableSection::calcOuterBorderEnd() const
846 {
847     int totalCols = table()->numEffCols();
848     if (!m_gridRows || !totalCols)
849         return 0;
850
851     unsigned borderWidth = 0;
852
853     const BorderValue& sb = style()->borderEnd();
854     if (sb.style() == BHIDDEN)
855         return -1;
856     if (sb.style() > BHIDDEN)
857         borderWidth = sb.width();
858
859     if (RenderTableCol* colGroup = table()->colElement(totalCols - 1)) {
860         const BorderValue& gb = colGroup->style()->borderEnd();
861         if (gb.style() == BHIDDEN)
862             return -1;
863         if (gb.style() > BHIDDEN && gb.width() > borderWidth)
864             borderWidth = gb.width();
865     }
866
867     bool allHidden = true;
868     for (int r = 0; r < m_gridRows; r++) {
869         const CellStruct& current = cellAt(r, totalCols - 1);
870         if (!current.hasCells())
871             continue;
872         // FIXME: Don't repeat for the same cell
873         const BorderValue& cb = current.primaryCell()->style()->borderEnd(); // FIXME: Make this work with perpendicular and flipped cells.
874         const BorderValue& rb = current.primaryCell()->parent()->style()->borderEnd();
875         if (cb.style() == BHIDDEN || rb.style() == BHIDDEN)
876             continue;
877         allHidden = false;
878         if (cb.style() > BHIDDEN && cb.width() > borderWidth)
879             borderWidth = cb.width();
880         if (rb.style() > BHIDDEN && rb.width() > borderWidth)
881             borderWidth = rb.width();
882     }
883     if (allHidden)
884         return -1;
885
886     return (borderWidth + (table()->style()->isLeftToRightDirection() ? 1 : 0)) / 2;
887 }
888
889 void RenderTableSection::recalcOuterBorder()
890 {
891     m_outerBorderBefore = calcOuterBorderBefore();
892     m_outerBorderAfter = calcOuterBorderAfter();
893     m_outerBorderStart = calcOuterBorderStart();
894     m_outerBorderEnd = calcOuterBorderEnd();
895 }
896
897 LayoutUnit RenderTableSection::firstLineBoxBaseline() const
898 {
899     if (!m_gridRows)
900         return -1;
901
902     LayoutUnit firstLineBaseline = m_grid[0].baseline;
903     if (firstLineBaseline)
904         return firstLineBaseline + m_rowPos[0];
905
906     firstLineBaseline = -1;
907     Row* firstRow = m_grid[0].row;
908     for (size_t i = 0; i < firstRow->size(); ++i) {
909         CellStruct& cs = firstRow->at(i);
910         RenderTableCell* cell = cs.primaryCell();
911         if (cell)
912             firstLineBaseline = max(firstLineBaseline, cell->logicalTop() + cell->paddingBefore() + cell->borderBefore() + cell->contentLogicalHeight());
913     }
914
915     return firstLineBaseline;
916 }
917
918 void RenderTableSection::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
919 {
920     // put this back in when all layout tests can handle it
921     // ASSERT(!needsLayout());
922     // avoid crashing on bugs that cause us to paint with dirty layout
923     if (needsLayout())
924         return;
925     
926     unsigned totalRows = m_gridRows;
927     unsigned totalCols = table()->columns().size();
928
929     if (!totalRows || !totalCols)
930         return;
931
932     LayoutPoint adjustedPaintOffset = paintOffset + location();
933
934     PaintPhase phase = paintInfo.phase;
935     bool pushedClip = pushContentsClip(paintInfo, adjustedPaintOffset);
936     paintObject(paintInfo, adjustedPaintOffset);
937     if (pushedClip)
938         popContentsClip(paintInfo, phase, adjustedPaintOffset);
939 }
940
941 static inline bool compareCellPositions(RenderTableCell* elem1, RenderTableCell* elem2)
942 {
943     return elem1->row() < elem2->row();
944 }
945
946 // This comparison is used only when we have overflowing cells as we have an unsorted array to sort. We thus need
947 // to sort both on rows and columns to properly repaint.
948 static inline bool compareCellPositionsWithOverflowingCells(RenderTableCell* elem1, RenderTableCell* elem2)
949 {
950     if (elem1->row() != elem2->row())
951         return elem1->row() < elem2->row();
952
953     return elem1->col() < elem2->col();
954 }
955
956 void RenderTableSection::paintCell(RenderTableCell* cell, PaintInfo& paintInfo, const LayoutPoint& paintOffset)
957 {
958     LayoutPoint cellPoint = flipForWritingMode(cell, paintOffset, ParentToChildFlippingAdjustment);
959     PaintPhase paintPhase = paintInfo.phase;
960     RenderTableRow* row = toRenderTableRow(cell->parent());
961
962     if (paintPhase == PaintPhaseBlockBackground || paintPhase == PaintPhaseChildBlockBackground) {
963         // We need to handle painting a stack of backgrounds.  This stack (from bottom to top) consists of
964         // the column group, column, row group, row, and then the cell.
965         RenderObject* col = table()->colElement(cell->col());
966         RenderObject* colGroup = 0;
967         if (col && col->parent()->style()->display() == TABLE_COLUMN_GROUP)
968             colGroup = col->parent();
969
970         // Column groups and columns first.
971         // FIXME: Columns and column groups do not currently support opacity, and they are being painted "too late" in
972         // the stack, since we have already opened a transparency layer (potentially) for the table row group.
973         // Note that we deliberately ignore whether or not the cell has a layer, since these backgrounds paint "behind" the
974         // cell.
975         cell->paintBackgroundsBehindCell(paintInfo, cellPoint, colGroup);
976         cell->paintBackgroundsBehindCell(paintInfo, cellPoint, col);
977
978         // Paint the row group next.
979         cell->paintBackgroundsBehindCell(paintInfo, cellPoint, this);
980
981         // Paint the row next, but only if it doesn't have a layer.  If a row has a layer, it will be responsible for
982         // painting the row background for the cell.
983         if (!row->hasSelfPaintingLayer())
984             cell->paintBackgroundsBehindCell(paintInfo, cellPoint, row);
985     }
986     if ((!cell->hasSelfPaintingLayer() && !row->hasSelfPaintingLayer()) || paintInfo.phase == PaintPhaseCollapsedTableBorders)
987         cell->paint(paintInfo, cellPoint);
988 }
989
990 void RenderTableSection::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
991 {
992     // Check which rows and cols are visible and only paint these.
993     unsigned totalRows = m_gridRows;
994     unsigned totalCols = table()->columns().size();
995
996     PaintPhase paintPhase = paintInfo.phase;
997
998     LayoutUnit os = 2 * maximalOutlineSize(paintPhase);
999     unsigned startrow = 0;
1000     unsigned endrow = totalRows;
1001
1002     LayoutRect localRepaintRect = paintInfo.rect;
1003     localRepaintRect.moveBy(-paintOffset);
1004     if (style()->isFlippedBlocksWritingMode()) {
1005         if (style()->isHorizontalWritingMode())
1006             localRepaintRect.setY(height() - localRepaintRect.maxY());
1007         else
1008             localRepaintRect.setX(width() - localRepaintRect.maxX());
1009     }
1010
1011     if (!m_forceSlowPaintPathWithOverflowingCell) {
1012         LayoutUnit before = (style()->isHorizontalWritingMode() ? localRepaintRect.y() : localRepaintRect.x()) - os;
1013         // binary search to find a row
1014         startrow = std::lower_bound(m_rowPos.begin(), m_rowPos.end(), before) - m_rowPos.begin();
1015
1016         // The binary search above gives us the first row with
1017         // a y position >= the top of the paint rect. Thus, the previous
1018         // may need to be repainted as well.
1019         if (startrow == m_rowPos.size() || (startrow > 0 && (m_rowPos[startrow] >  before)))
1020           --startrow;
1021
1022         LayoutUnit after = (style()->isHorizontalWritingMode() ? localRepaintRect.maxY() : localRepaintRect.maxX()) + os;
1023         endrow = std::lower_bound(m_rowPos.begin(), m_rowPos.end(), after) - m_rowPos.begin();
1024         if (endrow == m_rowPos.size())
1025           --endrow;
1026
1027         if (!endrow && m_rowPos[0] - table()->outerBorderBefore() <= after)
1028             ++endrow;
1029     }
1030
1031     unsigned startcol = 0;
1032     unsigned endcol = totalCols;
1033     // FIXME: Implement RTL.
1034     if (!m_forceSlowPaintPathWithOverflowingCell && style()->isLeftToRightDirection()) {
1035         LayoutUnit start = (style()->isHorizontalWritingMode() ? localRepaintRect.x() : localRepaintRect.y()) - os;
1036         Vector<LayoutUnit>& columnPos = table()->columnPositions();
1037         startcol = std::lower_bound(columnPos.begin(), columnPos.end(), start) - columnPos.begin();
1038         if ((startcol == columnPos.size()) || (startcol > 0 && (columnPos[startcol] > start)))
1039             --startcol;
1040
1041         LayoutUnit end = (style()->isHorizontalWritingMode() ? localRepaintRect.maxX() : localRepaintRect.maxY()) + os;
1042         endcol = std::lower_bound(columnPos.begin(), columnPos.end(), end) - columnPos.begin();
1043         if (endcol == columnPos.size())
1044             --endcol;
1045
1046         if (!endcol && columnPos[0] - table()->outerBorderStart() <= end)
1047             ++endcol;
1048     }
1049     if (startcol < endcol) {
1050         if (!m_hasMultipleCellLevels && !m_overflowingCells.size()) {
1051             // Draw the dirty cells in the order that they appear.
1052             for (unsigned r = startrow; r < endrow; r++) {
1053                 for (unsigned c = startcol; c < endcol; c++) {
1054                     CellStruct& current = cellAt(r, c);
1055                     RenderTableCell* cell = current.primaryCell();
1056                     if (!cell || (r > startrow && primaryCellAt(r - 1, c) == cell) || (c > startcol && primaryCellAt(r, c - 1) == cell))
1057                         continue;
1058                     paintCell(cell, paintInfo, paintOffset);
1059                 }
1060             }
1061         } else {
1062             // The overflowing cells should be scarce to avoid adding a lot of cells to the HashSet.
1063             ASSERT(m_overflowingCells.size() < totalRows * totalCols * gMaxAllowedOverflowingCellRatioForFastPaintPath);
1064
1065             // To make sure we properly repaint the section, we repaint all the overflowing cells that we collected.
1066             Vector<RenderTableCell*> cells;
1067             copyToVector(m_overflowingCells, cells);
1068
1069             HashSet<RenderTableCell*> spanningCells;
1070
1071             for (unsigned r = startrow; r < endrow; r++) {
1072                 for (unsigned c = startcol; c < endcol; c++) {
1073                     CellStruct& current = cellAt(r, c);
1074                     if (!current.hasCells())
1075                         continue;
1076                     for (unsigned i = 0; i < current.cells.size(); ++i) {
1077                         if (m_overflowingCells.contains(current.cells[i]))
1078                             continue;
1079
1080                         if (current.cells[i]->rowSpan() > 1 || current.cells[i]->colSpan() > 1) {
1081                             if (spanningCells.contains(current.cells[i]))
1082                                 continue;
1083                             spanningCells.add(current.cells[i]);
1084                         }
1085
1086                         cells.append(current.cells[i]);
1087                     }
1088                 }
1089             }
1090
1091             // Sort the dirty cells by paint order.
1092             if (!m_overflowingCells.size())
1093                 std::stable_sort(cells.begin(), cells.end(), compareCellPositions);
1094             else
1095                 std::sort(cells.begin(), cells.end(), compareCellPositionsWithOverflowingCells);
1096
1097             int size = cells.size();
1098             // Paint the cells.
1099             for (int i = 0; i < size; ++i)
1100                 paintCell(cells[i], paintInfo, paintOffset);
1101         }
1102     }
1103 }
1104
1105 void RenderTableSection::imageChanged(WrappedImagePtr, const IntRect*)
1106 {
1107     // FIXME: Examine cells and repaint only the rect the image paints in.
1108     repaint();
1109 }
1110
1111 void RenderTableSection::recalcCells()
1112 {
1113     m_cCol = 0;
1114     m_cRow = -1;
1115     clearGrid();
1116     m_gridRows = 0;
1117
1118     for (RenderObject* row = firstChild(); row; row = row->nextSibling()) {
1119         if (row->isTableRow()) {
1120             m_cRow++;
1121             m_cCol = 0;
1122             if (!ensureRows(m_cRow + 1))
1123                 break;
1124             
1125             RenderTableRow* tableRow = toRenderTableRow(row);
1126             m_grid[m_cRow].rowRenderer = tableRow;
1127             setRowLogicalHeightToRowStyleLogicalHeightIfNotRelative(&m_grid[m_cRow]);
1128
1129             for (RenderObject* cell = row->firstChild(); cell; cell = cell->nextSibling()) {
1130                 if (cell->isTableCell())
1131                     addCell(toRenderTableCell(cell), tableRow);
1132             }
1133         }
1134     }
1135     m_needsCellRecalc = false;
1136     setNeedsLayout(true);
1137 }
1138
1139 void RenderTableSection::setNeedsCellRecalc()
1140 {
1141     m_needsCellRecalc = true;
1142     if (RenderTable* t = table())
1143         t->setNeedsSectionRecalc();
1144 }
1145
1146 void RenderTableSection::clearGrid()
1147 {
1148     int rows = m_gridRows;
1149     while (rows--)
1150         delete m_grid[rows].row;
1151 }
1152
1153 int RenderTableSection::numColumns() const
1154 {
1155     int result = 0;
1156     
1157     for (int r = 0; r < m_gridRows; ++r) {
1158         for (int c = result; c < table()->numEffCols(); ++c) {
1159             const CellStruct& cell = cellAt(r, c);
1160             if (cell.hasCells() || cell.inColSpan)
1161                 result = c;
1162         }
1163     }
1164     
1165     return result + 1;
1166 }
1167
1168 void RenderTableSection::appendColumn(int pos)
1169 {
1170     for (int row = 0; row < m_gridRows; ++row)
1171         m_grid[row].row->resize(pos + 1);
1172 }
1173
1174 void RenderTableSection::splitColumn(int pos, int first)
1175 {
1176     if (m_cCol > pos)
1177         m_cCol++;
1178     for (int row = 0; row < m_gridRows; ++row) {
1179         Row& r = *m_grid[row].row;
1180         r.insert(pos + 1, CellStruct());
1181         if (r[pos].hasCells()) {
1182             r[pos + 1].cells.append(r[pos].cells);
1183             RenderTableCell* cell = r[pos].primaryCell();
1184             ASSERT(cell);
1185             int colleft = cell->colSpan() - r[pos].inColSpan;
1186             if (first > colleft)
1187               r[pos + 1].inColSpan = 0;
1188             else
1189               r[pos + 1].inColSpan = first + r[pos].inColSpan;
1190         } else {
1191             r[pos + 1].inColSpan = 0;
1192         }
1193     }
1194 }
1195
1196 // Hit Testing
1197 bool RenderTableSection::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
1198 {
1199     // If we have no children then we have nothing to do.
1200     if (!firstChild())
1201         return false;
1202
1203     // Table sections cannot ever be hit tested.  Effectively they do not exist.
1204     // Just forward to our children always.
1205     LayoutPoint adjustedLocation = accumulatedOffset + location();
1206
1207     if (hasOverflowClip() && !overflowClipRect(adjustedLocation).intersects(result.rectForPoint(pointInContainer)))
1208         return false;
1209
1210     if (hasOverflowingCell()) {
1211         for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
1212             // FIXME: We have to skip over inline flows, since they can show up inside table rows
1213             // at the moment (a demoted inline <form> for example). If we ever implement a
1214             // table-specific hit-test method (which we should do for performance reasons anyway),
1215             // then we can remove this check.
1216             if (child->isBox() && !toRenderBox(child)->hasSelfPaintingLayer()) {
1217                 LayoutPoint childPoint = flipForWritingMode(toRenderBox(child), adjustedLocation, ParentToChildFlippingAdjustment);
1218                 if (child->nodeAtPoint(request, result, pointInContainer, childPoint, action)) {
1219                     updateHitTestResult(result, toLayoutPoint(pointInContainer - childPoint));
1220                     return true;
1221                 }
1222             }
1223         }
1224         return false;
1225     }
1226
1227     LayoutPoint location = pointInContainer - toLayoutSize(adjustedLocation);
1228     if (style()->isFlippedBlocksWritingMode()) {
1229         if (style()->isHorizontalWritingMode())
1230             location.setY(height() - location.y());
1231         else
1232             location.setX(width() - location.x());
1233     }
1234
1235     LayoutUnit offsetInColumnDirection = style()->isHorizontalWritingMode() ? location.y() : location.x();
1236     // Find the first row that starts after offsetInColumnDirection.
1237     unsigned nextRow = std::upper_bound(m_rowPos.begin(), m_rowPos.end(), offsetInColumnDirection) - m_rowPos.begin();
1238     if (nextRow == m_rowPos.size())
1239         return false;
1240     // Now set hitRow to the index of the hit row, or 0.
1241     unsigned hitRow = nextRow > 0 ? nextRow - 1 : 0;
1242
1243     Vector<LayoutUnit>& columnPos = table()->columnPositions();
1244     LayoutUnit offsetInRowDirection = style()->isHorizontalWritingMode() ? location.x() : location.y();
1245     if (!style()->isLeftToRightDirection())
1246         offsetInRowDirection = columnPos[columnPos.size() - 1] - offsetInRowDirection;
1247
1248     unsigned nextColumn = std::lower_bound(columnPos.begin(), columnPos.end(), offsetInRowDirection) - columnPos.begin();
1249     if (nextColumn == columnPos.size())
1250         return false;
1251     unsigned hitColumn = nextColumn > 0 ? nextColumn - 1 : 0;
1252
1253     CellStruct& current = cellAt(hitRow, hitColumn);
1254
1255     // If the cell is empty, there's nothing to do
1256     if (!current.hasCells())
1257         return false;
1258
1259     for (int i = current.cells.size() - 1; i >= 0; --i) {
1260         RenderTableCell* cell = current.cells[i];
1261         LayoutPoint cellPoint = flipForWritingMode(cell, adjustedLocation, ParentToChildFlippingAdjustment);
1262         if (static_cast<RenderObject*>(cell)->nodeAtPoint(request, result, pointInContainer, cellPoint, action)) {
1263             updateHitTestResult(result, toLayoutPoint(pointInContainer - cellPoint));
1264             return true;
1265         }
1266     }
1267     return false;
1268
1269 }
1270
1271 } // namespace WebCore