Home | History | Annotate | Download | only in rendering
      1 /*
      2  * Copyright (C) 1997 Martin Jones (mjones (at) kde.org)
      3  *           (C) 1997 Torben Weis (weis (at) kde.org)
      4  *           (C) 1998 Waldo Bastian (bastian (at) kde.org)
      5  *           (C) 1999 Lars Knoll (knoll (at) kde.org)
      6  *           (C) 1999 Antti Koivisto (koivisto (at) kde.org)
      7  * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
      8  *
      9  * This library is free software; you can redistribute it and/or
     10  * modify it under the terms of the GNU Library General Public
     11  * License as published by the Free Software Foundation; either
     12  * version 2 of the License, or (at your option) any later version.
     13  *
     14  * This library is distributed in the hope that it will be useful,
     15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
     16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     17  * Library General Public License for more details.
     18  *
     19  * You should have received a copy of the GNU Library General Public License
     20  * along with this library; see the file COPYING.LIB.  If not, write to
     21  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
     22  * Boston, MA 02110-1301, USA.
     23  */
     24 
     25 #include "config.h"
     26 #include "core/rendering/RenderTableCell.h"
     27 
     28 #include "HTMLNames.h"
     29 #include "core/css/StylePropertySet.h"
     30 #include "core/html/HTMLTableCellElement.h"
     31 #include "core/rendering/LayoutRectRecorder.h"
     32 #include "core/rendering/PaintInfo.h"
     33 #include "core/rendering/RenderTableCol.h"
     34 #include "core/rendering/RenderView.h"
     35 #include "core/rendering/SubtreeLayoutScope.h"
     36 #include "core/rendering/style/CollapsedBorderValue.h"
     37 #include "platform/geometry/FloatQuad.h"
     38 #include "platform/geometry/TransformState.h"
     39 #include "platform/graphics/GraphicsContextStateSaver.h"
     40 
     41 using namespace std;
     42 
     43 namespace WebCore {
     44 
     45 using namespace HTMLNames;
     46 
     47 struct SameSizeAsRenderTableCell : public RenderBlockFlow {
     48     unsigned bitfields;
     49     int paddings[2];
     50 };
     51 
     52 COMPILE_ASSERT(sizeof(RenderTableCell) == sizeof(SameSizeAsRenderTableCell), RenderTableCell_should_stay_small);
     53 COMPILE_ASSERT(sizeof(CollapsedBorderValue) == 8, CollapsedBorderValue_should_stay_small);
     54 
     55 RenderTableCell::RenderTableCell(Element* element)
     56     : RenderBlockFlow(element)
     57     , m_column(unsetColumnIndex)
     58     , m_cellWidthChanged(false)
     59     , m_intrinsicPaddingBefore(0)
     60     , m_intrinsicPaddingAfter(0)
     61 {
     62     // We only update the flags when notified of DOM changes in colSpanOrRowSpanChanged()
     63     // so we need to set their initial values here in case something asks for colSpan()/rowSpan() before then.
     64     updateColAndRowSpanFlags();
     65 }
     66 
     67 void RenderTableCell::willBeRemovedFromTree()
     68 {
     69     RenderBlock::willBeRemovedFromTree();
     70 
     71     section()->setNeedsCellRecalc();
     72     section()->removeCachedCollapsedBorders(this);
     73 }
     74 
     75 unsigned RenderTableCell::parseColSpanFromDOM() const
     76 {
     77     ASSERT(node());
     78     if (node()->hasTagName(tdTag) || node()->hasTagName(thTag))
     79         return min<unsigned>(toHTMLTableCellElement(node())->colSpan(), maxColumnIndex);
     80     return 1;
     81 }
     82 
     83 unsigned RenderTableCell::parseRowSpanFromDOM() const
     84 {
     85     ASSERT(node());
     86     if (node()->hasTagName(tdTag) || node()->hasTagName(thTag))
     87         return min<unsigned>(toHTMLTableCellElement(node())->rowSpan(), maxRowIndex);
     88     return 1;
     89 }
     90 
     91 void RenderTableCell::updateColAndRowSpanFlags()
     92 {
     93     // The vast majority of table cells do not have a colspan or rowspan,
     94     // so we keep a bool to know if we need to bother reading from the DOM.
     95     m_hasColSpan = node() && parseColSpanFromDOM() != 1;
     96     m_hasRowSpan = node() && parseRowSpanFromDOM() != 1;
     97 }
     98 
     99 void RenderTableCell::colSpanOrRowSpanChanged()
    100 {
    101     ASSERT(node());
    102     ASSERT(node()->hasTagName(tdTag) || node()->hasTagName(thTag));
    103 
    104     updateColAndRowSpanFlags();
    105 
    106     // FIXME: I suspect that we could return early here if !m_hasColSpan && !m_hasRowSpan.
    107 
    108     setNeedsLayoutAndPrefWidthsRecalc();
    109     if (parent() && section())
    110         section()->setNeedsCellRecalc();
    111 }
    112 
    113 Length RenderTableCell::logicalWidthFromColumns(RenderTableCol* firstColForThisCell, Length widthFromStyle) const
    114 {
    115     ASSERT(firstColForThisCell && firstColForThisCell == table()->colElement(col()));
    116     RenderTableCol* tableCol = firstColForThisCell;
    117 
    118     unsigned colSpanCount = colSpan();
    119     int colWidthSum = 0;
    120     for (unsigned i = 1; i <= colSpanCount; i++) {
    121         Length colWidth = tableCol->style()->logicalWidth();
    122 
    123         // Percentage value should be returned only for colSpan == 1.
    124         // Otherwise we return original width for the cell.
    125         if (!colWidth.isFixed()) {
    126             if (colSpanCount > 1)
    127                 return widthFromStyle;
    128             return colWidth;
    129         }
    130 
    131         colWidthSum += colWidth.value();
    132         tableCol = tableCol->nextColumn();
    133         // If no next <col> tag found for the span we just return what we have for now.
    134         if (!tableCol)
    135             break;
    136     }
    137 
    138     // Column widths specified on <col> apply to the border box of the cell, see bug 8126.
    139     // FIXME: Why is border/padding ignored in the negative width case?
    140     if (colWidthSum > 0)
    141         return Length(max(0, colWidthSum - borderAndPaddingLogicalWidth().ceil()), Fixed);
    142     return Length(colWidthSum, Fixed);
    143 }
    144 
    145 void RenderTableCell::computePreferredLogicalWidths()
    146 {
    147     // The child cells rely on the grids up in the sections to do their computePreferredLogicalWidths work.  Normally the sections are set up early, as table
    148     // cells are added, but relayout can cause the cells to be freed, leaving stale pointers in the sections'
    149     // grids.  We must refresh those grids before the child cells try to use them.
    150     table()->recalcSectionsIfNeeded();
    151 
    152     RenderBlock::computePreferredLogicalWidths();
    153     if (node() && style()->autoWrap()) {
    154         // See if nowrap was set.
    155         Length w = styleOrColLogicalWidth();
    156         const AtomicString& nowrap = toElement(node())->getAttribute(nowrapAttr);
    157         if (!nowrap.isNull() && w.isFixed())
    158             // Nowrap is set, but we didn't actually use it because of the
    159             // fixed width set on the cell.  Even so, it is a WinIE/Moz trait
    160             // to make the minwidth of the cell into the fixed width.  They do this
    161             // even in strict mode, so do not make this a quirk.  Affected the top
    162             // of hiptop.com.
    163             m_minPreferredLogicalWidth = max<LayoutUnit>(w.value(), m_minPreferredLogicalWidth);
    164     }
    165 }
    166 
    167 void RenderTableCell::addLayerHitTestRects(LayerHitTestRects& layerRects, const RenderLayer* currentLayer, const LayoutPoint& layerOffset, const LayoutRect& containerRect) const
    168 {
    169     LayoutPoint adjustedLayerOffset = layerOffset;
    170     // RenderTableCell's location includes the offset of it's containing RenderTableRow, so
    171     // we need to subtract that again here (as for RenderTableCell::offsetFromContainer.
    172     if (parent())
    173         adjustedLayerOffset -= parentBox()->locationOffset();
    174     RenderBox::addLayerHitTestRects(layerRects, currentLayer, adjustedLayerOffset, containerRect);
    175 }
    176 
    177 void RenderTableCell::computeIntrinsicPadding(int rowHeight, SubtreeLayoutScope& layouter)
    178 {
    179     int oldIntrinsicPaddingBefore = intrinsicPaddingBefore();
    180     int oldIntrinsicPaddingAfter = intrinsicPaddingAfter();
    181     int logicalHeightWithoutIntrinsicPadding = pixelSnappedLogicalHeight() - oldIntrinsicPaddingBefore - oldIntrinsicPaddingAfter;
    182 
    183     int intrinsicPaddingBefore = 0;
    184     switch (style()->verticalAlign()) {
    185     case SUB:
    186     case SUPER:
    187     case TEXT_TOP:
    188     case TEXT_BOTTOM:
    189     case LENGTH:
    190     case BASELINE: {
    191         LayoutUnit baseline = cellBaselinePosition();
    192         if (baseline > borderBefore() + paddingBefore())
    193             intrinsicPaddingBefore = section()->rowBaseline(rowIndex()) - (baseline - oldIntrinsicPaddingBefore);
    194         break;
    195     }
    196     case TOP:
    197         break;
    198     case MIDDLE:
    199         intrinsicPaddingBefore = (rowHeight - logicalHeightWithoutIntrinsicPadding) / 2;
    200         break;
    201     case BOTTOM:
    202         intrinsicPaddingBefore = rowHeight - logicalHeightWithoutIntrinsicPadding;
    203         break;
    204     case BASELINE_MIDDLE:
    205         break;
    206     }
    207 
    208     int intrinsicPaddingAfter = rowHeight - logicalHeightWithoutIntrinsicPadding - intrinsicPaddingBefore;
    209     setIntrinsicPaddingBefore(intrinsicPaddingBefore);
    210     setIntrinsicPaddingAfter(intrinsicPaddingAfter);
    211 
    212     // FIXME: Changing an intrinsic padding shouldn't trigger a relayout as it only shifts the cell inside the row but
    213     // doesn't change the logical height.
    214     if (intrinsicPaddingBefore != oldIntrinsicPaddingBefore || intrinsicPaddingAfter != oldIntrinsicPaddingAfter)
    215         layouter.setNeedsLayout(this);
    216 }
    217 
    218 void RenderTableCell::updateLogicalWidth()
    219 {
    220 }
    221 
    222 void RenderTableCell::setCellLogicalWidth(int tableLayoutLogicalWidth, SubtreeLayoutScope& layouter)
    223 {
    224     if (tableLayoutLogicalWidth == logicalWidth())
    225         return;
    226 
    227     layouter.setNeedsLayout(this);
    228 
    229     if (!table()->selfNeedsLayout() && checkForRepaintDuringLayout())
    230         repaint();
    231 
    232     setLogicalWidth(tableLayoutLogicalWidth);
    233     setCellWidthChanged(true);
    234 }
    235 
    236 void RenderTableCell::layout()
    237 {
    238     ASSERT(needsLayout());
    239 
    240     LayoutRectRecorder recorder(*this);
    241 
    242     updateFirstLetter();
    243 
    244     int oldCellBaseline = cellBaselinePosition();
    245     layoutBlock(cellWidthChanged());
    246 
    247     // If we have replaced content, the intrinsic height of our content may have changed since the last time we laid out. If that's the case the intrinsic padding we used
    248     // for layout (the padding required to push the contents of the cell down to the row's baseline) is included in our new height and baseline and makes both
    249     // of them wrong. So if our content's intrinsic height has changed push the new content up into the intrinsic padding and relayout so that the rest of
    250     // table and row layout can use the correct baseline and height for this cell.
    251     if (isBaselineAligned() && section()->rowBaseline(rowIndex()) && cellBaselinePosition() > section()->rowBaseline(rowIndex())) {
    252         int newIntrinsicPaddingBefore = max<LayoutUnit>(0, intrinsicPaddingBefore() - max<LayoutUnit>(0, cellBaselinePosition() - oldCellBaseline));
    253         setIntrinsicPaddingBefore(newIntrinsicPaddingBefore);
    254         SubtreeLayoutScope layouter(this);
    255         layouter.setNeedsLayout(this);
    256         layoutBlock(cellWidthChanged());
    257     }
    258 
    259     setCellWidthChanged(false);
    260 }
    261 
    262 LayoutUnit RenderTableCell::paddingTop() const
    263 {
    264     int result = computedCSSPaddingTop();
    265     if (!isHorizontalWritingMode())
    266         return result;
    267     return result + (style()->writingMode() == TopToBottomWritingMode ? intrinsicPaddingBefore() : intrinsicPaddingAfter());
    268 }
    269 
    270 LayoutUnit RenderTableCell::paddingBottom() const
    271 {
    272     int result = computedCSSPaddingBottom();
    273     if (!isHorizontalWritingMode())
    274         return result;
    275     return result + (style()->writingMode() == TopToBottomWritingMode ? intrinsicPaddingAfter() : intrinsicPaddingBefore());
    276 }
    277 
    278 LayoutUnit RenderTableCell::paddingLeft() const
    279 {
    280     int result = computedCSSPaddingLeft();
    281     if (isHorizontalWritingMode())
    282         return result;
    283     return result + (style()->writingMode() == LeftToRightWritingMode ? intrinsicPaddingBefore() : intrinsicPaddingAfter());
    284 }
    285 
    286 LayoutUnit RenderTableCell::paddingRight() const
    287 {
    288     int result = computedCSSPaddingRight();
    289     if (isHorizontalWritingMode())
    290         return result;
    291     return result + (style()->writingMode() == LeftToRightWritingMode ? intrinsicPaddingAfter() : intrinsicPaddingBefore());
    292 }
    293 
    294 LayoutUnit RenderTableCell::paddingBefore() const
    295 {
    296     return static_cast<int>(computedCSSPaddingBefore()) + intrinsicPaddingBefore();
    297 }
    298 
    299 LayoutUnit RenderTableCell::paddingAfter() const
    300 {
    301     return static_cast<int>(computedCSSPaddingAfter()) + intrinsicPaddingAfter();
    302 }
    303 
    304 void RenderTableCell::setOverrideLogicalContentHeightFromRowHeight(LayoutUnit rowHeight)
    305 {
    306     clearIntrinsicPadding();
    307     setOverrideLogicalContentHeight(max<LayoutUnit>(0, rowHeight - borderAndPaddingLogicalHeight()));
    308 }
    309 
    310 LayoutSize RenderTableCell::offsetFromContainer(RenderObject* o, const LayoutPoint& point, bool* offsetDependsOnPoint) const
    311 {
    312     ASSERT(o == container());
    313 
    314     LayoutSize offset = RenderBlock::offsetFromContainer(o, point, offsetDependsOnPoint);
    315     if (parent())
    316         offset -= parentBox()->locationOffset();
    317 
    318     return offset;
    319 }
    320 
    321 LayoutRect RenderTableCell::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
    322 {
    323     // If the table grid is dirty, we cannot get reliable information about adjoining cells,
    324     // so we ignore outside borders. This should not be a problem because it means that
    325     // the table is going to recalculate the grid, relayout and repaint its current rect, which
    326     // includes any outside borders of this cell.
    327     if (!table()->collapseBorders() || table()->needsSectionRecalc())
    328         return RenderBlock::clippedOverflowRectForRepaint(repaintContainer);
    329 
    330     bool rtl = !styleForCellFlow()->isLeftToRightDirection();
    331     int outlineSize = style()->outlineSize();
    332     int left = max(borderHalfLeft(true), outlineSize);
    333     int right = max(borderHalfRight(true), outlineSize);
    334     int top = max(borderHalfTop(true), outlineSize);
    335     int bottom = max(borderHalfBottom(true), outlineSize);
    336     if ((left && !rtl) || (right && rtl)) {
    337         if (RenderTableCell* before = table()->cellBefore(this)) {
    338             top = max(top, before->borderHalfTop(true));
    339             bottom = max(bottom, before->borderHalfBottom(true));
    340         }
    341     }
    342     if ((left && rtl) || (right && !rtl)) {
    343         if (RenderTableCell* after = table()->cellAfter(this)) {
    344             top = max(top, after->borderHalfTop(true));
    345             bottom = max(bottom, after->borderHalfBottom(true));
    346         }
    347     }
    348     if (top) {
    349         if (RenderTableCell* above = table()->cellAbove(this)) {
    350             left = max(left, above->borderHalfLeft(true));
    351             right = max(right, above->borderHalfRight(true));
    352         }
    353     }
    354     if (bottom) {
    355         if (RenderTableCell* below = table()->cellBelow(this)) {
    356             left = max(left, below->borderHalfLeft(true));
    357             right = max(right, below->borderHalfRight(true));
    358         }
    359     }
    360     LayoutPoint location(max<LayoutUnit>(left, -visualOverflowRect().x()), max<LayoutUnit>(top, -visualOverflowRect().y()));
    361     LayoutRect r(-location.x(), -location.y(), location.x() + max(width() + right, visualOverflowRect().maxX()), location.y() + max(height() + bottom, visualOverflowRect().maxY()));
    362 
    363     if (RenderView* v = view()) {
    364         // FIXME: layoutDelta needs to be applied in parts before/after transforms and
    365         // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
    366         r.move(v->layoutDelta());
    367     }
    368     computeRectForRepaint(repaintContainer, r);
    369     return r;
    370 }
    371 
    372 void RenderTableCell::computeRectForRepaint(const RenderLayerModelObject* repaintContainer, LayoutRect& r, bool fixed) const
    373 {
    374     if (repaintContainer == this)
    375         return;
    376     r.setY(r.y());
    377     RenderView* v = view();
    378     if ((!v || !v->layoutStateEnabled() || repaintContainer) && parent())
    379         r.moveBy(-parentBox()->location()); // Rows are in the same coordinate space, so don't add their offset in.
    380     RenderBlock::computeRectForRepaint(repaintContainer, r, fixed);
    381 }
    382 
    383 LayoutUnit RenderTableCell::cellBaselinePosition() const
    384 {
    385     // <http://www.w3.org/TR/2007/CR-CSS21-20070719/tables.html#height-layout>: The baseline of a cell is the baseline of
    386     // the first in-flow line box in the cell, or the first in-flow table-row in the cell, whichever comes first. If there
    387     // is no such line box or table-row, the baseline is the bottom of content edge of the cell box.
    388     LayoutUnit firstLineBaseline = firstLineBoxBaseline();
    389     if (firstLineBaseline != -1)
    390         return firstLineBaseline;
    391     return paddingBefore() + borderBefore() + contentLogicalHeight();
    392 }
    393 
    394 void RenderTableCell::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
    395 {
    396     ASSERT(style()->display() == TABLE_CELL);
    397     ASSERT(!row() || row()->rowIndexWasSet());
    398 
    399     RenderBlock::styleDidChange(diff, oldStyle);
    400     setHasBoxDecorations(true);
    401 
    402     if (parent() && section() && oldStyle && style()->height() != oldStyle->height())
    403         section()->rowLogicalHeightChanged(rowIndex());
    404 
    405     // Our intrinsic padding pushes us down to align with the baseline of other cells on the row. If our vertical-align
    406     // has changed then so will the padding needed to align with other cells - clear it so we can recalculate it from scratch.
    407     if (oldStyle && style()->verticalAlign() != oldStyle->verticalAlign())
    408         clearIntrinsicPadding();
    409 
    410     // If border was changed, notify table.
    411     if (parent()) {
    412         RenderTable* table = this->table();
    413         if (table && !table->selfNeedsLayout() && !table->normalChildNeedsLayout()&& oldStyle && oldStyle->border() != style()->border())
    414             table->invalidateCollapsedBorders();
    415     }
    416 }
    417 
    418 // The following rules apply for resolving conflicts and figuring out which border
    419 // to use.
    420 // (1) Borders with the 'border-style' of 'hidden' take precedence over all other conflicting
    421 // borders. Any border with this value suppresses all borders at this location.
    422 // (2) Borders with a style of 'none' have the lowest priority. Only if the border properties of all
    423 // the elements meeting at this edge are 'none' will the border be omitted (but note that 'none' is
    424 // the default value for the border style.)
    425 // (3) If none of the styles are 'hidden' and at least one of them is not 'none', then narrow borders
    426 // are discarded in favor of wider ones. If several have the same 'border-width' then styles are preferred
    427 // in this order: 'double', 'solid', 'dashed', 'dotted', 'ridge', 'outset', 'groove', and the lowest: 'inset'.
    428 // (4) If border styles differ only in color, then a style set on a cell wins over one on a row,
    429 // which wins over a row group, column, column group and, lastly, table. It is undefined which color
    430 // is used when two elements of the same type disagree.
    431 static int compareBorders(const CollapsedBorderValue& border1, const CollapsedBorderValue& border2)
    432 {
    433     // Sanity check the values passed in. The null border have lowest priority.
    434     if (!border2.exists()) {
    435         if (!border1.exists())
    436             return 0;
    437         return 1;
    438     }
    439     if (!border1.exists())
    440         return -1;
    441 
    442     // Rule #1 above.
    443     if (border2.style() == BHIDDEN) {
    444         if (border1.style() == BHIDDEN)
    445             return 0;
    446         return -1;
    447     }
    448     if (border1.style() == BHIDDEN)
    449         return 1;
    450 
    451     // Rule #2 above.  A style of 'none' has lowest priority and always loses to any other border.
    452     if (border2.style() == BNONE) {
    453         if (border1.style() == BNONE)
    454             return 0;
    455         return 1;
    456     }
    457     if (border1.style() == BNONE)
    458         return -1;
    459 
    460     // The first part of rule #3 above. Wider borders win.
    461     if (border1.width() != border2.width())
    462         return border1.width() < border2.width() ? -1 : 1;
    463 
    464     // The borders have equal width.  Sort by border style.
    465     if (border1.style() != border2.style())
    466         return border1.style() < border2.style() ? -1 : 1;
    467 
    468     // The border have the same width and style.  Rely on precedence (cell over row over row group, etc.)
    469     if (border1.precedence() == border2.precedence())
    470         return 0;
    471     return border1.precedence() < border2.precedence() ? -1 : 1;
    472 }
    473 
    474 static CollapsedBorderValue chooseBorder(const CollapsedBorderValue& border1, const CollapsedBorderValue& border2)
    475 {
    476     const CollapsedBorderValue& border = compareBorders(border1, border2) < 0 ? border2 : border1;
    477     return border.style() == BHIDDEN ? CollapsedBorderValue() : border;
    478 }
    479 
    480 bool RenderTableCell::hasStartBorderAdjoiningTable() const
    481 {
    482     bool isStartColumn = !col();
    483     bool isEndColumn = table()->colToEffCol(col() + colSpan() - 1) == table()->numEffCols() - 1;
    484     bool hasSameDirectionAsTable = hasSameDirectionAs(table());
    485 
    486     // The table direction determines the row direction. In mixed directionality, we cannot guarantee that
    487     // we have a common border with the table (think a ltr table with rtl start cell).
    488     return (isStartColumn && hasSameDirectionAsTable) || (isEndColumn && !hasSameDirectionAsTable);
    489 }
    490 
    491 bool RenderTableCell::hasEndBorderAdjoiningTable() const
    492 {
    493     bool isStartColumn = !col();
    494     bool isEndColumn = table()->colToEffCol(col() + colSpan() - 1) == table()->numEffCols() - 1;
    495     bool hasSameDirectionAsTable = hasSameDirectionAs(table());
    496 
    497     // The table direction determines the row direction. In mixed directionality, we cannot guarantee that
    498     // we have a common border with the table (think a ltr table with ltr end cell).
    499     return (isStartColumn && !hasSameDirectionAsTable) || (isEndColumn && hasSameDirectionAsTable);
    500 }
    501 
    502 CollapsedBorderValue RenderTableCell::collapsedStartBorder(IncludeBorderColorOrNot includeColor) const
    503 {
    504     CollapsedBorderValue result = computeCollapsedStartBorder(includeColor);
    505     if (includeColor)
    506         section()->setCachedCollapsedBorder(this, CBSStart, result);
    507     return result;
    508 }
    509 
    510 CollapsedBorderValue RenderTableCell::computeCollapsedStartBorder(IncludeBorderColorOrNot includeColor) const
    511 {
    512     RenderTable* table = this->table();
    513 
    514     // For the start border, we need to check, in order of precedence:
    515     // (1) Our start border.
    516     int startColorProperty = includeColor ? CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderStartColor, styleForCellFlow()->direction(), styleForCellFlow()->writingMode()) : 0;
    517     int endColorProperty = includeColor ? CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderEndColor, styleForCellFlow()->direction(), styleForCellFlow()->writingMode()) : 0;
    518     CollapsedBorderValue result(style()->borderStart(), includeColor ? resolveColor(startColorProperty) : Color(), BCELL);
    519 
    520     // (2) The end border of the preceding cell.
    521     RenderTableCell* cellBefore = table->cellBefore(this);
    522     if (cellBefore) {
    523         CollapsedBorderValue cellBeforeAdjoiningBorder = CollapsedBorderValue(cellBefore->borderAdjoiningCellAfter(this), includeColor ? cellBefore->resolveColor(endColorProperty) : Color(), BCELL);
    524         // |result| should be the 2nd argument as |cellBefore| should win in case of equality per CSS 2.1 (Border conflict resolution, point 4).
    525         result = chooseBorder(cellBeforeAdjoiningBorder, result);
    526         if (!result.exists())
    527             return result;
    528     }
    529 
    530     bool startBorderAdjoinsTable = hasStartBorderAdjoiningTable();
    531     if (startBorderAdjoinsTable) {
    532         // (3) Our row's start border.
    533         result = chooseBorder(result, CollapsedBorderValue(row()->borderAdjoiningStartCell(this), includeColor ? parent()->resolveColor(startColorProperty) : Color(), BROW));
    534         if (!result.exists())
    535             return result;
    536 
    537         // (4) Our row group's start border.
    538         result = chooseBorder(result, CollapsedBorderValue(section()->borderAdjoiningStartCell(this), includeColor ? section()->resolveColor(startColorProperty) : Color(), BROWGROUP));
    539         if (!result.exists())
    540             return result;
    541     }
    542 
    543     // (5) Our column and column group's start borders.
    544     bool startColEdge;
    545     bool endColEdge;
    546     if (RenderTableCol* colElt = table->colElement(col(), &startColEdge, &endColEdge)) {
    547         if (colElt->isTableColumnGroup() && startColEdge) {
    548             // The |colElt| is a column group and is also the first colgroup (in case of spanned colgroups).
    549             result = chooseBorder(result, CollapsedBorderValue(colElt->borderAdjoiningCellStartBorder(this), includeColor ? colElt->resolveColor(startColorProperty) : Color(), BCOLGROUP));
    550             if (!result.exists())
    551                 return result;
    552         } else if (!colElt->isTableColumnGroup()) {
    553             // We first consider the |colElt| and irrespective of whether it is a spanned col or not, we apply
    554             // its start border. This is as per HTML5 which states that: "For the purposes of the CSS table model,
    555             // the col element is expected to be treated as if it was present as many times as its span attribute specifies".
    556             result = chooseBorder(result, CollapsedBorderValue(colElt->borderAdjoiningCellStartBorder(this), includeColor ? colElt->resolveColor(startColorProperty) : Color(), BCOL));
    557             if (!result.exists())
    558                 return result;
    559             // Next, apply the start border of the enclosing colgroup but only if it is adjacent to the cell's edge.
    560             if (RenderTableCol* enclosingColumnGroup = colElt->enclosingColumnGroupIfAdjacentBefore()) {
    561                 result = chooseBorder(result, CollapsedBorderValue(enclosingColumnGroup->borderAdjoiningCellStartBorder(this), includeColor ? enclosingColumnGroup->resolveColor(startColorProperty) : Color(), BCOLGROUP));
    562                 if (!result.exists())
    563                     return result;
    564             }
    565         }
    566     }
    567 
    568     // (6) The end border of the preceding column.
    569     if (cellBefore) {
    570         if (RenderTableCol* colElt = table->colElement(col() - 1, &startColEdge, &endColEdge)) {
    571             if (colElt->isTableColumnGroup() && endColEdge) {
    572                 // The element is a colgroup and is also the last colgroup (in case of spanned colgroups).
    573                 result = chooseBorder(CollapsedBorderValue(colElt->borderAdjoiningCellAfter(this), includeColor ? colElt->resolveColor(endColorProperty) : Color(), BCOLGROUP), result);
    574                 if (!result.exists())
    575                     return result;
    576             } else if (colElt->isTableColumn()) {
    577                 // Resolve the collapsing border against the col's border ignoring any 'span' as per HTML5.
    578                 result = chooseBorder(CollapsedBorderValue(colElt->borderAdjoiningCellAfter(this), includeColor ? colElt->resolveColor(endColorProperty) : Color(), BCOL), result);
    579                 if (!result.exists())
    580                     return result;
    581                 // Next, if the previous col has a parent colgroup then its end border should be applied
    582                 // but only if it is adjacent to the cell's edge.
    583                 if (RenderTableCol* enclosingColumnGroup = colElt->enclosingColumnGroupIfAdjacentAfter()) {
    584                     result = chooseBorder(CollapsedBorderValue(enclosingColumnGroup->borderAdjoiningCellEndBorder(this), includeColor ? enclosingColumnGroup->resolveColor(endColorProperty) : Color(), BCOLGROUP), result);
    585                     if (!result.exists())
    586                         return result;
    587                 }
    588             }
    589         }
    590     }
    591 
    592     if (startBorderAdjoinsTable) {
    593         // (7) The table's start border.
    594         result = chooseBorder(result, CollapsedBorderValue(table->tableStartBorderAdjoiningCell(this), includeColor ? table->resolveColor(startColorProperty) : Color(), BTABLE));
    595         if (!result.exists())
    596             return result;
    597     }
    598 
    599     return result;
    600 }
    601 
    602 CollapsedBorderValue RenderTableCell::collapsedEndBorder(IncludeBorderColorOrNot includeColor) const
    603 {
    604     CollapsedBorderValue result = computeCollapsedEndBorder(includeColor);
    605     if (includeColor)
    606         section()->setCachedCollapsedBorder(this, CBSEnd, result);
    607     return result;
    608 }
    609 
    610 CollapsedBorderValue RenderTableCell::computeCollapsedEndBorder(IncludeBorderColorOrNot includeColor) const
    611 {
    612     RenderTable* table = this->table();
    613     // Note: We have to use the effective column information instead of whether we have a cell after as a table doesn't
    614     // have to be regular (any row can have less cells than the total cell count).
    615     bool isEndColumn = table->colToEffCol(col() + colSpan() - 1) == table->numEffCols() - 1;
    616 
    617     // For end border, we need to check, in order of precedence:
    618     // (1) Our end border.
    619     int startColorProperty = includeColor ? CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderStartColor, styleForCellFlow()->direction(), styleForCellFlow()->writingMode()) : 0;
    620     int endColorProperty = includeColor ? CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderEndColor, styleForCellFlow()->direction(), styleForCellFlow()->writingMode()) : 0;
    621     CollapsedBorderValue result = CollapsedBorderValue(style()->borderEnd(), includeColor ? resolveColor(endColorProperty) : Color(), BCELL);
    622 
    623     // (2) The start border of the following cell.
    624     if (!isEndColumn) {
    625         if (RenderTableCell* cellAfter = table->cellAfter(this)) {
    626             CollapsedBorderValue cellAfterAdjoiningBorder = CollapsedBorderValue(cellAfter->borderAdjoiningCellBefore(this), includeColor ? cellAfter->resolveColor(startColorProperty) : Color(), BCELL);
    627             result = chooseBorder(result, cellAfterAdjoiningBorder);
    628             if (!result.exists())
    629                 return result;
    630         }
    631     }
    632 
    633     bool endBorderAdjoinsTable = hasEndBorderAdjoiningTable();
    634     if (endBorderAdjoinsTable) {
    635         // (3) Our row's end border.
    636         result = chooseBorder(result, CollapsedBorderValue(row()->borderAdjoiningEndCell(this), includeColor ? parent()->resolveColor(endColorProperty) : Color(), BROW));
    637         if (!result.exists())
    638             return result;
    639 
    640         // (4) Our row group's end border.
    641         result = chooseBorder(result, CollapsedBorderValue(section()->borderAdjoiningEndCell(this), includeColor ? section()->resolveColor(endColorProperty) : Color(), BROWGROUP));
    642         if (!result.exists())
    643             return result;
    644     }
    645 
    646     // (5) Our column and column group's end borders.
    647     bool startColEdge;
    648     bool endColEdge;
    649     if (RenderTableCol* colElt = table->colElement(col() + colSpan() - 1, &startColEdge, &endColEdge)) {
    650         if (colElt->isTableColumnGroup() && endColEdge) {
    651             // The element is a colgroup and is also the last colgroup (in case of spanned colgroups).
    652             result = chooseBorder(result, CollapsedBorderValue(colElt->borderAdjoiningCellEndBorder(this), includeColor ? colElt->resolveColor(endColorProperty) : Color(), BCOLGROUP));
    653             if (!result.exists())
    654                 return result;
    655         } else if (!colElt->isTableColumnGroup()) {
    656             // First apply the end border of the column irrespective of whether it is spanned or not. This is as per
    657             // HTML5 which states that: "For the purposes of the CSS table model, the col element is expected to be
    658             // treated as if it was present as many times as its span attribute specifies".
    659             result = chooseBorder(result, CollapsedBorderValue(colElt->borderAdjoiningCellEndBorder(this), includeColor ? colElt->resolveColor(endColorProperty) : Color(), BCOL));
    660             if (!result.exists())
    661                 return result;
    662             // Next, if it has a parent colgroup then we apply its end border but only if it is adjacent to the cell.
    663             if (RenderTableCol* enclosingColumnGroup = colElt->enclosingColumnGroupIfAdjacentAfter()) {
    664                 result = chooseBorder(result, CollapsedBorderValue(enclosingColumnGroup->borderAdjoiningCellEndBorder(this), includeColor ? enclosingColumnGroup->resolveColor(endColorProperty) : Color(), BCOLGROUP));
    665                 if (!result.exists())
    666                     return result;
    667             }
    668         }
    669     }
    670 
    671     // (6) The start border of the next column.
    672     if (!isEndColumn) {
    673         if (RenderTableCol* colElt = table->colElement(col() + colSpan(), &startColEdge, &endColEdge)) {
    674             if (colElt->isTableColumnGroup() && startColEdge) {
    675                 // This case is a colgroup without any col, we only compute it if it is adjacent to the cell's edge.
    676                 result = chooseBorder(result, CollapsedBorderValue(colElt->borderAdjoiningCellBefore(this), includeColor ? colElt->resolveColor(startColorProperty) : Color(), BCOLGROUP));
    677                 if (!result.exists())
    678                     return result;
    679             } else if (colElt->isTableColumn()) {
    680                 // Resolve the collapsing border against the col's border ignoring any 'span' as per HTML5.
    681                 result = chooseBorder(result, CollapsedBorderValue(colElt->borderAdjoiningCellBefore(this), includeColor ? colElt->resolveColor(startColorProperty) : Color(), BCOL));
    682                 if (!result.exists())
    683                     return result;
    684                 // If we have a parent colgroup, resolve the border only if it is adjacent to the cell.
    685                 if (RenderTableCol* enclosingColumnGroup = colElt->enclosingColumnGroupIfAdjacentBefore()) {
    686                     result = chooseBorder(result, CollapsedBorderValue(enclosingColumnGroup->borderAdjoiningCellStartBorder(this), includeColor ? enclosingColumnGroup->resolveColor(startColorProperty) : Color(), BCOLGROUP));
    687                     if (!result.exists())
    688                         return result;
    689                 }
    690             }
    691         }
    692     }
    693 
    694     if (endBorderAdjoinsTable) {
    695         // (7) The table's end border.
    696         result = chooseBorder(result, CollapsedBorderValue(table->tableEndBorderAdjoiningCell(this), includeColor ? table->resolveColor(endColorProperty) : Color(), BTABLE));
    697         if (!result.exists())
    698             return result;
    699     }
    700 
    701     return result;
    702 }
    703 
    704 CollapsedBorderValue RenderTableCell::collapsedBeforeBorder(IncludeBorderColorOrNot includeColor) const
    705 {
    706     CollapsedBorderValue result = computeCollapsedBeforeBorder(includeColor);
    707     if (includeColor)
    708         section()->setCachedCollapsedBorder(this, CBSBefore, result);
    709     return result;
    710 }
    711 
    712 CollapsedBorderValue RenderTableCell::computeCollapsedBeforeBorder(IncludeBorderColorOrNot includeColor) const
    713 {
    714     RenderTable* table = this->table();
    715 
    716     // For before border, we need to check, in order of precedence:
    717     // (1) Our before border.
    718     int beforeColorProperty = includeColor ? CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderBeforeColor, styleForCellFlow()->direction(), styleForCellFlow()->writingMode()) : 0;
    719     int afterColorProperty = includeColor ? CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderAfterColor, styleForCellFlow()->direction(), styleForCellFlow()->writingMode()) : 0;
    720     CollapsedBorderValue result = CollapsedBorderValue(style()->borderBefore(), includeColor ? resolveColor(beforeColorProperty) : Color(), BCELL);
    721 
    722     RenderTableCell* prevCell = table->cellAbove(this);
    723     if (prevCell) {
    724         // (2) A before cell's after border.
    725         result = chooseBorder(CollapsedBorderValue(prevCell->style()->borderAfter(), includeColor ? prevCell->resolveColor(afterColorProperty) : Color(), BCELL), result);
    726         if (!result.exists())
    727             return result;
    728     }
    729 
    730     // (3) Our row's before border.
    731     result = chooseBorder(result, CollapsedBorderValue(parent()->style()->borderBefore(), includeColor ? parent()->resolveColor(beforeColorProperty) : Color(), BROW));
    732     if (!result.exists())
    733         return result;
    734 
    735     // (4) The previous row's after border.
    736     if (prevCell) {
    737         RenderObject* prevRow = 0;
    738         if (prevCell->section() == section())
    739             prevRow = parent()->previousSibling();
    740         else
    741             prevRow = prevCell->section()->lastChild();
    742 
    743         if (prevRow) {
    744             result = chooseBorder(CollapsedBorderValue(prevRow->style()->borderAfter(), includeColor ? prevRow->resolveColor(afterColorProperty) : Color(), BROW), result);
    745             if (!result.exists())
    746                 return result;
    747         }
    748     }
    749 
    750     // Now check row groups.
    751     RenderTableSection* currSection = section();
    752     if (!rowIndex()) {
    753         // (5) Our row group's before border.
    754         result = chooseBorder(result, CollapsedBorderValue(currSection->style()->borderBefore(), includeColor ? currSection->resolveColor(beforeColorProperty) : Color(), BROWGROUP));
    755         if (!result.exists())
    756             return result;
    757 
    758         // (6) Previous row group's after border.
    759         currSection = table->sectionAbove(currSection, SkipEmptySections);
    760         if (currSection) {
    761             result = chooseBorder(CollapsedBorderValue(currSection->style()->borderAfter(), includeColor ? currSection->resolveColor(afterColorProperty) : Color(), BROWGROUP), result);
    762             if (!result.exists())
    763                 return result;
    764         }
    765     }
    766 
    767     if (!currSection) {
    768         // (8) Our column and column group's before borders.
    769         RenderTableCol* colElt = table->colElement(col());
    770         if (colElt) {
    771             result = chooseBorder(result, CollapsedBorderValue(colElt->style()->borderBefore(), includeColor ? colElt->resolveColor(beforeColorProperty) : Color(), BCOL));
    772             if (!result.exists())
    773                 return result;
    774             if (RenderTableCol* enclosingColumnGroup = colElt->enclosingColumnGroup()) {
    775                 result = chooseBorder(result, CollapsedBorderValue(enclosingColumnGroup->style()->borderBefore(), includeColor ? enclosingColumnGroup->resolveColor(beforeColorProperty) : Color(), BCOLGROUP));
    776                 if (!result.exists())
    777                     return result;
    778             }
    779         }
    780 
    781         // (9) The table's before border.
    782         result = chooseBorder(result, CollapsedBorderValue(table->style()->borderBefore(), includeColor ? table->resolveColor(beforeColorProperty) : Color(), BTABLE));
    783         if (!result.exists())
    784             return result;
    785     }
    786 
    787     return result;
    788 }
    789 
    790 CollapsedBorderValue RenderTableCell::collapsedAfterBorder(IncludeBorderColorOrNot includeColor) const
    791 {
    792     CollapsedBorderValue result = computeCollapsedAfterBorder(includeColor);
    793     if (includeColor)
    794         section()->setCachedCollapsedBorder(this, CBSAfter, result);
    795     return result;
    796 }
    797 
    798 CollapsedBorderValue RenderTableCell::computeCollapsedAfterBorder(IncludeBorderColorOrNot includeColor) const
    799 {
    800     RenderTable* table = this->table();
    801 
    802     // For after border, we need to check, in order of precedence:
    803     // (1) Our after border.
    804     int beforeColorProperty = includeColor ? CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderBeforeColor, styleForCellFlow()->direction(), styleForCellFlow()->writingMode()) : 0;
    805     int afterColorProperty = includeColor ? CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderAfterColor, styleForCellFlow()->direction(), styleForCellFlow()->writingMode()) : 0;
    806     CollapsedBorderValue result = CollapsedBorderValue(style()->borderAfter(), includeColor ? resolveColor(afterColorProperty) : Color(), BCELL);
    807 
    808     RenderTableCell* nextCell = table->cellBelow(this);
    809     if (nextCell) {
    810         // (2) An after cell's before border.
    811         result = chooseBorder(result, CollapsedBorderValue(nextCell->style()->borderBefore(), includeColor ? nextCell->resolveColor(beforeColorProperty) : Color(), BCELL));
    812         if (!result.exists())
    813             return result;
    814     }
    815 
    816     // (3) Our row's after border. (FIXME: Deal with rowspan!)
    817     result = chooseBorder(result, CollapsedBorderValue(parent()->style()->borderAfter(), includeColor ? parent()->resolveColor(afterColorProperty) : Color(), BROW));
    818     if (!result.exists())
    819         return result;
    820 
    821     // (4) The next row's before border.
    822     if (nextCell) {
    823         result = chooseBorder(result, CollapsedBorderValue(nextCell->parent()->style()->borderBefore(), includeColor ? nextCell->parent()->resolveColor(beforeColorProperty) : Color(), BROW));
    824         if (!result.exists())
    825             return result;
    826     }
    827 
    828     // Now check row groups.
    829     RenderTableSection* currSection = section();
    830     if (rowIndex() + rowSpan() >= currSection->numRows()) {
    831         // (5) Our row group's after border.
    832         result = chooseBorder(result, CollapsedBorderValue(currSection->style()->borderAfter(), includeColor ? currSection->resolveColor(afterColorProperty) : Color(), BROWGROUP));
    833         if (!result.exists())
    834             return result;
    835 
    836         // (6) Following row group's before border.
    837         currSection = table->sectionBelow(currSection, SkipEmptySections);
    838         if (currSection) {
    839             result = chooseBorder(result, CollapsedBorderValue(currSection->style()->borderBefore(), includeColor ? currSection->resolveColor(beforeColorProperty) : Color(), BROWGROUP));
    840             if (!result.exists())
    841                 return result;
    842         }
    843     }
    844 
    845     if (!currSection) {
    846         // (8) Our column and column group's after borders.
    847         RenderTableCol* colElt = table->colElement(col());
    848         if (colElt) {
    849             result = chooseBorder(result, CollapsedBorderValue(colElt->style()->borderAfter(), includeColor ? colElt->resolveColor(afterColorProperty) : Color(), BCOL));
    850             if (!result.exists()) return result;
    851             if (RenderTableCol* enclosingColumnGroup = colElt->enclosingColumnGroup()) {
    852                 result = chooseBorder(result, CollapsedBorderValue(enclosingColumnGroup->style()->borderAfter(), includeColor ? enclosingColumnGroup->resolveColor(afterColorProperty) : Color(), BCOLGROUP));
    853                 if (!result.exists())
    854                     return result;
    855             }
    856         }
    857 
    858         // (9) The table's after border.
    859         result = chooseBorder(result, CollapsedBorderValue(table->style()->borderAfter(), includeColor ? table->resolveColor(afterColorProperty) : Color(), BTABLE));
    860         if (!result.exists())
    861             return result;
    862     }
    863 
    864     return result;
    865 }
    866 
    867 inline CollapsedBorderValue RenderTableCell::cachedCollapsedLeftBorder(const RenderStyle* styleForCellFlow) const
    868 {
    869     if (styleForCellFlow->isHorizontalWritingMode())
    870         return styleForCellFlow->isLeftToRightDirection() ? section()->cachedCollapsedBorder(this, CBSStart) : section()->cachedCollapsedBorder(this, CBSEnd);
    871     return styleForCellFlow->isFlippedBlocksWritingMode() ? section()->cachedCollapsedBorder(this, CBSAfter) : section()->cachedCollapsedBorder(this, CBSBefore);
    872 }
    873 
    874 inline CollapsedBorderValue RenderTableCell::cachedCollapsedRightBorder(const RenderStyle* styleForCellFlow) const
    875 {
    876     if (styleForCellFlow->isHorizontalWritingMode())
    877         return styleForCellFlow->isLeftToRightDirection() ? section()->cachedCollapsedBorder(this, CBSEnd) : section()->cachedCollapsedBorder(this, CBSStart);
    878     return styleForCellFlow->isFlippedBlocksWritingMode() ? section()->cachedCollapsedBorder(this, CBSBefore) : section()->cachedCollapsedBorder(this, CBSAfter);
    879 }
    880 
    881 inline CollapsedBorderValue RenderTableCell::cachedCollapsedTopBorder(const RenderStyle* styleForCellFlow) const
    882 {
    883     if (styleForCellFlow->isHorizontalWritingMode())
    884         return styleForCellFlow->isFlippedBlocksWritingMode() ? section()->cachedCollapsedBorder(this, CBSAfter) : section()->cachedCollapsedBorder(this, CBSBefore);
    885     return styleForCellFlow->isLeftToRightDirection() ? section()->cachedCollapsedBorder(this, CBSStart) : section()->cachedCollapsedBorder(this, CBSEnd);
    886 }
    887 
    888 inline CollapsedBorderValue RenderTableCell::cachedCollapsedBottomBorder(const RenderStyle* styleForCellFlow) const
    889 {
    890     if (styleForCellFlow->isHorizontalWritingMode())
    891         return styleForCellFlow->isFlippedBlocksWritingMode() ? section()->cachedCollapsedBorder(this, CBSBefore) : section()->cachedCollapsedBorder(this, CBSAfter);
    892     return styleForCellFlow->isLeftToRightDirection() ? section()->cachedCollapsedBorder(this, CBSEnd) : section()->cachedCollapsedBorder(this, CBSStart);
    893 }
    894 
    895 int RenderTableCell::borderLeft() const
    896 {
    897     return table()->collapseBorders() ? borderHalfLeft(false) : RenderBlock::borderLeft();
    898 }
    899 
    900 int RenderTableCell::borderRight() const
    901 {
    902     return table()->collapseBorders() ? borderHalfRight(false) : RenderBlock::borderRight();
    903 }
    904 
    905 int RenderTableCell::borderTop() const
    906 {
    907     return table()->collapseBorders() ? borderHalfTop(false) : RenderBlock::borderTop();
    908 }
    909 
    910 int RenderTableCell::borderBottom() const
    911 {
    912     return table()->collapseBorders() ? borderHalfBottom(false) : RenderBlock::borderBottom();
    913 }
    914 
    915 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=46191, make the collapsed border drawing
    916 // work with different block flow values instead of being hard-coded to top-to-bottom.
    917 int RenderTableCell::borderStart() const
    918 {
    919     return table()->collapseBorders() ? borderHalfStart(false) : RenderBlock::borderStart();
    920 }
    921 
    922 int RenderTableCell::borderEnd() const
    923 {
    924     return table()->collapseBorders() ? borderHalfEnd(false) : RenderBlock::borderEnd();
    925 }
    926 
    927 int RenderTableCell::borderBefore() const
    928 {
    929     return table()->collapseBorders() ? borderHalfBefore(false) : RenderBlock::borderBefore();
    930 }
    931 
    932 int RenderTableCell::borderAfter() const
    933 {
    934     return table()->collapseBorders() ? borderHalfAfter(false) : RenderBlock::borderAfter();
    935 }
    936 
    937 int RenderTableCell::borderHalfLeft(bool outer) const
    938 {
    939     const RenderStyle* styleForCellFlow = this->styleForCellFlow();
    940     if (styleForCellFlow->isHorizontalWritingMode())
    941         return styleForCellFlow->isLeftToRightDirection() ? borderHalfStart(outer) : borderHalfEnd(outer);
    942     return styleForCellFlow->isFlippedBlocksWritingMode() ? borderHalfAfter(outer) : borderHalfBefore(outer);
    943 }
    944 
    945 int RenderTableCell::borderHalfRight(bool outer) const
    946 {
    947     const RenderStyle* styleForCellFlow = this->styleForCellFlow();
    948     if (styleForCellFlow->isHorizontalWritingMode())
    949         return styleForCellFlow->isLeftToRightDirection() ? borderHalfEnd(outer) : borderHalfStart(outer);
    950     return styleForCellFlow->isFlippedBlocksWritingMode() ? borderHalfBefore(outer) : borderHalfAfter(outer);
    951 }
    952 
    953 int RenderTableCell::borderHalfTop(bool outer) const
    954 {
    955     const RenderStyle* styleForCellFlow = this->styleForCellFlow();
    956     if (styleForCellFlow->isHorizontalWritingMode())
    957         return styleForCellFlow->isFlippedBlocksWritingMode() ? borderHalfAfter(outer) : borderHalfBefore(outer);
    958     return styleForCellFlow->isLeftToRightDirection() ? borderHalfStart(outer) : borderHalfEnd(outer);
    959 }
    960 
    961 int RenderTableCell::borderHalfBottom(bool outer) const
    962 {
    963     const RenderStyle* styleForCellFlow = this->styleForCellFlow();
    964     if (styleForCellFlow->isHorizontalWritingMode())
    965         return styleForCellFlow->isFlippedBlocksWritingMode() ? borderHalfBefore(outer) : borderHalfAfter(outer);
    966     return styleForCellFlow->isLeftToRightDirection() ? borderHalfEnd(outer) : borderHalfStart(outer);
    967 }
    968 
    969 int RenderTableCell::borderHalfStart(bool outer) const
    970 {
    971     CollapsedBorderValue border = collapsedStartBorder(DoNotIncludeBorderColor);
    972     if (border.exists())
    973         return (border.width() + ((styleForCellFlow()->isLeftToRightDirection() ^ outer) ? 1 : 0)) / 2; // Give the extra pixel to top and left.
    974     return 0;
    975 }
    976 
    977 int RenderTableCell::borderHalfEnd(bool outer) const
    978 {
    979     CollapsedBorderValue border = collapsedEndBorder(DoNotIncludeBorderColor);
    980     if (border.exists())
    981         return (border.width() + ((styleForCellFlow()->isLeftToRightDirection() ^ outer) ? 0 : 1)) / 2;
    982     return 0;
    983 }
    984 
    985 int RenderTableCell::borderHalfBefore(bool outer) const
    986 {
    987     CollapsedBorderValue border = collapsedBeforeBorder(DoNotIncludeBorderColor);
    988     if (border.exists())
    989         return (border.width() + ((styleForCellFlow()->isFlippedBlocksWritingMode() ^ outer) ? 0 : 1)) / 2; // Give the extra pixel to top and left.
    990     return 0;
    991 }
    992 
    993 int RenderTableCell::borderHalfAfter(bool outer) const
    994 {
    995     CollapsedBorderValue border = collapsedAfterBorder(DoNotIncludeBorderColor);
    996     if (border.exists())
    997         return (border.width() + ((styleForCellFlow()->isFlippedBlocksWritingMode() ^ outer) ? 1 : 0)) / 2;
    998     return 0;
    999 }
   1000 
   1001 void RenderTableCell::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
   1002 {
   1003     ASSERT(paintInfo.phase != PaintPhaseCollapsedTableBorders);
   1004     RenderBlock::paint(paintInfo, paintOffset);
   1005 }
   1006 
   1007 static EBorderStyle collapsedBorderStyle(EBorderStyle style)
   1008 {
   1009     if (style == OUTSET)
   1010         return GROOVE;
   1011     if (style == INSET)
   1012         return RIDGE;
   1013     return style;
   1014 }
   1015 
   1016 struct CollapsedBorder {
   1017     CollapsedBorderValue borderValue;
   1018     BoxSide side;
   1019     bool shouldPaint;
   1020     int x1;
   1021     int y1;
   1022     int x2;
   1023     int y2;
   1024     EBorderStyle style;
   1025 };
   1026 
   1027 class CollapsedBorders {
   1028 public:
   1029     CollapsedBorders()
   1030         : m_count(0)
   1031     {
   1032     }
   1033 
   1034     void addBorder(const CollapsedBorderValue& borderValue, BoxSide borderSide, bool shouldPaint,
   1035                    int x1, int y1, int x2, int y2, EBorderStyle borderStyle)
   1036     {
   1037         if (borderValue.exists() && shouldPaint) {
   1038             m_borders[m_count].borderValue = borderValue;
   1039             m_borders[m_count].side = borderSide;
   1040             m_borders[m_count].shouldPaint = shouldPaint;
   1041             m_borders[m_count].x1 = x1;
   1042             m_borders[m_count].x2 = x2;
   1043             m_borders[m_count].y1 = y1;
   1044             m_borders[m_count].y2 = y2;
   1045             m_borders[m_count].style = borderStyle;
   1046             m_count++;
   1047         }
   1048     }
   1049 
   1050     CollapsedBorder* nextBorder()
   1051     {
   1052         for (unsigned i = 0; i < m_count; i++) {
   1053             if (m_borders[i].borderValue.exists() && m_borders[i].shouldPaint) {
   1054                 m_borders[i].shouldPaint = false;
   1055                 return &m_borders[i];
   1056             }
   1057         }
   1058 
   1059         return 0;
   1060     }
   1061 
   1062     CollapsedBorder m_borders[4];
   1063     unsigned m_count;
   1064 };
   1065 
   1066 static void addBorderStyle(RenderTable::CollapsedBorderValues& borderValues,
   1067                            CollapsedBorderValue borderValue)
   1068 {
   1069     if (!borderValue.exists())
   1070         return;
   1071     size_t count = borderValues.size();
   1072     for (size_t i = 0; i < count; ++i)
   1073         if (borderValues[i].isSameIgnoringColor(borderValue))
   1074             return;
   1075     borderValues.append(borderValue);
   1076 }
   1077 
   1078 void RenderTableCell::collectBorderValues(RenderTable::CollapsedBorderValues& borderValues) const
   1079 {
   1080     addBorderStyle(borderValues, collapsedStartBorder());
   1081     addBorderStyle(borderValues, collapsedEndBorder());
   1082     addBorderStyle(borderValues, collapsedBeforeBorder());
   1083     addBorderStyle(borderValues, collapsedAfterBorder());
   1084 }
   1085 
   1086 static int compareBorderValuesForQSort(const void* pa, const void* pb)
   1087 {
   1088     const CollapsedBorderValue* a = static_cast<const CollapsedBorderValue*>(pa);
   1089     const CollapsedBorderValue* b = static_cast<const CollapsedBorderValue*>(pb);
   1090     if (a->isSameIgnoringColor(*b))
   1091         return 0;
   1092     return compareBorders(*a, *b);
   1093 }
   1094 
   1095 void RenderTableCell::sortBorderValues(RenderTable::CollapsedBorderValues& borderValues)
   1096 {
   1097     qsort(borderValues.data(), borderValues.size(), sizeof(CollapsedBorderValue),
   1098         compareBorderValuesForQSort);
   1099 }
   1100 
   1101 void RenderTableCell::paintCollapsedBorders(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
   1102 {
   1103     ASSERT(paintInfo.phase == PaintPhaseCollapsedTableBorders);
   1104 
   1105     if (!paintInfo.shouldPaintWithinRoot(this) || style()->visibility() != VISIBLE)
   1106         return;
   1107 
   1108     LayoutRect localRepaintRect = paintInfo.rect;
   1109     localRepaintRect.inflate(maximalOutlineSize(paintInfo.phase));
   1110 
   1111     LayoutRect paintRect = LayoutRect(paintOffset + location(), pixelSnappedSize());
   1112     if (paintRect.y() - table()->outerBorderTop() >= localRepaintRect.maxY())
   1113         return;
   1114 
   1115     if (paintRect.maxY() + table()->outerBorderBottom() <= localRepaintRect.y())
   1116         return;
   1117 
   1118     GraphicsContext* graphicsContext = paintInfo.context;
   1119     if (!table()->currentBorderValue() || graphicsContext->paintingDisabled())
   1120         return;
   1121 
   1122     const RenderStyle* styleForCellFlow = this->styleForCellFlow();
   1123     CollapsedBorderValue leftVal = cachedCollapsedLeftBorder(styleForCellFlow);
   1124     CollapsedBorderValue rightVal = cachedCollapsedRightBorder(styleForCellFlow);
   1125     CollapsedBorderValue topVal = cachedCollapsedTopBorder(styleForCellFlow);
   1126     CollapsedBorderValue bottomVal = cachedCollapsedBottomBorder(styleForCellFlow);
   1127 
   1128     // Adjust our x/y/width/height so that we paint the collapsed borders at the correct location.
   1129     int topWidth = topVal.width();
   1130     int bottomWidth = bottomVal.width();
   1131     int leftWidth = leftVal.width();
   1132     int rightWidth = rightVal.width();
   1133 
   1134     IntRect borderRect = pixelSnappedIntRect(paintRect.x() - leftWidth / 2,
   1135             paintRect.y() - topWidth / 2,
   1136             paintRect.width() + leftWidth / 2 + (rightWidth + 1) / 2,
   1137             paintRect.height() + topWidth / 2 + (bottomWidth + 1) / 2);
   1138 
   1139     EBorderStyle topStyle = collapsedBorderStyle(topVal.style());
   1140     EBorderStyle bottomStyle = collapsedBorderStyle(bottomVal.style());
   1141     EBorderStyle leftStyle = collapsedBorderStyle(leftVal.style());
   1142     EBorderStyle rightStyle = collapsedBorderStyle(rightVal.style());
   1143 
   1144     bool renderTop = topStyle > BHIDDEN && !topVal.isTransparent();
   1145     bool renderBottom = bottomStyle > BHIDDEN && !bottomVal.isTransparent();
   1146     bool renderLeft = leftStyle > BHIDDEN && !leftVal.isTransparent();
   1147     bool renderRight = rightStyle > BHIDDEN && !rightVal.isTransparent();
   1148 
   1149     // We never paint diagonals at the joins.  We simply let the border with the highest
   1150     // precedence paint on top of borders with lower precedence.
   1151     CollapsedBorders borders;
   1152     borders.addBorder(topVal, BSTop, renderTop, borderRect.x(), borderRect.y(), borderRect.maxX(), borderRect.y() + topWidth, topStyle);
   1153     borders.addBorder(bottomVal, BSBottom, renderBottom, borderRect.x(), borderRect.maxY() - bottomWidth, borderRect.maxX(), borderRect.maxY(), bottomStyle);
   1154     borders.addBorder(leftVal, BSLeft, renderLeft, borderRect.x(), borderRect.y(), borderRect.x() + leftWidth, borderRect.maxY(), leftStyle);
   1155     borders.addBorder(rightVal, BSRight, renderRight, borderRect.maxX() - rightWidth, borderRect.y(), borderRect.maxX(), borderRect.maxY(), rightStyle);
   1156 
   1157     bool antialias = shouldAntialiasLines(graphicsContext);
   1158 
   1159     for (CollapsedBorder* border = borders.nextBorder(); border; border = borders.nextBorder()) {
   1160         if (border->borderValue.isSameIgnoringColor(*table()->currentBorderValue())) {
   1161             drawLineForBoxSide(graphicsContext, border->x1, border->y1, border->x2, border->y2, border->side,
   1162                 resolveColor(border->borderValue.color()), border->style, 0, 0, antialias);
   1163         }
   1164     }
   1165 }
   1166 
   1167 void RenderTableCell::paintBackgroundsBehindCell(PaintInfo& paintInfo, const LayoutPoint& paintOffset, RenderObject* backgroundObject)
   1168 {
   1169     if (!paintInfo.shouldPaintWithinRoot(this))
   1170         return;
   1171 
   1172     if (!backgroundObject)
   1173         return;
   1174 
   1175     if (style()->visibility() != VISIBLE)
   1176         return;
   1177 
   1178     RenderTable* tableElt = table();
   1179     if (!tableElt->collapseBorders() && style()->emptyCells() == HIDE && !firstChild())
   1180         return;
   1181 
   1182     LayoutPoint adjustedPaintOffset = paintOffset;
   1183     if (backgroundObject != this)
   1184         adjustedPaintOffset.moveBy(location());
   1185 
   1186     Color c = backgroundObject->resolveColor(CSSPropertyBackgroundColor);
   1187     const FillLayer* bgLayer = backgroundObject->style()->backgroundLayers();
   1188 
   1189     if (bgLayer->hasImage() || c.isValid()) {
   1190         // We have to clip here because the background would paint
   1191         // on top of the borders otherwise.  This only matters for cells and rows.
   1192         bool shouldClip = backgroundObject->hasLayer() && (backgroundObject == this || backgroundObject == parent()) && tableElt->collapseBorders();
   1193         GraphicsContextStateSaver stateSaver(*paintInfo.context, shouldClip);
   1194         if (shouldClip) {
   1195             LayoutRect clipRect(adjustedPaintOffset.x() + borderLeft(), adjustedPaintOffset.y() + borderTop(),
   1196                 width() - borderLeft() - borderRight(), height() - borderTop() - borderBottom());
   1197             paintInfo.context->clip(clipRect);
   1198         }
   1199         paintFillLayers(paintInfo, c, bgLayer, LayoutRect(adjustedPaintOffset, pixelSnappedSize()), BackgroundBleedNone, CompositeSourceOver, backgroundObject);
   1200     }
   1201 }
   1202 
   1203 void RenderTableCell::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
   1204 {
   1205     if (!paintInfo.shouldPaintWithinRoot(this))
   1206         return;
   1207 
   1208     RenderTable* tableElt = table();
   1209     if (!tableElt->collapseBorders() && style()->emptyCells() == HIDE && !firstChild())
   1210         return;
   1211 
   1212     LayoutRect paintRect = LayoutRect(paintOffset, pixelSnappedSize());
   1213     paintBoxShadow(paintInfo, paintRect, style(), Normal);
   1214 
   1215     // Paint our cell background.
   1216     paintBackgroundsBehindCell(paintInfo, paintOffset, this);
   1217 
   1218     paintBoxShadow(paintInfo, paintRect, style(), Inset);
   1219 
   1220     if (!style()->hasBorder() || tableElt->collapseBorders())
   1221         return;
   1222 
   1223     paintBorder(paintInfo, paintRect, style());
   1224 }
   1225 
   1226 void RenderTableCell::paintMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
   1227 {
   1228     if (style()->visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask)
   1229         return;
   1230 
   1231     RenderTable* tableElt = table();
   1232     if (!tableElt->collapseBorders() && style()->emptyCells() == HIDE && !firstChild())
   1233         return;
   1234 
   1235     paintMaskImages(paintInfo, LayoutRect(paintOffset, pixelSnappedSize()));
   1236 }
   1237 
   1238 bool RenderTableCell::boxShadowShouldBeAppliedToBackground(BackgroundBleedAvoidance, InlineFlowBox*) const
   1239 {
   1240     return false;
   1241 }
   1242 
   1243 void RenderTableCell::scrollbarsChanged(bool horizontalScrollbarChanged, bool verticalScrollbarChanged)
   1244 {
   1245     LayoutUnit scrollbarHeight = scrollbarLogicalHeight();
   1246     if (!scrollbarHeight)
   1247         return; // Not sure if we should be doing something when a scrollbar goes away or not.
   1248 
   1249     // We only care if the scrollbar that affects our intrinsic padding has been added.
   1250     if ((isHorizontalWritingMode() && !horizontalScrollbarChanged) ||
   1251         (!isHorizontalWritingMode() && !verticalScrollbarChanged))
   1252         return;
   1253 
   1254     // Shrink our intrinsic padding as much as possible to accommodate the scrollbar.
   1255     if (style()->verticalAlign() == MIDDLE) {
   1256         LayoutUnit totalHeight = logicalHeight();
   1257         LayoutUnit heightWithoutIntrinsicPadding = totalHeight - intrinsicPaddingBefore() - intrinsicPaddingAfter();
   1258         totalHeight -= scrollbarHeight;
   1259         LayoutUnit newBeforePadding = (totalHeight - heightWithoutIntrinsicPadding) / 2;
   1260         LayoutUnit newAfterPadding = totalHeight - heightWithoutIntrinsicPadding - newBeforePadding;
   1261         setIntrinsicPaddingBefore(newBeforePadding);
   1262         setIntrinsicPaddingAfter(newAfterPadding);
   1263     } else
   1264         setIntrinsicPaddingAfter(intrinsicPaddingAfter() - scrollbarHeight);
   1265 }
   1266 
   1267 RenderTableCell* RenderTableCell::createAnonymous(Document* document)
   1268 {
   1269     RenderTableCell* renderer = new RenderTableCell(0);
   1270     renderer->setDocumentForAnonymous(document);
   1271     return renderer;
   1272 }
   1273 
   1274 RenderTableCell* RenderTableCell::createAnonymousWithParentRenderer(const RenderObject* parent)
   1275 {
   1276     RenderTableCell* newCell = RenderTableCell::createAnonymous(&parent->document());
   1277     RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parent->style(), TABLE_CELL);
   1278     newCell->setStyle(newStyle.release());
   1279     return newCell;
   1280 }
   1281 
   1282 } // namespace WebCore
   1283