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