OSDN Git Service

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