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