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