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