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