OSDN Git Service

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