OSDN Git Service

am 866b5c80: (-s ours) am d8dd893d: Cherry-pick security fix in WebKit change 62271
[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 CollapsedBorderValue compareBorders(const CollapsedBorderValue& border1, const CollapsedBorderValue& border2)
308 {
309     // Sanity check the values passed in.  If either is null, return the other.
310     if (!border2.exists())
311         return border1;
312     if (!border1.exists())
313         return border2;
314
315     // Rule #1 above.
316     if (border1.style() == BHIDDEN || border2.style() == BHIDDEN)
317         return CollapsedBorderValue(); // No border should exist at this location.
318     
319     // Rule #2 above.  A style of 'none' has lowest priority and always loses to any other border.
320     if (border2.style() == BNONE)
321         return border1;
322     if (border1.style() == BNONE)
323         return border2;
324
325     // The first part of rule #3 above. Wider borders win.
326     if (border1.width() != border2.width())
327         return border1.width() > border2.width() ? border1 : border2;
328     
329     // The borders have equal width.  Sort by border style.
330     if (border1.style() != border2.style())
331         return border1.style() > border2.style() ? border1 : border2;
332     
333     // The border have the same width and style.  Rely on precedence (cell over row over row group, etc.)
334     return border1.precedence() >= border2.precedence() ? border1 : border2;
335 }
336
337 CollapsedBorderValue RenderTableCell::collapsedLeftBorder(bool rtl) const
338 {
339     RenderTable* tableElt = table();
340     bool leftmostColumn;
341     if (!rtl)
342         leftmostColumn = col() == 0;
343     else {
344         int effCol = tableElt->colToEffCol(col() + colSpan() - 1);
345         leftmostColumn = effCol == tableElt->numEffCols() - 1;
346     }
347     
348     // For border left, we need to check, in order of precedence:
349     // (1) Our left border.
350     int left = CSSPropertyBorderLeftColor;
351     int right = CSSPropertyBorderRightColor;
352     CollapsedBorderValue result(&style()->borderLeft(), style()->visitedDependentColor(left), BCELL);
353     
354     // (2) The right border of the cell to the left.
355     RenderTableCell* prevCell = rtl ? tableElt->cellAfter(this) : tableElt->cellBefore(this);
356     if (prevCell) {
357         CollapsedBorderValue prevCellBorder = CollapsedBorderValue(&prevCell->style()->borderRight(), prevCell->style()->visitedDependentColor(right), BCELL);
358         result = rtl ? compareBorders(result, prevCellBorder) : compareBorders(prevCellBorder, result);
359         if (!result.exists())
360             return result;
361     } else if (leftmostColumn) {
362         // (3) Our row's left border.
363         result = compareBorders(result, CollapsedBorderValue(&parent()->style()->borderLeft(), parent()->style()->visitedDependentColor(left), BROW));
364         if (!result.exists())
365             return result;
366         
367         // (4) Our row group's left border.
368         result = compareBorders(result, CollapsedBorderValue(&section()->style()->borderLeft(), section()->style()->visitedDependentColor(left), BROWGROUP));
369         if (!result.exists())
370             return result;
371     }
372     
373     // (5) Our column and column group's left borders.
374     bool startColEdge;
375     bool endColEdge;
376     RenderTableCol* colElt = tableElt->colElement(col() + (rtl ? colSpan() - 1 : 0), &startColEdge, &endColEdge);
377     if (colElt && (!rtl ? startColEdge : endColEdge)) {
378         result = compareBorders(result, CollapsedBorderValue(&colElt->style()->borderLeft(), colElt->style()->visitedDependentColor(left), BCOL));
379         if (!result.exists())
380             return result;
381         if (colElt->parent()->isTableCol() && (!rtl ? !colElt->previousSibling() : !colElt->nextSibling())) {
382             result = compareBorders(result, CollapsedBorderValue(&colElt->parent()->style()->borderLeft(), colElt->parent()->style()->visitedDependentColor(left), BCOLGROUP));
383             if (!result.exists())
384                 return result;
385         }
386     }
387     
388     // (6) The right border of the column to the left.
389     if (!leftmostColumn) {
390         colElt = tableElt->colElement(col() + (rtl ? colSpan() : -1), &startColEdge, &endColEdge);
391         if (colElt && (!rtl ? endColEdge : startColEdge)) {
392             CollapsedBorderValue rightBorder = CollapsedBorderValue(&colElt->style()->borderRight(), colElt->style()->visitedDependentColor(right), BCOL);
393             result = rtl ? compareBorders(result, rightBorder) : compareBorders(rightBorder, result);
394             if (!result.exists())
395                 return result;
396         }
397     } else {
398         // (7) The table's left border.
399         result = compareBorders(result, CollapsedBorderValue(&tableElt->style()->borderLeft(), tableElt->style()->visitedDependentColor(left), BTABLE));
400         if (!result.exists())
401             return result;
402     }
403     
404     return result;
405 }
406
407 CollapsedBorderValue RenderTableCell::collapsedRightBorder(bool rtl) const
408 {
409     RenderTable* tableElt = table();
410     bool rightmostColumn;
411     if (rtl)
412         rightmostColumn = col() == 0;
413     else {
414         int effCol = tableElt->colToEffCol(col() + colSpan() - 1);
415         rightmostColumn = effCol == tableElt->numEffCols() - 1;
416     }
417     
418     // For border right, we need to check, in order of precedence:
419     // (1) Our right border.
420     int left = CSSPropertyBorderLeftColor;
421     int right = CSSPropertyBorderRightColor;
422     CollapsedBorderValue result = CollapsedBorderValue(&style()->borderRight(), style()->visitedDependentColor(right), BCELL);
423     
424     // (2) The left border of the cell to the right.
425     if (!rightmostColumn) {
426         RenderTableCell* nextCell = rtl ? tableElt->cellBefore(this) : tableElt->cellAfter(this);
427         if (nextCell && nextCell->style()) {
428             CollapsedBorderValue leftBorder = CollapsedBorderValue(&nextCell->style()->borderLeft(), nextCell->style()->visitedDependentColor(left), BCELL);
429             result = rtl ? compareBorders(leftBorder, result) : compareBorders(result, leftBorder);
430             if (!result.exists())
431                 return result;
432         }
433     } else {
434         // (3) Our row's right border.
435         result = compareBorders(result, CollapsedBorderValue(&parent()->style()->borderRight(), parent()->style()->visitedDependentColor(right), BROW));
436         if (!result.exists())
437             return result;
438         
439         // (4) Our row group's right border.
440         result = compareBorders(result, CollapsedBorderValue(&section()->style()->borderRight(), section()->style()->visitedDependentColor(right), BROWGROUP));
441         if (!result.exists())
442             return result;
443     }
444     
445     // (5) Our column and column group's right borders.
446     bool startColEdge;
447     bool endColEdge;
448     RenderTableCol* colElt = tableElt->colElement(col() + (rtl ? 0 : colSpan() - 1), &startColEdge, &endColEdge);
449     if (colElt && (!rtl ? endColEdge : startColEdge)) {
450         result = compareBorders(result, CollapsedBorderValue(&colElt->style()->borderRight(), colElt->style()->visitedDependentColor(right), BCOL));
451         if (!result.exists())
452             return result;
453         if (colElt->parent()->isTableCol() && (!rtl ? !colElt->nextSibling() : !colElt->previousSibling())) {
454             result = compareBorders(result, CollapsedBorderValue(&colElt->parent()->style()->borderRight(), colElt->parent()->style()->visitedDependentColor(right), BCOLGROUP));
455             if (!result.exists())
456                 return result;
457         }
458     }
459     
460     // (6) The left border of the column to the right.
461     if (!rightmostColumn) {
462         colElt = tableElt->colElement(col() + (rtl ? -1 : colSpan()), &startColEdge, &endColEdge);
463         if (colElt && (!rtl ? startColEdge : endColEdge)) {
464             CollapsedBorderValue leftBorder = CollapsedBorderValue(&colElt->style()->borderLeft(), colElt->style()->visitedDependentColor(left), BCOL);
465             result = rtl ? compareBorders(leftBorder, result) : compareBorders(result, leftBorder);
466             if (!result.exists())
467                 return result;
468         }
469     } else {
470         // (7) The table's right border.
471         result = compareBorders(result, CollapsedBorderValue(&tableElt->style()->borderRight(), tableElt->style()->visitedDependentColor(right), BTABLE));
472         if (!result.exists())
473             return result;
474     }
475     
476     return result;
477 }
478
479 CollapsedBorderValue RenderTableCell::collapsedTopBorder() const
480 {
481     // For border top, we need to check, in order of precedence:
482     // (1) Our top border.
483     int top = CSSPropertyBorderTopColor;
484     int bottom = CSSPropertyBorderBottomColor;
485     CollapsedBorderValue result = CollapsedBorderValue(&style()->borderTop(), style()->visitedDependentColor(top), BCELL);
486     
487     RenderTableCell* prevCell = table()->cellAbove(this);
488     if (prevCell) {
489         // (2) A previous cell's bottom border.
490         result = compareBorders(CollapsedBorderValue(&prevCell->style()->borderBottom(), prevCell->style()->visitedDependentColor(bottom), BCELL), result);
491         if (!result.exists()) 
492             return result;
493     }
494     
495     // (3) Our row's top border.
496     result = compareBorders(result, CollapsedBorderValue(&parent()->style()->borderTop(), parent()->style()->visitedDependentColor(top), BROW));
497     if (!result.exists())
498         return result;
499     
500     // (4) The previous row's bottom border.
501     if (prevCell) {
502         RenderObject* prevRow = 0;
503         if (prevCell->section() == section())
504             prevRow = parent()->previousSibling();
505         else
506             prevRow = prevCell->section()->lastChild();
507     
508         if (prevRow) {
509             result = compareBorders(CollapsedBorderValue(&prevRow->style()->borderBottom(), prevRow->style()->visitedDependentColor(bottom), BROW), result);
510             if (!result.exists())
511                 return result;
512         }
513     }
514     
515     // Now check row groups.
516     RenderTableSection* currSection = section();
517     if (!row()) {
518         // (5) Our row group's top border.
519         result = compareBorders(result, CollapsedBorderValue(&currSection->style()->borderTop(), currSection->style()->visitedDependentColor(top), BROWGROUP));
520         if (!result.exists())
521             return result;
522         
523         // (6) Previous row group's bottom border.
524         currSection = table()->sectionAbove(currSection);
525         if (currSection) {
526             result = compareBorders(CollapsedBorderValue(&currSection->style()->borderBottom(), currSection->style()->visitedDependentColor(bottom), BROWGROUP), result);
527             if (!result.exists())
528                 return result;
529         }
530     }
531     
532     if (!currSection) {
533         // (8) Our column and column group's top borders.
534         RenderTableCol* colElt = table()->colElement(col());
535         if (colElt) {
536             result = compareBorders(result, CollapsedBorderValue(&colElt->style()->borderTop(), colElt->style()->visitedDependentColor(top), BCOL));
537             if (!result.exists())
538                 return result;
539             if (colElt->parent()->isTableCol()) {
540                 result = compareBorders(result, CollapsedBorderValue(&colElt->parent()->style()->borderTop(), colElt->parent()->style()->visitedDependentColor(top), BCOLGROUP));
541                 if (!result.exists())
542                     return result;
543             }
544         }
545         
546         // (9) The table's top border.
547         RenderTable* enclosingTable = table();
548         result = compareBorders(result, CollapsedBorderValue(&enclosingTable->style()->borderTop(), enclosingTable->style()->visitedDependentColor(top), BTABLE));
549         if (!result.exists())
550             return result;
551     }
552     
553     return result;
554 }
555
556 CollapsedBorderValue RenderTableCell::collapsedBottomBorder() const
557 {
558     // For border top, we need to check, in order of precedence:
559     // (1) Our bottom border.
560     int top = CSSPropertyBorderTopColor;
561     int bottom = CSSPropertyBorderBottomColor;
562     CollapsedBorderValue result = CollapsedBorderValue(&style()->borderBottom(), style()->visitedDependentColor(bottom), BCELL);
563     
564     RenderTableCell* nextCell = table()->cellBelow(this);
565     if (nextCell) {
566         // (2) A following cell's top border.
567         result = compareBorders(result, CollapsedBorderValue(&nextCell->style()->borderTop(), nextCell->style()->visitedDependentColor(top), BCELL));
568         if (!result.exists())
569             return result;
570     }
571     
572     // (3) Our row's bottom border. (FIXME: Deal with rowspan!)
573     result = compareBorders(result, CollapsedBorderValue(&parent()->style()->borderBottom(), parent()->style()->visitedDependentColor(bottom), BROW));
574     if (!result.exists())
575         return result;
576     
577     // (4) The next row's top border.
578     if (nextCell) {
579         result = compareBorders(result, CollapsedBorderValue(&nextCell->parent()->style()->borderTop(), nextCell->parent()->style()->visitedDependentColor(top), BROW));
580         if (!result.exists())
581             return result;
582     }
583     
584     // Now check row groups.
585     RenderTableSection* currSection = section();
586     if (row() + rowSpan() >= currSection->numRows()) {
587         // (5) Our row group's bottom border.
588         result = compareBorders(result, CollapsedBorderValue(&currSection->style()->borderBottom(), currSection->style()->visitedDependentColor(bottom), BROWGROUP));
589         if (!result.exists())
590             return result;
591         
592         // (6) Following row group's top border.
593         currSection = table()->sectionBelow(currSection);
594         if (currSection) {
595             result = compareBorders(result, CollapsedBorderValue(&currSection->style()->borderTop(), currSection->style()->visitedDependentColor(top), BROWGROUP));
596             if (!result.exists())
597                 return result;
598         }
599     }
600     
601     if (!currSection) {
602         // (8) Our column and column group's bottom borders.
603         RenderTableCol* colElt = table()->colElement(col());
604         if (colElt) {
605             result = compareBorders(result, CollapsedBorderValue(&colElt->style()->borderBottom(), colElt->style()->visitedDependentColor(bottom), BCOL));
606             if (!result.exists()) return result;
607             if (colElt->parent()->isTableCol()) {
608                 result = compareBorders(result, CollapsedBorderValue(&colElt->parent()->style()->borderBottom(), colElt->parent()->style()->visitedDependentColor(bottom), BCOLGROUP));
609                 if (!result.exists())
610                     return result;
611             }
612         }
613         
614         // (9) The table's bottom border.
615         RenderTable* enclosingTable = table();
616         result = compareBorders(result, CollapsedBorderValue(&enclosingTable->style()->borderBottom(), enclosingTable->style()->visitedDependentColor(bottom), BTABLE));
617         if (!result.exists())
618             return result;
619     }
620     
621     return result;    
622 }
623
624 int RenderTableCell::borderLeft() const
625 {
626     return table()->collapseBorders() ? borderHalfLeft(false) : RenderBlock::borderLeft();
627 }
628
629 int RenderTableCell::borderRight() const
630 {
631     return table()->collapseBorders() ? borderHalfRight(false) : RenderBlock::borderRight();
632 }
633
634 int RenderTableCell::borderTop() const
635 {
636     return table()->collapseBorders() ? borderHalfTop(false) : RenderBlock::borderTop();
637 }
638
639 int RenderTableCell::borderBottom() const
640 {
641     return table()->collapseBorders() ? borderHalfBottom(false) : RenderBlock::borderBottom();
642 }
643
644 int RenderTableCell::borderHalfLeft(bool outer) const
645 {
646     CollapsedBorderValue border = collapsedLeftBorder(table()->style()->direction() == RTL);
647     if (border.exists())
648         return (border.width() + (outer ? 0 : 1)) / 2; // Give the extra pixel to top and left.
649     return 0;
650 }
651     
652 int RenderTableCell::borderHalfRight(bool outer) const
653 {
654     CollapsedBorderValue border = collapsedRightBorder(table()->style()->direction() == RTL);
655     if (border.exists())
656         return (border.width() + (outer ? 1 : 0)) / 2;
657     return 0;
658 }
659
660 int RenderTableCell::borderHalfTop(bool outer) const
661 {
662     CollapsedBorderValue border = collapsedTopBorder();
663     if (border.exists())
664         return (border.width() + (outer ? 0 : 1)) / 2; // Give the extra pixel to top and left.
665     return 0;
666 }
667
668 int RenderTableCell::borderHalfBottom(bool outer) const
669 {
670     CollapsedBorderValue border = collapsedBottomBorder();
671     if (border.exists())
672         return (border.width() + (outer ? 1 : 0)) / 2;
673     return 0;
674 }
675
676 void RenderTableCell::paint(PaintInfo& paintInfo, int tx, int ty)
677 {
678     if (paintInfo.phase == PaintPhaseCollapsedTableBorders && style()->visibility() == VISIBLE) {
679         if (!paintInfo.shouldPaintWithinRoot(this))
680             return;
681
682         tx += x();
683         ty += y();
684         int os = 2 * maximalOutlineSize(paintInfo.phase);
685         if (ty - table()->outerBorderTop() < paintInfo.rect.bottom() + os &&
686             ty + height() + table()->outerBorderBottom() > paintInfo.rect.y() - os)
687             paintCollapsedBorder(paintInfo.context, tx, ty, width(), height());
688         return;
689     } 
690     
691     RenderBlock::paint(paintInfo, tx, ty);
692 }
693
694 static EBorderStyle collapsedBorderStyle(EBorderStyle style)
695 {
696     if (style == OUTSET)
697         return GROOVE;
698     if (style == INSET)
699         return RIDGE;
700     return style;
701 }
702
703 struct CollapsedBorder {
704     CollapsedBorderValue borderValue;
705     BoxSide side;
706     bool shouldPaint;
707     int x1;
708     int y1;
709     int x2;
710     int y2;
711     EBorderStyle style;
712 };
713
714 class CollapsedBorders {
715 public:
716     CollapsedBorders()
717         : m_count(0)
718     {
719     }
720     
721     void addBorder(const CollapsedBorderValue& borderValue, BoxSide borderSide, bool shouldPaint,
722                    int x1, int y1, int x2, int y2, EBorderStyle borderStyle)
723     {
724         if (borderValue.exists() && shouldPaint) {
725             m_borders[m_count].borderValue = borderValue;
726             m_borders[m_count].side = borderSide;
727             m_borders[m_count].shouldPaint = shouldPaint;
728             m_borders[m_count].x1 = x1;
729             m_borders[m_count].x2 = x2;
730             m_borders[m_count].y1 = y1;
731             m_borders[m_count].y2 = y2;
732             m_borders[m_count].style = borderStyle;
733             m_count++;
734         }
735     }
736
737     CollapsedBorder* nextBorder()
738     {
739         for (int i = 0; i < m_count; i++) {
740             if (m_borders[i].borderValue.exists() && m_borders[i].shouldPaint) {
741                 m_borders[i].shouldPaint = false;
742                 return &m_borders[i];
743             }
744         }
745         
746         return 0;
747     }
748     
749     CollapsedBorder m_borders[4];
750     int m_count;
751 };
752
753 static void addBorderStyle(RenderTableCell::CollapsedBorderStyles& borderStyles, CollapsedBorderValue borderValue)
754 {
755     if (!borderValue.exists())
756         return;
757     size_t count = borderStyles.size();
758     for (size_t i = 0; i < count; ++i)
759         if (borderStyles[i] == borderValue)
760             return;
761     borderStyles.append(borderValue);
762 }
763
764 void RenderTableCell::collectBorderStyles(CollapsedBorderStyles& borderStyles) const
765 {
766     bool rtl = table()->style()->direction() == RTL;
767     addBorderStyle(borderStyles, collapsedLeftBorder(rtl));
768     addBorderStyle(borderStyles, collapsedRightBorder(rtl));
769     addBorderStyle(borderStyles, collapsedTopBorder());
770     addBorderStyle(borderStyles, collapsedBottomBorder());
771 }
772
773 static int compareBorderStylesForQSort(const void* pa, const void* pb)
774 {
775     const CollapsedBorderValue* a = static_cast<const CollapsedBorderValue*>(pa);
776     const CollapsedBorderValue* b = static_cast<const CollapsedBorderValue*>(pb);
777     if (*a == *b)
778         return 0;
779     CollapsedBorderValue borderWithHigherPrecedence = compareBorders(*a, *b);
780 #ifdef ANDROID_FIX
781     if (*a == borderWithHigherPrecedence) {
782         // klibc uses a combsort for quicksort and requires that two values always give the same answer
783         // regardless of comparison order. Unfortunately, compareBorders does not honor that requirement.
784         // Call compareBorders again with reversed parameters. If it returns the first value again then
785         // we can assume the values are equal. http://bugs.webkit.org/show_bug.cgi?id=13147
786         CollapsedBorderValue qSortHack = compareBorders(*b, *a);
787         if (*b == qSortHack)
788             return 0;
789         return 1;
790     }
791 #else
792     if (*a == borderWithHigherPrecedence)
793         return 1;
794 #endif
795     return -1;
796 }
797
798 void RenderTableCell::sortBorderStyles(CollapsedBorderStyles& borderStyles)
799 {
800     qsort(borderStyles.data(), borderStyles.size(), sizeof(CollapsedBorderValue),
801         compareBorderStylesForQSort);
802 }
803
804 void RenderTableCell::paintCollapsedBorder(GraphicsContext* graphicsContext, int tx, int ty, int w, int h)
805 {
806     if (!table()->currentBorderStyle())
807         return;
808     
809     bool rtl = table()->style()->direction() == RTL;
810     CollapsedBorderValue leftVal = collapsedLeftBorder(rtl);
811     CollapsedBorderValue rightVal = collapsedRightBorder(rtl);
812     CollapsedBorderValue topVal = collapsedTopBorder();
813     CollapsedBorderValue bottomVal = collapsedBottomBorder();
814      
815     // Adjust our x/y/width/height so that we paint the collapsed borders at the correct location.
816     int topWidth = topVal.width();
817     int bottomWidth = bottomVal.width();
818     int leftWidth = leftVal.width();
819     int rightWidth = rightVal.width();
820     
821     tx -= leftWidth / 2;
822     ty -= topWidth / 2;
823     w += leftWidth / 2 + (rightWidth + 1) / 2;
824     h += topWidth / 2 + (bottomWidth + 1) / 2;
825     
826     EBorderStyle topStyle = collapsedBorderStyle(topVal.style());
827     EBorderStyle bottomStyle = collapsedBorderStyle(bottomVal.style());
828     EBorderStyle leftStyle = collapsedBorderStyle(leftVal.style());
829     EBorderStyle rightStyle = collapsedBorderStyle(rightVal.style());
830     
831     bool renderTop = topStyle > BHIDDEN && !topVal.isTransparent();
832     bool renderBottom = bottomStyle > BHIDDEN && !bottomVal.isTransparent();
833     bool renderLeft = leftStyle > BHIDDEN && !leftVal.isTransparent();
834     bool renderRight = rightStyle > BHIDDEN && !rightVal.isTransparent();
835
836     // We never paint diagonals at the joins.  We simply let the border with the highest
837     // precedence paint on top of borders with lower precedence.  
838     CollapsedBorders borders;
839     borders.addBorder(topVal, BSTop, renderTop, tx, ty, tx + w, ty + topWidth, topStyle);
840     borders.addBorder(bottomVal, BSBottom, renderBottom, tx, ty + h - bottomWidth, tx + w, ty + h, bottomStyle);
841     borders.addBorder(leftVal, BSLeft, renderLeft, tx, ty, tx + leftWidth, ty + h, leftStyle);
842     borders.addBorder(rightVal, BSRight, renderRight, tx + w - rightWidth, ty, tx + w, ty + h, rightStyle);
843     
844     for (CollapsedBorder* border = borders.nextBorder(); border; border = borders.nextBorder()) {
845         if (border->borderValue == *table()->currentBorderStyle())
846             drawLineForBoxSide(graphicsContext, border->x1, border->y1, border->x2, border->y2, border->side, 
847                                border->borderValue.color(), border->style, 0, 0);
848     }
849 }
850
851 void RenderTableCell::paintBackgroundsBehindCell(PaintInfo& paintInfo, int tx, int ty, RenderObject* backgroundObject)
852 {
853     if (!paintInfo.shouldPaintWithinRoot(this))
854         return;
855
856     if (!backgroundObject)
857         return;
858
859     if (style()->visibility() != VISIBLE)
860         return;
861
862     RenderTable* tableElt = table();
863     if (!tableElt->collapseBorders() && style()->emptyCells() == HIDE && !firstChild())
864         return;
865
866     if (backgroundObject != this) {
867         tx += x();
868         ty += y();
869     }
870
871     int w = width();
872     int h = height();
873
874     Color c = backgroundObject->style()->visitedDependentColor(CSSPropertyBackgroundColor);
875     const FillLayer* bgLayer = backgroundObject->style()->backgroundLayers();
876
877     if (bgLayer->hasImage() || c.isValid()) {
878         // We have to clip here because the background would paint
879         // on top of the borders otherwise.  This only matters for cells and rows.
880         bool shouldClip = backgroundObject->hasLayer() && (backgroundObject == this || backgroundObject == parent()) && tableElt->collapseBorders();
881         if (shouldClip) {
882             IntRect clipRect(tx + borderLeft(), ty + borderTop(),
883                 w - borderLeft() - borderRight(), h - borderTop() - borderBottom());
884             paintInfo.context->save();
885             paintInfo.context->clip(clipRect);
886         }
887         paintFillLayers(paintInfo, c, bgLayer, tx, ty, w, h, CompositeSourceOver, backgroundObject);
888         if (shouldClip)
889             paintInfo.context->restore();
890     }
891 }
892
893 void RenderTableCell::paintBoxDecorations(PaintInfo& paintInfo, int tx, int ty)
894 {
895     if (!paintInfo.shouldPaintWithinRoot(this))
896         return;
897
898     RenderTable* tableElt = table();
899     if (!tableElt->collapseBorders() && style()->emptyCells() == HIDE && !firstChild())
900         return;
901
902     int w = width();
903     int h = height();
904    
905     if (style()->boxShadow())
906         paintBoxShadow(paintInfo.context, tx, ty, w, h, style(), Normal);
907     
908     // Paint our cell background.
909     paintBackgroundsBehindCell(paintInfo, tx, ty, this);
910     if (style()->boxShadow())
911         paintBoxShadow(paintInfo.context, tx, ty, w, h, style(), Inset);
912
913     if (!style()->hasBorder() || tableElt->collapseBorders())
914         return;
915
916     paintBorder(paintInfo.context, tx, ty, w, h, style());
917 }
918
919 void RenderTableCell::paintMask(PaintInfo& paintInfo, int tx, int ty)
920 {
921     if (style()->visibility() != VISIBLE || paintInfo.phase != PaintPhaseMask)
922         return;
923
924     RenderTable* tableElt = table();
925     if (!tableElt->collapseBorders() && style()->emptyCells() == HIDE && !firstChild())
926         return;
927
928     int w = width();
929     int h = height();
930    
931     paintMaskImages(paintInfo, tx, ty, w, h);
932 }
933
934 } // namespace WebCore