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