OSDN Git Service

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