OSDN Git Service

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