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 "RenderTableCell.h"
     27 
     28 #include "CollapsedBorderValue.h"
     29 #include "FloatQuad.h"
     30 #include "GraphicsContext.h"
     31 #include "HTMLNames.h"
     32 #include "HTMLTableCellElement.h"
     33 #include "PaintInfo.h"
     34 #include "RenderTableCol.h"
     35 #include "RenderView.h"
     36 #include "TransformState.h"
     37 
     38 #ifdef ANDROID_LAYOUT
     39 #include "Document.h"
     40 #include "Settings.h"
     41 #endif
     42 
     43 using namespace std;
     44 
     45 namespace WebCore {
     46 
     47 using namespace HTMLNames;
     48 
     49 RenderTableCell::RenderTableCell(Node* node)
     50     : RenderBlock(node)
     51     , m_row(-1)
     52     , m_column(-1)
     53     , m_rowSpan(1)
     54     , m_columnSpan(1)
     55     , m_cellWidthChanged(false)
     56     , m_intrinsicPaddingBefore(0)
     57     , m_intrinsicPaddingAfter(0)
     58 {
     59     updateFromElement();
     60 }
     61 
     62 void RenderTableCell::destroy()
     63 {
     64     RenderTableSection* recalcSection = parent() ? section() : 0;
     65 
     66     RenderBlock::destroy();
     67 
     68     if (recalcSection)
     69         recalcSection->setNeedsCellRecalc();
     70 }
     71 
     72 void RenderTableCell::updateFromElement()
     73 {
     74     Node* n = node();
     75     if (n && (n->hasTagName(tdTag) || n->hasTagName(thTag))) {
     76         HTMLTableCellElement* tc = static_cast<HTMLTableCellElement*>(n);
     77         int oldRSpan = m_rowSpan;
     78         int oldCSpan = m_columnSpan;
     79 
     80         m_columnSpan = tc->colSpan();
     81         m_rowSpan = tc->rowSpan();
     82         if ((oldRSpan != m_rowSpan || oldCSpan != m_columnSpan) && style() && parent()) {
     83             setNeedsLayoutAndPrefWidthsRecalc();
     84             if (section())
     85                 section()->setNeedsCellRecalc();
     86         }
     87     }
     88 }
     89 
     90 Length RenderTableCell::styleOrColLogicalWidth() const
     91 {
     92     Length w = style()->logicalWidth();
     93     if (!w.isAuto())
     94         return w;
     95 
     96     if (RenderTableCol* tableCol = table()->colElement(col())) {
     97         int colSpanCount = colSpan();
     98 
     99         Length colWidthSum = Length(0, Fixed);
    100         for (int i = 1; i <= colSpanCount; i++) {
    101             Length colWidth = tableCol->style()->logicalWidth();
    102 
    103             // Percentage value should be returned only for colSpan == 1.
    104             // Otherwise we return original width for the cell.
    105             if (!colWidth.isFixed()) {
    106                 if (colSpanCount > 1)
    107                     return w;
    108                 return colWidth;
    109             }
    110 
    111             colWidthSum = Length(colWidthSum.value() + colWidth.value(), Fixed);
    112 
    113             tableCol = table()->nextColElement(tableCol);
    114             // If no next <col> tag found for the span we just return what we have for now.
    115             if (!tableCol)
    116                 break;
    117         }
    118 
    119         // Column widths specified on <col> apply to the border box of the cell.
    120         // Percentages don't need to be handled since they're always treated this way (even when specified on the cells).
    121         // See Bugzilla bug 8126 for details.
    122         if (colWidthSum.isFixed() && colWidthSum.value() > 0)
    123             colWidthSum = Length(max(0, colWidthSum.value() - borderAndPaddingLogicalWidth()), Fixed);
    124         return colWidthSum;
    125     }
    126 
    127     return w;
    128 }
    129 
    130 void RenderTableCell::computePreferredLogicalWidths()
    131 {
    132     // 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
    133     // cells are added, but relayout can cause the cells to be freed, leaving stale pointers in the sections'
    134     // grids.  We must refresh those grids before the child cells try to use them.
    135     table()->recalcSectionsIfNeeded();
    136 
    137     RenderBlock::computePreferredLogicalWidths();
    138     if (node() && style()->autoWrap()) {
    139         // See if nowrap was set.
    140         Length w = styleOrColLogicalWidth();
    141         String nowrap = static_cast<Element*>(node())->getAttribute(nowrapAttr);
    142         if (!nowrap.isNull() && w.isFixed())
    143             // Nowrap is set, but we didn't actually use it because of the
    144             // fixed width set on the cell.  Even so, it is a WinIE/Moz trait
    145             // to make the minwidth of the cell into the fixed width.  They do this
    146             // even in strict mode, so do not make this a quirk.  Affected the top
    147             // of hiptop.com.
    148             m_minPreferredLogicalWidth = max(w.value(), m_minPreferredLogicalWidth);
    149     }
    150 }
    151 
    152 void RenderTableCell::computeLogicalWidth()
    153 {
    154 #ifdef ANDROID_LAYOUT
    155     if (view()->frameView())
    156         setVisibleWidth(view()->frameView()->textWrapWidth());
    157 #endif
    158 }
    159 
    160 void RenderTableCell::updateLogicalWidth(int w)
    161 {
    162     if (w == logicalWidth())
    163         return;
    164 
    165     setLogicalWidth(w);
    166     setCellWidthChanged(true);
    167 }
    168 
    169 void RenderTableCell::layout()
    170 {
    171     layoutBlock(cellWidthChanged());
    172     setCellWidthChanged(false);
    173 }
    174 
    175 int RenderTableCell::paddingTop(bool includeIntrinsicPadding) const
    176 {
    177     int result = RenderBlock::paddingTop();
    178     if (!includeIntrinsicPadding || !isHorizontalWritingMode())
    179         return result;
    180     return result + (style()->writingMode() == TopToBottomWritingMode ? intrinsicPaddingBefore() : intrinsicPaddingAfter());
    181 }
    182 
    183 int RenderTableCell::paddingBottom(bool includeIntrinsicPadding) const
    184 {
    185     int result = RenderBlock::paddingBottom();
    186     if (!includeIntrinsicPadding || !isHorizontalWritingMode())
    187         return result;
    188     return result + (style()->writingMode() == TopToBottomWritingMode ? intrinsicPaddingAfter() : intrinsicPaddingBefore());
    189 }
    190 
    191 int RenderTableCell::paddingLeft(bool includeIntrinsicPadding) const
    192 {
    193     int result = RenderBlock::paddingLeft();
    194     if (!includeIntrinsicPadding || isHorizontalWritingMode())
    195         return result;
    196     return result + (style()->writingMode() == LeftToRightWritingMode ? intrinsicPaddingBefore() : intrinsicPaddingAfter());
    197 
    198 }
    199 
    200 int RenderTableCell::paddingRight(bool includeIntrinsicPadding) const
    201 {
    202     int result = RenderBlock::paddingRight();
    203     if (!includeIntrinsicPadding || isHorizontalWritingMode())
    204         return result;
    205     return result + (style()->writingMode() == LeftToRightWritingMode ? intrinsicPaddingAfter() : intrinsicPaddingBefore());
    206 }
    207 
    208 int RenderTableCell::paddingBefore(bool includeIntrinsicPadding) const
    209 {
    210     int result = RenderBlock::paddingBefore();
    211     if (!includeIntrinsicPadding)
    212         return result;
    213     return result + intrinsicPaddingBefore();
    214 }
    215 
    216 int RenderTableCell::paddingAfter(bool includeIntrinsicPadding) const
    217 {
    218     int result = RenderBlock::paddingAfter();
    219     if (!includeIntrinsicPadding)
    220         return result;
    221     return result + intrinsicPaddingAfter();
    222 }
    223 
    224 void RenderTableCell::setOverrideSize(int size)
    225 {
    226     clearIntrinsicPadding();
    227     RenderBlock::setOverrideSize(size);
    228 }
    229 
    230 void RenderTableCell::setOverrideSizeFromRowHeight(int rowHeight)
    231 {
    232     clearIntrinsicPadding();
    233     RenderBlock::setOverrideSize(max(0, rowHeight - borderBefore() - paddingBefore() - borderAfter() - paddingAfter()));
    234 }
    235 
    236 IntSize RenderTableCell::offsetFromContainer(RenderObject* o, const IntPoint& point) const
    237 {
    238     ASSERT(o == container());
    239 
    240     IntSize offset = RenderBlock::offsetFromContainer(o, point);
    241     if (parent())
    242         offset.expand(-parentBox()->x(), -parentBox()->y());
    243 
    244     return offset;
    245 }
    246 
    247 IntRect RenderTableCell::clippedOverflowRectForRepaint(RenderBoxModelObject* repaintContainer)
    248 {
    249     // If the table grid is dirty, we cannot get reliable information about adjoining cells,
    250     // so we ignore outside borders. This should not be a problem because it means that
    251     // the table is going to recalculate the grid, relayout and repaint its current rect, which
    252     // includes any outside borders of this cell.
    253     if (!table()->collapseBorders() || table()->needsSectionRecalc())
    254         return RenderBlock::clippedOverflowRectForRepaint(repaintContainer);
    255 
    256     bool rtl = !table()->style()->isLeftToRightDirection();
    257     int outlineSize = style()->outlineSize();
    258     int left = max(borderHalfLeft(true), outlineSize);
    259     int right = max(borderHalfRight(true), outlineSize);
    260     int top = max(borderHalfTop(true), outlineSize);
    261     int bottom = max(borderHalfBottom(true), outlineSize);
    262     if ((left && !rtl) || (right && rtl)) {
    263         if (RenderTableCell* before = table()->cellBefore(this)) {
    264             top = max(top, before->borderHalfTop(true));
    265             bottom = max(bottom, before->borderHalfBottom(true));
    266         }
    267     }
    268     if ((left && rtl) || (right && !rtl)) {
    269         if (RenderTableCell* after = table()->cellAfter(this)) {
    270             top = max(top, after->borderHalfTop(true));
    271             bottom = max(bottom, after->borderHalfBottom(true));
    272         }
    273     }
    274     if (top) {
    275         if (RenderTableCell* above = table()->cellAbove(this)) {
    276             left = max(left, above->borderHalfLeft(true));
    277             right = max(right, above->borderHalfRight(true));
    278         }
    279     }
    280     if (bottom) {
    281         if (RenderTableCell* below = table()->cellBelow(this)) {
    282             left = max(left, below->borderHalfLeft(true));
    283             right = max(right, below->borderHalfRight(true));
    284         }
    285     }
    286     left = max(left, -minXVisualOverflow());
    287     top = max(top, -minYVisualOverflow());
    288     IntRect r(-left, - top, left + max(width() + right, maxXVisualOverflow()), top + max(height() + bottom, maxYVisualOverflow()));
    289 
    290     if (RenderView* v = view()) {
    291         // FIXME: layoutDelta needs to be applied in parts before/after transforms and
    292         // repaint containers. https://bugs.webkit.org/show_bug.cgi?id=23308
    293         r.move(v->layoutDelta());
    294     }
    295     computeRectForRepaint(repaintContainer, r);
    296     return r;
    297 }
    298 
    299 void RenderTableCell::computeRectForRepaint(RenderBoxModelObject* repaintContainer, IntRect& r, bool fixed)
    300 {
    301     if (repaintContainer == this)
    302         return;
    303     r.setY(r.y());
    304     RenderView* v = view();
    305     if ((!v || !v->layoutStateEnabled() || repaintContainer) && parent())
    306         r.move(-parentBox()->x(), -parentBox()->y()); // Rows are in the same coordinate space, so don't add their offset in.
    307     RenderBlock::computeRectForRepaint(repaintContainer, r, fixed);
    308 }
    309 
    310 int RenderTableCell::cellBaselinePosition() const
    311 {
    312     // <http://www.w3.org/TR/2007/CR-CSS21-20070719/tables.html#height-layout>: The baseline of a cell is the baseline of
    313     // the first in-flow line box in the cell, or the first in-flow table-row in the cell, whichever comes first. If there
    314     // is no such line box or table-row, the baseline is the bottom of content edge of the cell box.
    315     int firstLineBaseline = firstLineBoxBaseline();
    316     if (firstLineBaseline != -1)
    317         return firstLineBaseline;
    318     return paddingBefore() + borderBefore() + contentLogicalHeight();
    319 }
    320 
    321 void RenderTableCell::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
    322 {
    323     if (parent() && section() && style() && style()->height() != newStyle->height())
    324         section()->setNeedsCellRecalc();
    325 
    326     ASSERT(newStyle->display() == TABLE_CELL);
    327 
    328     RenderBlock::styleWillChange(diff, newStyle);
    329 }
    330 
    331 void RenderTableCell::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
    332 {
    333     RenderBlock::styleDidChange(diff, oldStyle);
    334     setHasBoxDecorations(true);
    335 }
    336 
    337 // The following rules apply for resolving conflicts and figuring out which border
    338 // to use.
    339 // (1) Borders with the 'border-style' of 'hidden' take precedence over all other conflicting
    340 // borders. Any border with this value suppresses all borders at this location.
    341 // (2) Borders with a style of 'none' have the lowest priority. Only if the border properties of all
    342 // the elements meeting at this edge are 'none' will the border be omitted (but note that 'none' is
    343 // the default value for the border style.)
    344 // (3) If none of the styles are 'hidden' and at least one of them is not 'none', then narrow borders
    345 // are discarded in favor of wider ones. If several have the same 'border-width' then styles are preferred
    346 // in this order: 'double', 'solid', 'dashed', 'dotted', 'ridge', 'outset', 'groove', and the lowest: 'inset'.
    347 // (4) If border styles differ only in color, then a style set on a cell wins over one on a row,
    348 // which wins over a row group, column, column group and, lastly, table. It is undefined which color
    349 // is used when two elements of the same type disagree.
    350 static int compareBorders(const CollapsedBorderValue& border1, const CollapsedBorderValue& border2)
    351 {
    352     // Sanity check the values passed in. The null border have lowest priority.
    353     if (!border2.exists()) {
    354         if (!border1.exists())
    355             return 0;
    356         return 1;
    357     }
    358     if (!border1.exists())
    359         return -1;
    360 
    361     // Rule #1 above.
    362     if (border2.style() == BHIDDEN) {
    363         if (border1.style() == BHIDDEN)
    364             return 0;
    365         return -1;
    366     }
    367     if (border1.style() == BHIDDEN)
    368         return 1;
    369 
    370     // Rule #2 above.  A style of 'none' has lowest priority and always loses to any other border.
    371     if (border2.style() == BNONE) {
    372         if (border1.style() == BNONE)
    373             return 0;
    374         return 1;
    375     }
    376     if (border1.style() == BNONE)
    377         return -1;
    378 
    379     // The first part of rule #3 above. Wider borders win.
    380     if (border1.width() != border2.width())
    381         return border1.width() < border2.width() ? -1 : 1;
    382 
    383     // The borders have equal width.  Sort by border style.
    384     if (border1.style() != border2.style())
    385         return border1.style() < border2.style() ? -1 : 1;
    386 
    387     // The border have the same width and style.  Rely on precedence (cell over row over row group, etc.)
    388     if (border1.precedence() == border2.precedence())
    389         return 0;
    390     return border1.precedence() < border2.precedence() ? -1 : 1;
    391 }
    392 
    393 static CollapsedBorderValue chooseBorder(const CollapsedBorderValue& border1, const CollapsedBorderValue& border2)
    394 {
    395     const CollapsedBorderValue& border = compareBorders(border1, border2) < 0 ? border2 : border1;
    396     return border.style() == BHIDDEN ? CollapsedBorderValue() : border;
    397 }
    398 
    399 CollapsedBorderValue RenderTableCell::collapsedStartBorder() const
    400 {
    401     RenderTable* table = this->table();
    402     bool isStartColumn = col() == 0;
    403 
    404     // For the start border, we need to check, in order of precedence:
    405     // (1) Our start border.
    406     int start = CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderStartColor, table->style()->direction(), table->style()->writingMode());
    407     int end = CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderEndColor, table->style()->direction(), table->style()->writingMode());
    408     CollapsedBorderValue result(&style()->borderStart(), style()->visitedDependentColor(start), BCELL);
    409 
    410     // (2) The end border of the preceding cell.
    411     if (RenderTableCell* prevCell = table->cellBefore(this)) {
    412         CollapsedBorderValue prevCellBorder = CollapsedBorderValue(&prevCell->style()->borderEnd(), prevCell->style()->visitedDependentColor(end), BCELL);
    413         result = chooseBorder(prevCellBorder, result);
    414         if (!result.exists())
    415             return result;
    416     } else if (isStartColumn) {
    417         // (3) Our row's start border.
    418         result = chooseBorder(result, CollapsedBorderValue(&parent()->style()->borderStart(), parent()->style()->visitedDependentColor(start), BROW));
    419         if (!result.exists())
    420             return result;
    421 
    422         // (4) Our row group's start border.
    423         result = chooseBorder(result, CollapsedBorderValue(&section()->style()->borderStart(), section()->style()->visitedDependentColor(start), BROWGROUP));
    424         if (!result.exists())
    425             return result;
    426     }
    427 
    428     // (5) Our column and column group's start borders.
    429     bool startColEdge;
    430     bool endColEdge;
    431     RenderTableCol* colElt = table->colElement(col(), &startColEdge, &endColEdge);
    432     if (colElt && startColEdge) {
    433         result = chooseBorder(result, CollapsedBorderValue(&colElt->style()->borderStart(), colElt->style()->visitedDependentColor(start), BCOL));
    434         if (!result.exists())
    435             return result;
    436         if (colElt->parent()->isTableCol() && !colElt->previousSibling()) {
    437             result = chooseBorder(result, CollapsedBorderValue(&colElt->parent()->style()->borderStart(), colElt->parent()->style()->visitedDependentColor(start), BCOLGROUP));
    438             if (!result.exists())
    439                 return result;
    440         }
    441     }
    442 
    443     // (6) The end border of the preceding column.
    444     if (!isStartColumn) {
    445         colElt = table->colElement(col() -1, &startColEdge, &endColEdge);
    446         if (colElt && endColEdge) {
    447             CollapsedBorderValue endBorder = CollapsedBorderValue(&colElt->style()->borderEnd(), colElt->style()->visitedDependentColor(end), BCOL);
    448             result = chooseBorder(endBorder, result);
    449             if (!result.exists())
    450                 return result;
    451         }
    452     } else {
    453         // (7) The table's start border.
    454         result = chooseBorder(result, CollapsedBorderValue(&table->style()->borderStart(), table->style()->visitedDependentColor(start), BTABLE));
    455         if (!result.exists())
    456             return result;
    457     }
    458 
    459     return result;
    460 }
    461 
    462 CollapsedBorderValue RenderTableCell::collapsedEndBorder() const
    463 {
    464     RenderTable* table = this->table();
    465     bool isEndColumn = table->colToEffCol(col() + colSpan() - 1) == table->numEffCols() - 1;
    466 
    467     // For end border, we need to check, in order of precedence:
    468     // (1) Our end border.
    469     int start = CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderStartColor, table->style()->direction(), table->style()->writingMode());
    470     int end = CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderEndColor, table->style()->direction(), table->style()->writingMode());
    471     CollapsedBorderValue result = CollapsedBorderValue(&style()->borderEnd(), style()->visitedDependentColor(end), BCELL);
    472 
    473     // (2) The start border of the following cell.
    474     if (!isEndColumn) {
    475         RenderTableCell* nextCell = table->cellAfter(this);
    476         if (nextCell && nextCell->style()) {
    477             CollapsedBorderValue startBorder = CollapsedBorderValue(&nextCell->style()->borderStart(), nextCell->style()->visitedDependentColor(start), BCELL);
    478             result = chooseBorder(result, startBorder);
    479             if (!result.exists())
    480                 return result;
    481         }
    482     } else {
    483         // (3) Our row's end border.
    484         result = chooseBorder(result, CollapsedBorderValue(&parent()->style()->borderEnd(), parent()->style()->visitedDependentColor(end), BROW));
    485         if (!result.exists())
    486             return result;
    487 
    488         // (4) Our row group's end border.
    489         result = chooseBorder(result, CollapsedBorderValue(&section()->style()->borderEnd(), section()->style()->visitedDependentColor(end), BROWGROUP));
    490         if (!result.exists())
    491             return result;
    492     }
    493 
    494     // (5) Our column and column group's end borders.
    495     bool startColEdge;
    496     bool endColEdge;
    497     RenderTableCol* colElt = table->colElement(col() + colSpan() - 1, &startColEdge, &endColEdge);
    498     if (colElt && endColEdge) {
    499         result = chooseBorder(result, CollapsedBorderValue(&colElt->style()->borderEnd(), colElt->style()->visitedDependentColor(end), BCOL));
    500         if (!result.exists())
    501             return result;
    502         if (colElt->parent()->isTableCol() && !colElt->nextSibling()) {
    503             result = chooseBorder(result, CollapsedBorderValue(&colElt->parent()->style()->borderEnd(), colElt->parent()->style()->visitedDependentColor(end), BCOLGROUP));
    504             if (!result.exists())
    505                 return result;
    506         }
    507     }
    508 
    509     // (6) The start border of the next column.
    510     if (!isEndColumn) {
    511         colElt = table->colElement(col() + colSpan(), &startColEdge, &endColEdge);
    512         if (colElt && startColEdge) {
    513             CollapsedBorderValue startBorder = CollapsedBorderValue(&colElt->style()->borderStart(), colElt->style()->visitedDependentColor(start), BCOL);
    514             result = chooseBorder(result, startBorder);
    515             if (!result.exists())
    516                 return result;
    517         }
    518     } else {
    519         // (7) The table's end border.
    520         result = chooseBorder(result, CollapsedBorderValue(&table->style()->borderEnd(), table->style()->visitedDependentColor(end), BTABLE));
    521         if (!result.exists())
    522             return result;
    523     }
    524 
    525     return result;
    526 }
    527 
    528 CollapsedBorderValue RenderTableCell::collapsedBeforeBorder() const
    529 {
    530     RenderTable* table = this->table();
    531 
    532     // For before border, we need to check, in order of precedence:
    533     // (1) Our before border.
    534     int before = CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderBeforeColor, table->style()->direction(), table->style()->writingMode());
    535     int after = CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderAfterColor, table->style()->direction(), table->style()->writingMode());
    536     CollapsedBorderValue result = CollapsedBorderValue(&style()->borderBefore(), style()->visitedDependentColor(before), BCELL);
    537 
    538     RenderTableCell* prevCell = table->cellAbove(this);
    539     if (prevCell) {
    540         // (2) A before cell's after border.
    541         result = chooseBorder(CollapsedBorderValue(&prevCell->style()->borderAfter(), prevCell->style()->visitedDependentColor(after), BCELL), result);
    542         if (!result.exists())
    543             return result;
    544     }
    545 
    546     // (3) Our row's before border.
    547     result = chooseBorder(result, CollapsedBorderValue(&parent()->style()->borderBefore(), parent()->style()->visitedDependentColor(before), BROW));
    548     if (!result.exists())
    549         return result;
    550 
    551     // (4) The previous row's after border.
    552     if (prevCell) {
    553         RenderObject* prevRow = 0;
    554         if (prevCell->section() == section())
    555             prevRow = parent()->previousSibling();
    556         else
    557             prevRow = prevCell->section()->lastChild();
    558 
    559         if (prevRow) {
    560             result = chooseBorder(CollapsedBorderValue(&prevRow->style()->borderAfter(), prevRow->style()->visitedDependentColor(after), BROW), result);
    561             if (!result.exists())
    562                 return result;
    563         }
    564     }
    565 
    566     // Now check row groups.
    567     RenderTableSection* currSection = section();
    568     if (!row()) {
    569         // (5) Our row group's before border.
    570         result = chooseBorder(result, CollapsedBorderValue(&currSection->style()->borderBefore(), currSection->style()->visitedDependentColor(before), BROWGROUP));
    571         if (!result.exists())
    572             return result;
    573 
    574         // (6) Previous row group's after border.
    575         currSection = table->sectionAbove(currSection);
    576         if (currSection) {
    577             result = chooseBorder(CollapsedBorderValue(&currSection->style()->borderAfter(), currSection->style()->visitedDependentColor(after), BROWGROUP), result);
    578             if (!result.exists())
    579                 return result;
    580         }
    581     }
    582 
    583     if (!currSection) {
    584         // (8) Our column and column group's before borders.
    585         RenderTableCol* colElt = table->colElement(col());
    586         if (colElt) {
    587             result = chooseBorder(result, CollapsedBorderValue(&colElt->style()->borderBefore(), colElt->style()->visitedDependentColor(before), BCOL));
    588             if (!result.exists())
    589                 return result;
    590             if (colElt->parent()->isTableCol()) {
    591                 result = chooseBorder(result, CollapsedBorderValue(&colElt->parent()->style()->borderBefore(), colElt->parent()->style()->visitedDependentColor(before), BCOLGROUP));
    592                 if (!result.exists())
    593                     return result;
    594             }
    595         }
    596 
    597         // (9) The table's before border.
    598         result = chooseBorder(result, CollapsedBorderValue(&table->style()->borderBefore(), table->style()->visitedDependentColor(before), BTABLE));
    599         if (!result.exists())
    600             return result;
    601     }
    602 
    603     return result;
    604 }
    605 
    606 CollapsedBorderValue RenderTableCell::collapsedAfterBorder() const
    607 {
    608     RenderTable* table = this->table();
    609 
    610     // For after border, we need to check, in order of precedence:
    611     // (1) Our after border.
    612     int before = CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderBeforeColor, table->style()->direction(), table->style()->writingMode());
    613     int after = CSSProperty::resolveDirectionAwareProperty(CSSPropertyWebkitBorderAfterColor, table->style()->direction(), table->style()->writingMode());
    614     CollapsedBorderValue result = CollapsedBorderValue(&style()->borderAfter(), style()->visitedDependentColor(after), BCELL);
    615 
    616     RenderTableCell* nextCell = table->cellBelow(this);
    617     if (nextCell) {
    618         // (2) An after cell's before border.
    619         result = chooseBorder(result, CollapsedBorderValue(&nextCell->style()->borderBefore(), nextCell->style()->visitedDependentColor(before), BCELL));
    620         if (!result.exists())
    621             return result;
    622     }
    623 
    624     // (3) Our row's after border. (FIXME: Deal with rowspan!)
    625     result = chooseBorder(result, CollapsedBorderValue(&parent()->style()->borderAfter(), parent()->style()->visitedDependentColor(after), BROW));
    626     if (!result.exists())
    627         return result;
    628 
    629     // (4) The next row's before border.
    630     if (nextCell) {
    631         result = chooseBorder(result, CollapsedBorderValue(&nextCell->parent()->style()->borderBefore(), nextCell->parent()->style()->visitedDependentColor(before), BROW));
    632         if (!result.exists())
    633             return result;
    634     }
    635 
    636     // Now check row groups.
    637     RenderTableSection* currSection = section();
    638     if (row() + rowSpan() >= currSection->numRows()) {
    639         // (5) Our row group's after border.
    640         result = chooseBorder(result, CollapsedBorderValue(&currSection->style()->borderAfter(), currSection->style()->visitedDependentColor(after), BROWGROUP));
    641         if (!result.exists())
    642             return result;
    643 
    644         // (6) Following row group's before border.
    645         currSection = table->sectionBelow(currSection);
    646         if (currSection) {
    647             result = chooseBorder(result, CollapsedBorderValue(&currSection->style()->borderBefore(), currSection->style()->visitedDependentColor(before), BROWGROUP));
    648             if (!result.exists())
    649                 return result;
    650         }
    651     }
    652 
    653     if (!currSection) {
    654         // (8) Our column and column group's after borders.
    655         RenderTableCol* colElt = table->colElement(col());
    656         if (colElt) {
    657             result = chooseBorder(result, CollapsedBorderValue(&colElt->style()->borderAfter(), colElt->style()->visitedDependentColor(after), BCOL));
    658             if (!result.exists()) return result;
    659             if (colElt->parent()->isTableCol()) {
    660                 result = chooseBorder(result, CollapsedBorderValue(&colElt->parent()->style()->borderAfter(), colElt->parent()->style()->visitedDependentColor(after), BCOLGROUP));
    661                 if (!result.exists())
    662                     return result;
    663             }
    664         }
    665 
    666         // (9) The table's after border.
    667         result = chooseBorder(result, CollapsedBorderValue(&table->style()->borderAfter(), table->style()->visitedDependentColor(after), BTABLE));
    668         if (!result.exists())
    669             return result;
    670     }
    671 
    672     return result;
    673 }
    674 
    675 CollapsedBorderValue RenderTableCell::collapsedLeftBorder() const
    676 {
    677     RenderStyle* tableStyle = table()->style();
    678     if (tableStyle->isHorizontalWritingMode())
    679         return tableStyle->isLeftToRightDirection() ? collapsedStartBorder() : collapsedEndBorder();
    680     return tableStyle->isFlippedBlocksWritingMode() ? collapsedAfterBorder() : collapsedBeforeBorder();
    681 }
    682 
    683 CollapsedBorderValue RenderTableCell::collapsedRightBorder() const
    684 {
    685     RenderStyle* tableStyle = table()->style();
    686     if (tableStyle->isHorizontalWritingMode())
    687         return tableStyle->isLeftToRightDirection() ? collapsedEndBorder() : collapsedStartBorder();
    688     return tableStyle->isFlippedBlocksWritingMode() ? collapsedBeforeBorder() : collapsedAfterBorder();
    689 }
    690 
    691 CollapsedBorderValue RenderTableCell::collapsedTopBorder() const
    692 {
    693     RenderStyle* tableStyle = table()->style();
    694     if (tableStyle->isHorizontalWritingMode())
    695         return tableStyle->isFlippedBlocksWritingMode() ? collapsedAfterBorder() : collapsedBeforeBorder();
    696     return tableStyle->isLeftToRightDirection() ? collapsedStartBorder() : collapsedEndBorder();
    697 }
    698 
    699 CollapsedBorderValue RenderTableCell::collapsedBottomBorder() const
    700 {
    701     RenderStyle* tableStyle = table()->style();
    702     if (tableStyle->isHorizontalWritingMode())
    703         return tableStyle->isFlippedBlocksWritingMode() ? collapsedBeforeBorder() : collapsedAfterBorder();
    704     return tableStyle->isLeftToRightDirection() ? collapsedEndBorder() : collapsedStartBorder();
    705 }
    706 
    707 int RenderTableCell::borderLeft() const
    708 {
    709     return table()->collapseBorders() ? borderHalfLeft(false) : RenderBlock::borderLeft();
    710 }
    711 
    712 int RenderTableCell::borderRight() const
    713 {
    714     return table()->collapseBorders() ? borderHalfRight(false) : RenderBlock::borderRight();
    715 }
    716 
    717 int RenderTableCell::borderTop() const
    718 {
    719     return table()->collapseBorders() ? borderHalfTop(false) : RenderBlock::borderTop();
    720 }
    721 
    722 int RenderTableCell::borderBottom() const
    723 {
    724     return table()->collapseBorders() ? borderHalfBottom(false) : RenderBlock::borderBottom();
    725 }
    726 
    727 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=46191, make the collapsed border drawing
    728 // work with different block flow values instead of being hard-coded to top-to-bottom.
    729 int RenderTableCell::borderStart() const
    730 {
    731     return table()->collapseBorders() ? borderHalfStart(false) : RenderBlock::borderStart();
    732 }
    733 
    734 int RenderTableCell::borderEnd() const
    735 {
    736     return table()->collapseBorders() ? borderHalfEnd(false) : RenderBlock::borderEnd();
    737 }
    738 
    739 int RenderTableCell::borderBefore() const
    740 {
    741     return table()->collapseBorders() ? borderHalfBefore(false) : RenderBlock::borderBefore();
    742 }
    743 
    744 int RenderTableCell::borderAfter() const
    745 {
    746     return table()->collapseBorders() ? borderHalfAfter(false) : RenderBlock::borderAfter();
    747 }
    748 
    749 int RenderTableCell::borderHalfLeft(bool outer) const
    750 {
    751     RenderStyle* tableStyle = table()->style();
    752     if (tableStyle->isHorizontalWritingMode())
    753         return tableStyle->isLeftToRightDirection() ? borderHalfStart(outer) : borderHalfEnd(outer);
    754     return tableStyle->isFlippedBlocksWritingMode() ? borderHalfAfter(outer) : borderHalfBefore(outer);
    755 }
    756 
    757 int RenderTableCell::borderHalfRight(bool outer) const
    758 {
    759     RenderStyle* tableStyle = table()->style();
    760     if (tableStyle->isHorizontalWritingMode())
    761         return tableStyle->isLeftToRightDirection() ? borderHalfEnd(outer) : borderHalfStart(outer);
    762     return tableStyle->isFlippedBlocksWritingMode() ? borderHalfBefore(outer) : borderHalfAfter(outer);
    763 }
    764 
    765 int RenderTableCell::borderHalfTop(bool outer) const
    766 {
    767     RenderStyle* tableStyle = table()->style();
    768     if (tableStyle->isHorizontalWritingMode())
    769         return tableStyle->isFlippedBlocksWritingMode() ? borderHalfAfter(outer) : borderHalfBefore(outer);
    770     return tableStyle->isLeftToRightDirection() ? borderHalfStart(outer) : borderHalfEnd(outer);
    771 }
    772 
    773 int RenderTableCell::borderHalfBottom(bool outer) const
    774 {
    775     RenderStyle* tableStyle = table()->style();
    776     if (tableStyle->isHorizontalWritingMode())
    777         return tableStyle->isFlippedBlocksWritingMode() ? borderHalfBefore(outer) : borderHalfAfter(outer);
    778     return tableStyle->isLeftToRightDirection() ? borderHalfEnd(outer) : borderHalfStart(outer);
    779 }
    780 
    781 int RenderTableCell::borderHalfStart(bool outer) const
    782 {
    783     CollapsedBorderValue border = collapsedStartBorder();
    784     if (border.exists())
    785         return (border.width() + ((table()->style()->isLeftToRightDirection() ^ outer) ? 1 : 0)) / 2; // Give the extra pixel to top and left.
    786     return 0;
    787 }
    788 
    789 int RenderTableCell::borderHalfEnd(bool outer) const
    790 {
    791     CollapsedBorderValue border = collapsedEndBorder();
    792     if (border.exists())
    793         return (border.width() + ((table()->style()->isLeftToRightDirection() ^ outer) ? 0 : 1)) / 2;
    794     return 0;
    795 }
    796 
    797 int RenderTableCell::borderHalfBefore(bool outer) const
    798 {
    799     CollapsedBorderValue border = collapsedBeforeBorder();
    800     if (border.exists())
    801         return (border.width() + ((table()->style()->isFlippedBlocksWritingMode() ^ outer) ? 0 : 1)) / 2; // Give the extra pixel to top and left.
    802     return 0;
    803 }
    804 
    805 int RenderTableCell::borderHalfAfter(bool outer) const
    806 {
    807     CollapsedBorderValue border = collapsedAfterBorder();
    808     if (border.exists())
    809         return (border.width() + ((table()->style()->isFlippedBlocksWritingMode() ^ outer) ? 1 : 0)) / 2;
    810     return 0;
    811 }
    812 
    813 void RenderTableCell::paint(PaintInfo& paintInfo, int tx, int ty)
    814 {
    815     if (paintInfo.phase == PaintPhaseCollapsedTableBorders && style()->visibility() == VISIBLE) {
    816         if (!paintInfo.shouldPaintWithinRoot(this))
    817             return;
    818 
    819         tx += x();
    820         ty += y();
    821         int os = 2 * maximalOutlineSize(paintInfo.phase);
    822         if (ty - table()->outerBorderTop() < paintInfo.rect.maxY() + os
    823             && ty + height() + table()->outerBorderBottom() > paintInfo.rect.y() - os)
    824             paintCollapsedBorder(paintInfo.context, tx, ty, width(), height());
    825         return;
    826     }
    827 
    828     RenderBlock::paint(paintInfo, tx, ty);
    829 }
    830 
    831 static EBorderStyle collapsedBorderStyle(EBorderStyle style)
    832 {
    833     if (style == OUTSET)
    834         return GROOVE;
    835     if (style == INSET)
    836         return RIDGE;
    837     return style;
    838 }
    839 
    840 struct CollapsedBorder {
    841     CollapsedBorderValue borderValue;
    842     BoxSide side;
    843     bool shouldPaint;
    844     int x1;
    845     int y1;
    846     int x2;
    847     int y2;
    848     EBorderStyle style;
    849 };
    850 
    851 class CollapsedBorders {
    852 public:
    853     CollapsedBorders()
    854         : m_count(0)
    855     {
    856     }
    857 
    858     void addBorder(const CollapsedBorderValue& borderValue, BoxSide borderSide, bool shouldPaint,
    859                    int x1, int y1, int x2, int y2, EBorderStyle borderStyle)
    860     {
    861         if (borderValue.exists() && shouldPaint) {
    862             m_borders[m_count].borderValue = borderValue;
    863             m_borders[m_count].side = borderSide;
    864             m_borders[m_count].shouldPaint = shouldPaint;
    865             m_borders[m_count].x1 = x1;
    866             m_borders[m_count].x2 = x2;
    867             m_borders[m_count].y1 = y1;
    868             m_borders[m_count].y2 = y2;
    869             m_borders[m_count].style = borderStyle;
    870             m_count++;
    871         }
    872     }
    873 
    874     CollapsedBorder* nextBorder()
    875     {
    876         for (int i = 0; i < m_count; i++) {
    877             if (m_borders[i].borderValue.exists() && m_borders[i].shouldPaint) {
    878                 m_borders[i].shouldPaint = false;
    879                 return &m_borders[i];
    880             }
    881         }
    882 
    883         return 0;
    884     }
    885 
    886     CollapsedBorder m_borders[4];
    887     int m_count;
    888 };
    889 
    890 static void addBorderStyle(RenderTableCell::CollapsedBorderStyles& borderStyles, CollapsedBorderValue borderValue)
    891 {
    892     if (!borderValue.exists())
    893         return;
    894     size_t count = borderStyles.size();
    895     for (size_t i = 0; i < count; ++i)
    896         if (borderStyles[i] == borderValue)
    897             return;
    898     borderStyles.append(borderValue);
    899 }
    900 
    901 void RenderTableCell::collectBorderStyles(CollapsedBorderStyles& borderStyles) const
    902 {
    903     addBorderStyle(borderStyles, collapsedStartBorder());
    904     addBorderStyle(borderStyles, collapsedEndBorder());
    905     addBorderStyle(borderStyles, collapsedBeforeBorder());
    906     addBorderStyle(borderStyles, collapsedAfterBorder());
    907 }
    908 
    909 static int compareBorderStylesForQSort(const void* pa, const void* pb)
    910 {
    911     const CollapsedBorderValue* a = static_cast<const CollapsedBorderValue*>(pa);
    912     const CollapsedBorderValue* b = static_cast<const CollapsedBorderValue*>(pb);
    913     if (*a == *b)
    914         return 0;
    915     return compareBorders(*a, *b);
    916 }
    917 
    918 void RenderTableCell::sortBorderStyles(CollapsedBorderStyles& borderStyles)
    919 {
    920     qsort(borderStyles.data(), borderStyles.size(), sizeof(CollapsedBorderValue),
    921         compareBorderStylesForQSort);
    922 }
    923 
    924 void RenderTableCell::paintCollapsedBorder(GraphicsContext* graphicsContext, int tx, int ty, int w, int h)
    925 {
    926     if (!table()->currentBorderStyle())
    927         return;
    928 
    929     CollapsedBorderValue leftVal = collapsedLeftBorder();
    930     CollapsedBorderValue rightVal = collapsedRightBorder();
    931     CollapsedBorderValue topVal = collapsedTopBorder();
    932     CollapsedBorderValue bottomVal = collapsedBottomBorder();
    933 
    934     // Adjust our x/y/width/height so that we paint the collapsed borders at the correct location.
    935     int topWidth = topVal.width();
    936     int bottomWidth = bottomVal.width();
    937     int leftWidth = leftVal.width();
    938     int rightWidth = rightVal.width();
    939 
    940     tx -= leftWidth / 2;
    941     ty -= topWidth / 2;
    942     w += leftWidth / 2 + (rightWidth + 1) / 2;
    943     h += topWidth / 2 + (bottomWidth + 1) / 2;
    944 
    945     EBorderStyle topStyle = collapsedBorderStyle(topVal.style());
    946     EBorderStyle bottomStyle = collapsedBorderStyle(bottomVal.style());
    947     EBorderStyle leftStyle = collapsedBorderStyle(leftVal.style());
    948     EBorderStyle rightStyle = collapsedBorderStyle(rightVal.style());
    949 
    950     bool renderTop = topStyle > BHIDDEN && !topVal.isTransparent();
    951     bool renderBottom = bottomStyle > BHIDDEN && !bottomVal.isTransparent();
    952     bool renderLeft = leftStyle > BHIDDEN && !leftVal.isTransparent();
    953     bool renderRight = rightStyle > BHIDDEN && !rightVal.isTransparent();
    954 
    955     // We never paint diagonals at the joins.  We simply let the border with the highest
    956     // precedence paint on top of borders with lower precedence.
    957     CollapsedBorders borders;
    958     borders.addBorder(topVal, BSTop, renderTop, tx, ty, tx + w, ty + topWidth, topStyle);
    959     borders.addBorder(bottomVal, BSBottom, renderBottom, tx, ty + h - bottomWidth, tx + w, ty + h, bottomStyle);
    960     borders.addBorder(leftVal, BSLeft, renderLeft, tx, ty, tx + leftWidth, ty + h, leftStyle);
    961     borders.addBorder(rightVal, BSRight, renderRight, tx + w - rightWidth, ty, tx + w, ty + h, rightStyle);
    962 
    963     for (CollapsedBorder* border = borders.nextBorder(); border; border = borders.nextBorder()) {
    964         if (border->borderValue == *table()->currentBorderStyle())
    965             drawLineForBoxSide(graphicsContext, border->x1, border->y1, border->x2, border->y2, border->side,
    966                                border->borderValue.color(), border->style, 0, 0);
    967     }
    968 }
    969 
    970 void RenderTableCell::paintBackgroundsBehindCell(PaintInfo& paintInfo, int tx, int ty, RenderObject* backgroundObject)
    971 {
    972     if (!paintInfo.shouldPaintWithinRoot(this))
    973         return;
    974 
    975     if (!backgroundObject)
    976         return;
    977 
    978     if (style()->visibility() != VISIBLE)
    979         return;
    980 
    981     RenderTable* tableElt = table();
    982     if (!tableElt->collapseBorders() && style()->emptyCells() == HIDE && !firstChild())
    983         return;
    984 
    985     if (backgroundObject != this) {
    986         tx += x();
    987         ty += y();
    988     }
    989 
    990     int w = width();
    991     int h = height();
    992 
    993     Color c = backgroundObject->style()->visitedDependentColor(CSSPropertyBackgroundColor);
    994     const FillLayer* bgLayer = backgroundObject->style()->backgroundLayers();
    995 
    996     if (bgLayer->hasImage() || c.isValid()) {
    997         // We have to clip here because the background would paint
    998         // on top of the borders otherwise.  This only matters for cells and rows.
    999         bool shouldClip = backgroundObject->hasLayer() && (backgroundObject == this || backgroundObject == parent()) && tableElt->collapseBorders();
   1000         if (shouldClip) {
   1001             IntRect clipRect(tx + borderLeft(), ty + borderTop(),
   1002                 w - borderLeft() - borderRight(), h - borderTop() - borderBottom());
   1003             paintInfo.context->save();
   1004             paintInfo.context->clip(clipRect);
   1005         }
   1006         paintFillLayers(paintInfo, c, bgLayer, tx, ty, w, h, CompositeSourceOver, backgroundObject);
   1007         if (shouldClip)
   1008             paintInfo.context->restore();
   1009     }
   1010 }
   1011 
   1012 void RenderTableCell::paintBoxDecorations(PaintInfo& paintInfo, int tx, int ty)
   1013 {
   1014     if (!paintInfo.shouldPaintWithinRoot(this))
   1015         return;
   1016 
   1017     RenderTable* tableElt = table();
   1018     if (!tableElt->collapseBorders() && style()->emptyCells() == HIDE && !firstChild())
   1019         return;
   1020 
   1021     int w = width();
   1022     int h = height();
   1023 
   1024     paintBoxShadow(paintInfo.context, tx, ty, w, h, style(), Normal);
   1025 
   1026     // Paint our cell background.
   1027     paintBackgroundsBehindCell(paintInfo, tx, ty, this);
   1028 
   1029     paintBoxShadow(paintInfo.context, tx, ty, w, h, style(), Inset);
   1030 
   1031     if (!style()->hasBorder() || tableElt->collapseBorders())
   1032         return;
   1033 
   1034     paintBorder(paintInfo.context, tx, ty, w, h, style());
   1035 }
   1036 
   1037 void RenderTableCell::paintMask(PaintInfo& paintInfo, int tx, int ty)
   1038 {
   1039     if (style()->visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask)
   1040         return;
   1041 
   1042     RenderTable* tableElt = table();
   1043     if (!tableElt->collapseBorders() && style()->emptyCells() == HIDE && !firstChild())
   1044         return;
   1045 
   1046     int w = width();
   1047     int h = height();
   1048 
   1049     paintMaskImages(paintInfo, tx, ty, w, h);
   1050 }
   1051 
   1052 void RenderTableCell::scrollbarsChanged(bool horizontalScrollbarChanged, bool verticalScrollbarChanged)
   1053 {
   1054     int scrollbarHeight = scrollbarLogicalHeight();
   1055     if (!scrollbarHeight)
   1056         return; // Not sure if we should be doing something when a scrollbar goes away or not.
   1057 
   1058     // We only care if the scrollbar that affects our intrinsic padding has been added.
   1059     if ((isHorizontalWritingMode() && !horizontalScrollbarChanged) ||
   1060         (!isHorizontalWritingMode() && !verticalScrollbarChanged))
   1061         return;
   1062 
   1063     // Shrink our intrinsic padding as much as possible to accommodate the scrollbar.
   1064     if (style()->verticalAlign() == MIDDLE) {
   1065         int totalHeight = logicalHeight();
   1066         int heightWithoutIntrinsicPadding = totalHeight - intrinsicPaddingBefore() - intrinsicPaddingAfter();
   1067         totalHeight -= scrollbarHeight;
   1068         int newBeforePadding = (totalHeight - heightWithoutIntrinsicPadding) / 2;
   1069         int newAfterPadding = totalHeight - heightWithoutIntrinsicPadding - newBeforePadding;
   1070         setIntrinsicPaddingBefore(newBeforePadding);
   1071         setIntrinsicPaddingAfter(newAfterPadding);
   1072     } else
   1073         setIntrinsicPaddingAfter(intrinsicPaddingAfter() - scrollbarHeight);
   1074 }
   1075 
   1076 } // namespace WebCore
   1077