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