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