2011-07-22 Simon Fraser <simon.fraser@apple.com>
[WebKit-https.git] / Source / WebCore / rendering / RenderBoxModelObject.cpp
1 /*
2  * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3  *           (C) 1999 Antti Koivisto (koivisto@kde.org)
4  *           (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
5  *           (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
6  * Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
7  * Copyright (C) 2010 Google 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
26 #include "config.h"
27 #include "RenderBoxModelObject.h"
28
29 #include "GraphicsContext.h"
30 #include "HTMLFrameOwnerElement.h"
31 #include "HTMLNames.h"
32 #include "ImageBuffer.h"
33 #include "Page.h"
34 #include "Path.h"
35 #include "RenderBlock.h"
36 #include "RenderInline.h"
37 #include "RenderLayer.h"
38 #include "RenderView.h"
39 #include <wtf/CurrentTime.h>
40
41 using namespace std;
42
43 namespace WebCore {
44
45 using namespace HTMLNames;
46
47 bool RenderBoxModelObject::s_wasFloating = false;
48 bool RenderBoxModelObject::s_hadLayer = false;
49 bool RenderBoxModelObject::s_layerWasSelfPainting = false;
50
51 static const double cInterpolationCutoff = 800. * 800.;
52 static const double cLowQualityTimeThreshold = 0.500; // 500 ms
53
54 typedef HashMap<const void*, IntSize> LayerSizeMap;
55 typedef HashMap<RenderBoxModelObject*, LayerSizeMap> ObjectLayerSizeMap;
56
57 // The HashMap for storing continuation pointers.
58 // An inline can be split with blocks occuring in between the inline content.
59 // When this occurs we need a pointer to the next object. We can basically be
60 // split into a sequence of inlines and blocks. The continuation will either be
61 // an anonymous block (that houses other blocks) or it will be an inline flow.
62 // <b><i><p>Hello</p></i></b>. In this example the <i> will have a block as
63 // its continuation but the <b> will just have an inline as its continuation.
64 typedef HashMap<const RenderBoxModelObject*, RenderBoxModelObject*> ContinuationMap;
65 static ContinuationMap* continuationMap = 0;
66
67 class ImageQualityController {
68     WTF_MAKE_NONCOPYABLE(ImageQualityController); WTF_MAKE_FAST_ALLOCATED;
69 public:
70     ImageQualityController();
71     bool shouldPaintAtLowQuality(GraphicsContext*, RenderBoxModelObject*, Image*, const void* layer, const IntSize&);
72     void removeLayer(RenderBoxModelObject*, LayerSizeMap* innerMap, const void* layer);
73     void set(RenderBoxModelObject*, LayerSizeMap* innerMap, const void* layer, const IntSize&);
74     void objectDestroyed(RenderBoxModelObject*);
75     bool isEmpty() { return m_objectLayerSizeMap.isEmpty(); }
76
77 private:
78     void highQualityRepaintTimerFired(Timer<ImageQualityController>*);
79     void restartTimer();
80
81     ObjectLayerSizeMap m_objectLayerSizeMap;
82     Timer<ImageQualityController> m_timer;
83     bool m_animatedResizeIsActive;
84 };
85
86 ImageQualityController::ImageQualityController()
87     : m_timer(this, &ImageQualityController::highQualityRepaintTimerFired)
88     , m_animatedResizeIsActive(false)
89 {
90 }
91
92 void ImageQualityController::removeLayer(RenderBoxModelObject* object, LayerSizeMap* innerMap, const void* layer)
93 {
94     if (innerMap) {
95         innerMap->remove(layer);
96         if (innerMap->isEmpty())
97             objectDestroyed(object);
98     }
99 }
100     
101 void ImageQualityController::set(RenderBoxModelObject* object, LayerSizeMap* innerMap, const void* layer, const IntSize& size)
102 {
103     if (innerMap)
104         innerMap->set(layer, size);
105     else {
106         LayerSizeMap newInnerMap;
107         newInnerMap.set(layer, size);
108         m_objectLayerSizeMap.set(object, newInnerMap);
109     }
110 }
111     
112 void ImageQualityController::objectDestroyed(RenderBoxModelObject* object)
113 {
114     m_objectLayerSizeMap.remove(object);
115     if (m_objectLayerSizeMap.isEmpty()) {
116         m_animatedResizeIsActive = false;
117         m_timer.stop();
118     }
119 }
120
121 void ImageQualityController::highQualityRepaintTimerFired(Timer<ImageQualityController>*)
122 {
123     if (m_animatedResizeIsActive) {
124         m_animatedResizeIsActive = false;
125         for (ObjectLayerSizeMap::iterator it = m_objectLayerSizeMap.begin(); it != m_objectLayerSizeMap.end(); ++it)
126             it->first->repaint();
127     }
128 }
129
130 void ImageQualityController::restartTimer()
131 {
132     m_timer.startOneShot(cLowQualityTimeThreshold);
133 }
134
135 bool ImageQualityController::shouldPaintAtLowQuality(GraphicsContext* context, RenderBoxModelObject* object, Image* image, const void *layer, const IntSize& size)
136 {
137     // If the image is not a bitmap image, then none of this is relevant and we just paint at high
138     // quality.
139     if (!image || !image->isBitmapImage() || context->paintingDisabled())
140         return false;
141
142     if (object->style()->imageRendering() == ImageRenderingOptimizeContrast)
143         return true;
144     
145     // Make sure to use the unzoomed image size, since if a full page zoom is in effect, the image
146     // is actually being scaled.
147     IntSize imageSize(image->width(), image->height());
148
149     // Look ourselves up in the hashtables.
150     ObjectLayerSizeMap::iterator i = m_objectLayerSizeMap.find(object);
151     LayerSizeMap* innerMap = i != m_objectLayerSizeMap.end() ? &i->second : 0;
152     IntSize oldSize;
153     bool isFirstResize = true;
154     if (innerMap) {
155         LayerSizeMap::iterator j = innerMap->find(layer);
156         if (j != innerMap->end()) {
157             isFirstResize = false;
158             oldSize = j->second;
159         }
160     }
161
162     const AffineTransform& currentTransform = context->getCTM();
163     bool contextIsScaled = !currentTransform.isIdentityOrTranslationOrFlipped();
164     if (!contextIsScaled && imageSize == size) {
165         // There is no scale in effect. If we had a scale in effect before, we can just remove this object from the list.
166         removeLayer(object, innerMap, layer);
167         return false;
168     }
169
170     // There is no need to hash scaled images that always use low quality mode when the page demands it. This is the iChat case.
171     if (object->document()->page()->inLowQualityImageInterpolationMode()) {
172         double totalPixels = static_cast<double>(image->width()) * static_cast<double>(image->height());
173         if (totalPixels > cInterpolationCutoff)
174             return true;
175     }
176
177     // If an animated resize is active, paint in low quality and kick the timer ahead.
178     if (m_animatedResizeIsActive) {
179         set(object, innerMap, layer, size);
180         restartTimer();
181         return true;
182     }
183     // If this is the first time resizing this image, or its size is the
184     // same as the last resize, draw at high res, but record the paint
185     // size and set the timer.
186     if (isFirstResize || oldSize == size) {
187         restartTimer();
188         set(object, innerMap, layer, size);
189         return false;
190     }
191     // If the timer is no longer active, draw at high quality and don't
192     // set the timer.
193     if (!m_timer.isActive()) {
194         removeLayer(object, innerMap, layer);
195         return false;
196     }
197     // This object has been resized to two different sizes while the timer
198     // is active, so draw at low quality, set the flag for animated resizes and
199     // the object to the list for high quality redraw.
200     set(object, innerMap, layer, size);
201     m_animatedResizeIsActive = true;
202     restartTimer();
203     return true;
204 }
205
206 static ImageQualityController* gImageQualityController = 0;
207
208 static ImageQualityController* imageQualityController()
209 {
210     if (!gImageQualityController)
211         gImageQualityController = new ImageQualityController;
212
213     return gImageQualityController;
214 }
215
216 void RenderBoxModelObject::setSelectionState(SelectionState s)
217 {
218     if (selectionState() == s)
219         return;
220     
221     if (s == SelectionInside && selectionState() != SelectionNone)
222         return;
223
224     if ((s == SelectionStart && selectionState() == SelectionEnd)
225         || (s == SelectionEnd && selectionState() == SelectionStart))
226         RenderObject::setSelectionState(SelectionBoth);
227     else
228         RenderObject::setSelectionState(s);
229     
230     // FIXME:
231     // We should consider whether it is OK propagating to ancestor RenderInlines.
232     // This is a workaround for http://webkit.org/b/32123
233     RenderBlock* cb = containingBlock();
234     if (cb && !cb->isRenderView())
235         cb->setSelectionState(s);
236 }
237
238 bool RenderBoxModelObject::shouldPaintAtLowQuality(GraphicsContext* context, Image* image, const void* layer, const IntSize& size)
239 {
240     return imageQualityController()->shouldPaintAtLowQuality(context, this, image, layer, size);
241 }
242
243 RenderBoxModelObject::RenderBoxModelObject(Node* node)
244     : RenderObject(node)
245     , m_layer(0)
246 {
247 }
248
249 RenderBoxModelObject::~RenderBoxModelObject()
250 {
251     // Our layer should have been destroyed and cleared by now
252     ASSERT(!hasLayer());
253     ASSERT(!m_layer);
254     if (gImageQualityController) {
255         gImageQualityController->objectDestroyed(this);
256         if (gImageQualityController->isEmpty()) {
257             delete gImageQualityController;
258             gImageQualityController = 0;
259         }
260     }
261 }
262
263 void RenderBoxModelObject::destroyLayer()
264 {
265     ASSERT(!hasLayer()); // Callers should have already called setHasLayer(false)
266     ASSERT(m_layer);
267     m_layer->destroy(renderArena());
268     m_layer = 0;
269 }
270
271 void RenderBoxModelObject::willBeDestroyed()
272 {
273     // This must be done before we destroy the RenderObject.
274     if (m_layer)
275         m_layer->clearClipRects();
276
277     // A continuation of this RenderObject should be destroyed at subclasses.
278     ASSERT(!continuation());
279
280     // RenderObject::willBeDestroyed calls back to destroyLayer() for layer destruction
281     RenderObject::willBeDestroyed();
282 }
283
284 bool RenderBoxModelObject::hasSelfPaintingLayer() const
285 {
286     return m_layer && m_layer->isSelfPaintingLayer();
287 }
288
289 void RenderBoxModelObject::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
290 {
291     s_wasFloating = isFloating();
292     s_hadLayer = hasLayer();
293     if (s_hadLayer)
294         s_layerWasSelfPainting = layer()->isSelfPaintingLayer();
295
296     // If our z-index changes value or our visibility changes,
297     // we need to dirty our stacking context's z-order list.
298     if (style() && newStyle) {
299         if (parent()) {
300             // Do a repaint with the old style first, e.g., for example if we go from
301             // having an outline to not having an outline.
302             if (diff == StyleDifferenceRepaintLayer) {
303                 layer()->repaintIncludingDescendants();
304                 if (!(style()->clip() == newStyle->clip()))
305                     layer()->clearClipRectsIncludingDescendants();
306             } else if (diff == StyleDifferenceRepaint || newStyle->outlineSize() < style()->outlineSize())
307                 repaint();
308         }
309         
310         if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
311             // When a layout hint happens, we go ahead and do a repaint of the layer, since the layer could
312             // end up being destroyed.
313             if (hasLayer()) {
314                 if (style()->position() != newStyle->position() ||
315                     style()->zIndex() != newStyle->zIndex() ||
316                     style()->hasAutoZIndex() != newStyle->hasAutoZIndex() ||
317                     !(style()->clip() == newStyle->clip()) ||
318                     style()->hasClip() != newStyle->hasClip() ||
319                     style()->opacity() != newStyle->opacity() ||
320                     style()->transform() != newStyle->transform())
321                 layer()->repaintIncludingDescendants();
322             } else if (newStyle->hasTransform() || newStyle->opacity() < 1) {
323                 // If we don't have a layer yet, but we are going to get one because of transform or opacity,
324                 //  then we need to repaint the old position of the object.
325                 repaint();
326             }
327         }
328
329         if (hasLayer() && (style()->hasAutoZIndex() != newStyle->hasAutoZIndex() ||
330                            style()->zIndex() != newStyle->zIndex() ||
331                            style()->visibility() != newStyle->visibility())) {
332             layer()->dirtyStackingContextZOrderLists();
333             if (style()->hasAutoZIndex() != newStyle->hasAutoZIndex() || style()->visibility() != newStyle->visibility())
334                 layer()->dirtyZOrderLists();
335         }
336     }
337
338     RenderObject::styleWillChange(diff, newStyle);
339 }
340
341 void RenderBoxModelObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
342 {
343     RenderObject::styleDidChange(diff, oldStyle);
344     updateBoxModelInfoFromStyle();
345     
346     if (requiresLayer()) {
347         if (!layer()) {
348             if (s_wasFloating && isFloating())
349                 setChildNeedsLayout(true);
350             m_layer = new (renderArena()) RenderLayer(this);
351             setHasLayer(true);
352             m_layer->insertOnlyThisLayer();
353             if (parent() && !needsLayout() && containingBlock()) {
354                 m_layer->setNeedsFullRepaint();
355                 m_layer->updateLayerPositions();
356             }
357         }
358     } else if (layer() && layer()->parent()) {
359         setHasTransform(false); // Either a transform wasn't specified or the object doesn't support transforms, so just null out the bit.
360         setHasReflection(false);
361         m_layer->removeOnlyThisLayer(); // calls destroyLayer() which clears m_layer
362         if (s_wasFloating && isFloating())
363             setChildNeedsLayout(true);
364     }
365
366     if (layer()) {
367         layer()->styleChanged(diff, oldStyle);
368         if (s_hadLayer && layer()->isSelfPaintingLayer() != s_layerWasSelfPainting)
369             setChildNeedsLayout(true);
370     }
371 }
372
373 void RenderBoxModelObject::updateBoxModelInfoFromStyle()
374 {
375     // Set the appropriate bits for a box model object.  Since all bits are cleared in styleWillChange,
376     // we only check for bits that could possibly be set to true.
377     setHasBoxDecorations(hasBackground() || style()->hasBorder() || style()->hasAppearance() || style()->boxShadow());
378     setInline(style()->isDisplayInlineType());
379     setRelPositioned(style()->position() == RelativePosition);
380     setHorizontalWritingMode(style()->isHorizontalWritingMode());
381 }
382
383 LayoutUnit RenderBoxModelObject::relativePositionOffsetX() const
384 {
385     // Objects that shrink to avoid floats normally use available line width when computing containing block width.  However
386     // in the case of relative positioning using percentages, we can't do this.  The offset should always be resolved using the
387     // available width of the containing block.  Therefore we don't use containingBlockLogicalWidthForContent() here, but instead explicitly
388     // call availableWidth on our containing block.
389     if (!style()->left().isAuto()) {
390         RenderBlock* cb = containingBlock();
391         if (!style()->right().isAuto() && !cb->style()->isLeftToRightDirection())
392             return -style()->right().calcValue(cb->availableWidth());
393         return style()->left().calcValue(cb->availableWidth());
394     }
395     if (!style()->right().isAuto()) {
396         RenderBlock* cb = containingBlock();
397         return -style()->right().calcValue(cb->availableWidth());
398     }
399     return 0;
400 }
401
402 LayoutUnit RenderBoxModelObject::relativePositionOffsetY() const
403 {
404     RenderBlock* containingBlock = this->containingBlock();
405
406     // If the containing block of a relatively positioned element does not
407     // specify a height, a percentage top or bottom offset should be resolved as
408     // auto. An exception to this is if the containing block has the WinIE quirk
409     // where <html> and <body> assume the size of the viewport. In this case,
410     // calculate the percent offset based on this height.
411     // See <https://bugs.webkit.org/show_bug.cgi?id=26396>.
412     if (!style()->top().isAuto()
413         && (!containingBlock->style()->height().isAuto()
414             || !style()->top().isPercent()
415             || containingBlock->stretchesToViewport()))
416         return style()->top().calcValue(containingBlock->availableHeight());
417
418     if (!style()->bottom().isAuto()
419         && (!containingBlock->style()->height().isAuto()
420             || !style()->bottom().isPercent()
421             || containingBlock->stretchesToViewport()))
422         return -style()->bottom().calcValue(containingBlock->availableHeight());
423
424     return 0;
425 }
426
427 LayoutUnit RenderBoxModelObject::offsetLeft() const
428 {
429     // If the element is the HTML body element or does not have an associated box
430     // return 0 and stop this algorithm.
431     if (isBody())
432         return 0;
433     
434     RenderBoxModelObject* offsetPar = offsetParent();
435     LayoutUnit xPos = (isBox() ? toRenderBox(this)->x() : 0);
436     
437     // If the offsetParent of the element is null, or is the HTML body element,
438     // return the distance between the canvas origin and the left border edge 
439     // of the element and stop this algorithm.
440     if (offsetPar) {
441         if (offsetPar->isBox() && !offsetPar->isBody())
442             xPos -= toRenderBox(offsetPar)->borderLeft();
443         if (!isPositioned()) {
444             if (isRelPositioned())
445                 xPos += relativePositionOffsetX();
446             RenderObject* curr = parent();
447             while (curr && curr != offsetPar) {
448                 // FIXME: What are we supposed to do inside SVG content?
449                 if (curr->isBox() && !curr->isTableRow())
450                     xPos += toRenderBox(curr)->x();
451                 curr = curr->parent();
452             }
453             if (offsetPar->isBox() && offsetPar->isBody() && !offsetPar->isRelPositioned() && !offsetPar->isPositioned())
454                 xPos += toRenderBox(offsetPar)->x();
455         }
456     }
457
458     return xPos;
459 }
460
461 LayoutUnit RenderBoxModelObject::offsetTop() const
462 {
463     // If the element is the HTML body element or does not have an associated box
464     // return 0 and stop this algorithm.
465     if (isBody())
466         return 0;
467     
468     RenderBoxModelObject* offsetPar = offsetParent();
469     LayoutUnit yPos = (isBox() ? toRenderBox(this)->y() : 0);
470     
471     // If the offsetParent of the element is null, or is the HTML body element,
472     // return the distance between the canvas origin and the top border edge 
473     // of the element and stop this algorithm.
474     if (offsetPar) {
475         if (offsetPar->isBox() && !offsetPar->isBody())
476             yPos -= toRenderBox(offsetPar)->borderTop();
477         if (!isPositioned()) {
478             if (isRelPositioned())
479                 yPos += relativePositionOffsetY();
480             RenderObject* curr = parent();
481             while (curr && curr != offsetPar) {
482                 // FIXME: What are we supposed to do inside SVG content?
483                 if (curr->isBox() && !curr->isTableRow())
484                     yPos += toRenderBox(curr)->y();
485                 curr = curr->parent();
486             }
487             if (offsetPar->isBox() && offsetPar->isBody() && !offsetPar->isRelPositioned() && !offsetPar->isPositioned())
488                 yPos += toRenderBox(offsetPar)->y();
489         }
490     }
491     return yPos;
492 }
493
494 LayoutUnit RenderBoxModelObject::paddingTop(bool) const
495 {
496     LayoutUnit w = 0;
497     Length padding = style()->paddingTop();
498     if (padding.isPercent())
499         w = containingBlock()->availableLogicalWidth();
500     return padding.calcMinValue(w);
501 }
502
503 LayoutUnit RenderBoxModelObject::paddingBottom(bool) const
504 {
505     LayoutUnit w = 0;
506     Length padding = style()->paddingBottom();
507     if (padding.isPercent())
508         w = containingBlock()->availableLogicalWidth();
509     return padding.calcMinValue(w);
510 }
511
512 LayoutUnit RenderBoxModelObject::paddingLeft(bool) const
513 {
514     LayoutUnit w = 0;
515     Length padding = style()->paddingLeft();
516     if (padding.isPercent())
517         w = containingBlock()->availableLogicalWidth();
518     return padding.calcMinValue(w);
519 }
520
521 LayoutUnit RenderBoxModelObject::paddingRight(bool) const
522 {
523     LayoutUnit w = 0;
524     Length padding = style()->paddingRight();
525     if (padding.isPercent())
526         w = containingBlock()->availableLogicalWidth();
527     return padding.calcMinValue(w);
528 }
529
530 LayoutUnit RenderBoxModelObject::paddingBefore(bool) const
531 {
532     LayoutUnit w = 0;
533     Length padding = style()->paddingBefore();
534     if (padding.isPercent())
535         w = containingBlock()->availableLogicalWidth();
536     return padding.calcMinValue(w);
537 }
538
539 LayoutUnit RenderBoxModelObject::paddingAfter(bool) const
540 {
541     LayoutUnit w = 0;
542     Length padding = style()->paddingAfter();
543     if (padding.isPercent())
544         w = containingBlock()->availableLogicalWidth();
545     return padding.calcMinValue(w);
546 }
547
548 LayoutUnit RenderBoxModelObject::paddingStart(bool) const
549 {
550     LayoutUnit w = 0;
551     Length padding = style()->paddingStart();
552     if (padding.isPercent())
553         w = containingBlock()->availableLogicalWidth();
554     return padding.calcMinValue(w);
555 }
556
557 LayoutUnit RenderBoxModelObject::paddingEnd(bool) const
558 {
559     LayoutUnit w = 0;
560     Length padding = style()->paddingEnd();
561     if (padding.isPercent())
562         w = containingBlock()->availableLogicalWidth();
563     return padding.calcMinValue(w);
564 }
565
566 RoundedRect RenderBoxModelObject::getBackgroundRoundedRect(const LayoutRect& borderRect, InlineFlowBox* box, LayoutUnit inlineBoxWidth, LayoutUnit inlineBoxHeight,
567     bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
568 {
569     RoundedRect border = style()->getRoundedBorderFor(borderRect, includeLogicalLeftEdge, includeLogicalRightEdge);
570     if (box && (box->nextLineBox() || box->prevLineBox())) {
571         RoundedRect segmentBorder = style()->getRoundedBorderFor(LayoutRect(0, 0, inlineBoxWidth, inlineBoxHeight), includeLogicalLeftEdge, includeLogicalRightEdge);
572         border.setRadii(segmentBorder.radii());
573     }
574
575     return border;
576 }
577
578 static IntRect backgroundRectAdjustedForBleedAvoidance(GraphicsContext* context, const IntRect& borderRect, BackgroundBleedAvoidance bleedAvoidance)
579 {
580     if (bleedAvoidance != BackgroundBleedShrinkBackground)
581         return borderRect;
582
583     IntRect adjustedRect = borderRect;
584     // We need to shrink the border by one device pixel on each side.
585     AffineTransform ctm = context->getCTM();
586     FloatSize contextScale(static_cast<float>(ctm.xScale()), static_cast<float>(ctm.yScale()));
587     adjustedRect.inflateX(-ceilf(1 / contextScale.width()));
588     adjustedRect.inflateY(-ceilf(1 / contextScale.height()));
589     return adjustedRect;
590 }
591
592 void RenderBoxModelObject::paintFillLayerExtended(const PaintInfo& paintInfo, const Color& color, const FillLayer* bgLayer, const LayoutRect& rect,
593     BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* box, const LayoutSize& boxSize, CompositeOperator op, RenderObject* backgroundObject)
594 {
595     GraphicsContext* context = paintInfo.context;
596     if (context->paintingDisabled() || rect.isEmpty())
597         return;
598
599     bool includeLeftEdge = box ? box->includeLogicalLeftEdge() : true;
600     bool includeRightEdge = box ? box->includeLogicalRightEdge() : true;
601
602     bool hasRoundedBorder = style()->hasBorderRadius() && (includeLeftEdge || includeRightEdge);
603     bool clippedWithLocalScrolling = hasOverflowClip() && bgLayer->attachment() == LocalBackgroundAttachment;
604     bool isBorderFill = bgLayer->clip() == BorderFillBox;
605     bool isRoot = this->isRoot();
606
607     Color bgColor = color;
608     StyleImage* bgImage = bgLayer->image();
609     bool shouldPaintBackgroundImage = bgImage && bgImage->canRender(style()->effectiveZoom());
610     
611     // When this style flag is set, change existing background colors and images to a solid white background.
612     // If there's no bg color or image, leave it untouched to avoid affecting transparency.
613     // We don't try to avoid loading the background images, because this style flag is only set
614     // when printing, and at that point we've already loaded the background images anyway. (To avoid
615     // loading the background images we'd have to do this check when applying styles rather than
616     // while rendering.)
617     if (style()->forceBackgroundsToWhite()) {
618         // Note that we can't reuse this variable below because the bgColor might be changed
619         bool shouldPaintBackgroundColor = !bgLayer->next() && bgColor.isValid() && bgColor.alpha() > 0;
620         if (shouldPaintBackgroundImage || shouldPaintBackgroundColor) {
621             bgColor = Color::white;
622             shouldPaintBackgroundImage = false;
623         }
624     }
625
626     bool colorVisible = bgColor.isValid() && bgColor.alpha() > 0;
627     
628     // Fast path for drawing simple color backgrounds.
629     if (!isRoot && !clippedWithLocalScrolling && !shouldPaintBackgroundImage && isBorderFill && !bgLayer->next()) {
630         if (!colorVisible)
631             return;
632
633         if (hasRoundedBorder && bleedAvoidance != BackgroundBleedUseTransparencyLayer) {
634             RoundedRect border = getBackgroundRoundedRect(backgroundRectAdjustedForBleedAvoidance(context, rect, bleedAvoidance), box, boxSize.width(), boxSize.height(), includeLeftEdge, includeRightEdge);
635             context->fillRoundedRect(border, bgColor, style()->colorSpace());
636         } else
637             context->fillRect(rect, bgColor, style()->colorSpace());
638         
639         return;
640     }
641
642     bool clipToBorderRadius = hasRoundedBorder && bleedAvoidance != BackgroundBleedUseTransparencyLayer;
643     GraphicsContextStateSaver clipToBorderStateSaver(*context, clipToBorderRadius);
644     if (clipToBorderRadius) {
645         RoundedRect border = getBackgroundRoundedRect(backgroundRectAdjustedForBleedAvoidance(context, rect, bleedAvoidance), box, boxSize.width(), boxSize.height(), includeLeftEdge, includeRightEdge);
646         context->addRoundedRectClip(border);
647     }
648     
649     LayoutUnit bLeft = includeLeftEdge ? borderLeft() : 0;
650     LayoutUnit bRight = includeRightEdge ? borderRight() : 0;
651     LayoutUnit pLeft = includeLeftEdge ? paddingLeft() : 0;
652     LayoutUnit pRight = includeRightEdge ? paddingRight() : 0;
653
654     GraphicsContextStateSaver clipWithScrollingStateSaver(*context, clippedWithLocalScrolling);
655     LayoutRect scrolledPaintRect = rect;
656     if (clippedWithLocalScrolling) {
657         // Clip to the overflow area.
658         context->clip(toRenderBox(this)->overflowClipRect(rect.location()));
659         
660         // Adjust the paint rect to reflect a scrolled content box with borders at the ends.
661         LayoutSize offset = layer()->scrolledContentOffset();
662         scrolledPaintRect.move(-offset);
663         scrolledPaintRect.setWidth(bLeft + layer()->scrollWidth() + bRight);
664         scrolledPaintRect.setHeight(borderTop() + layer()->scrollHeight() + borderBottom());
665     }
666     
667     GraphicsContextStateSaver backgroundClipStateSaver(*context, false);
668     if (bgLayer->clip() == PaddingFillBox || bgLayer->clip() == ContentFillBox) {
669         // Clip to the padding or content boxes as necessary.
670         bool includePadding = bgLayer->clip() == ContentFillBox;
671         LayoutRect clipRect = LayoutRect(scrolledPaintRect.x() + bLeft + (includePadding ? pLeft : 0),
672                                    scrolledPaintRect.y() + borderTop() + (includePadding ? paddingTop() : 0),
673                                    scrolledPaintRect.width() - bLeft - bRight - (includePadding ? pLeft + pRight : 0),
674                                    scrolledPaintRect.height() - borderTop() - borderBottom() - (includePadding ? paddingTop() + paddingBottom() : 0));
675         backgroundClipStateSaver.save();
676         context->clip(clipRect);
677     } else if (bgLayer->clip() == TextFillBox) {
678         // We have to draw our text into a mask that can then be used to clip background drawing.
679         // First figure out how big the mask has to be.  It should be no bigger than what we need
680         // to actually render, so we should intersect the dirty rect with the border box of the background.
681         LayoutRect maskRect = rect;
682         maskRect.intersect(paintInfo.rect);
683         
684         // Now create the mask.
685         OwnPtr<ImageBuffer> maskImage = ImageBuffer::create(maskRect.size());
686         if (!maskImage)
687             return;
688         
689         GraphicsContext* maskImageContext = maskImage->context();
690         maskImageContext->translate(-maskRect.x(), -maskRect.y());
691         
692         // Now add the text to the clip.  We do this by painting using a special paint phase that signals to
693         // InlineTextBoxes that they should just add their contents to the clip.
694         PaintInfo info(maskImageContext, maskRect, PaintPhaseTextClip, true, 0, 0);
695         if (box) {
696             RootInlineBox* root = box->root();
697             box->paint(info, LayoutPoint(scrolledPaintRect.x() - box->x(), scrolledPaintRect.y() - box->y()), root->lineTop(), root->lineBottom());
698         } else {
699             LayoutSize localOffset = isBox() ? toRenderBox(this)->locationOffset() : LayoutSize();
700             paint(info, scrolledPaintRect.location() - localOffset);
701         }
702         
703         // The mask has been created.  Now we just need to clip to it.
704         backgroundClipStateSaver.save();
705         context->clipToImageBuffer(maskImage.get(), maskRect);
706     }
707     
708     // Only fill with a base color (e.g., white) if we're the root document, since iframes/frames with
709     // no background in the child document should show the parent's background.
710     bool isOpaqueRoot = false;
711     if (isRoot) {
712         isOpaqueRoot = true;
713         if (!bgLayer->next() && !(bgColor.isValid() && bgColor.alpha() == 255) && view()->frameView()) {
714             Element* ownerElement = document()->ownerElement();
715             if (ownerElement) {
716                 if (!ownerElement->hasTagName(frameTag)) {
717                     // Locate the <body> element using the DOM.  This is easier than trying
718                     // to crawl around a render tree with potential :before/:after content and
719                     // anonymous blocks created by inline <body> tags etc.  We can locate the <body>
720                     // render object very easily via the DOM.
721                     HTMLElement* body = document()->body();
722                     if (body) {
723                         // Can't scroll a frameset document anyway.
724                         isOpaqueRoot = body->hasLocalName(framesetTag);
725                     }
726 #if ENABLE(SVG)
727                     else {
728                         // SVG documents and XML documents with SVG root nodes are transparent.
729                         isOpaqueRoot = !document()->hasSVGRootNode();
730                     }
731 #endif
732                 }
733             } else
734                 isOpaqueRoot = !view()->frameView()->isTransparent();
735         }
736         view()->frameView()->setContentIsOpaque(isOpaqueRoot);
737     }
738
739     // Paint the color first underneath all images.
740     if (!bgLayer->next()) {
741         LayoutRect backgroundRect(scrolledPaintRect);
742         backgroundRect.intersect(paintInfo.rect);
743         // If we have an alpha and we are painting the root element, go ahead and blend with the base background color.
744         Color baseColor;
745         bool shouldClearBackground = false;
746         if (isOpaqueRoot) {
747             baseColor = view()->frameView()->baseBackgroundColor();
748             if (!baseColor.alpha())
749                 shouldClearBackground = true;
750         }
751
752         if (baseColor.alpha()) {
753             if (bgColor.alpha())
754                 baseColor = baseColor.blend(bgColor);
755
756             context->fillRect(backgroundRect, baseColor, style()->colorSpace(), CompositeCopy);
757         } else if (bgColor.alpha()) {
758             CompositeOperator operation = shouldClearBackground ? CompositeCopy : context->compositeOperation();
759             context->fillRect(backgroundRect, bgColor, style()->colorSpace(), operation);
760         } else if (shouldClearBackground)
761             context->clearRect(backgroundRect);
762     }
763
764     // no progressive loading of the background image
765     if (shouldPaintBackgroundImage) {
766         BackgroundImageGeometry geometry;
767         calculateBackgroundImageGeometry(bgLayer, scrolledPaintRect, geometry);
768         geometry.clip(paintInfo.rect);
769         if (!geometry.destRect().isEmpty()) {
770             CompositeOperator compositeOp = op == CompositeSourceOver ? bgLayer->composite() : op;
771             RenderObject* clientForBackgroundImage = backgroundObject ? backgroundObject : this;
772             RefPtr<Image> image = bgImage->image(clientForBackgroundImage, geometry.tileSize());
773             bool useLowQualityScaling = shouldPaintAtLowQuality(context, image.get(), bgLayer, geometry.tileSize());
774             context->drawTiledImage(image.get(), style()->colorSpace(), geometry.destRect(), geometry.relativePhase(), geometry.tileSize(), 
775                 compositeOp, useLowQualityScaling);
776         }
777     }
778 }
779
780 IntSize RenderBoxModelObject::calculateFillTileSize(const FillLayer* fillLayer, IntSize positioningAreaSize) const
781 {
782     StyleImage* image = fillLayer->image();
783     image->setImageContainerSize(positioningAreaSize); // Use the box established by background-origin.
784
785     EFillSizeType type = fillLayer->size().type;
786
787     switch (type) {
788         case SizeLength: {
789             int w = positioningAreaSize.width();
790             int h = positioningAreaSize.height();
791
792             Length layerWidth = fillLayer->size().size.width();
793             Length layerHeight = fillLayer->size().size.height();
794
795             if (layerWidth.isFixed())
796                 w = layerWidth.value();
797             else if (layerWidth.isPercent())
798                 w = layerWidth.calcValue(positioningAreaSize.width());
799             
800             if (layerHeight.isFixed())
801                 h = layerHeight.value();
802             else if (layerHeight.isPercent())
803                 h = layerHeight.calcValue(positioningAreaSize.height());
804             
805             // If one of the values is auto we have to use the appropriate
806             // scale to maintain our aspect ratio.
807             if (layerWidth.isAuto() && !layerHeight.isAuto()) {
808                 IntSize imageIntrinsicSize = image->imageSize(this, style()->effectiveZoom());
809                 if (imageIntrinsicSize.height())
810                     w = imageIntrinsicSize.width() * h / imageIntrinsicSize.height();        
811             } else if (!layerWidth.isAuto() && layerHeight.isAuto()) {
812                 IntSize imageIntrinsicSize = image->imageSize(this, style()->effectiveZoom());
813                 if (imageIntrinsicSize.width())
814                     h = imageIntrinsicSize.height() * w / imageIntrinsicSize.width();
815             } else if (layerWidth.isAuto() && layerHeight.isAuto()) {
816                 // If both width and height are auto, use the image's intrinsic size.
817                 IntSize imageIntrinsicSize = image->imageSize(this, style()->effectiveZoom());
818                 w = imageIntrinsicSize.width();
819                 h = imageIntrinsicSize.height();
820             }
821             
822             return IntSize(max(1, w), max(1, h));
823         }
824         case Contain:
825         case Cover: {
826             IntSize imageIntrinsicSize = image->imageSize(this, 1);
827             float horizontalScaleFactor = imageIntrinsicSize.width()
828                 ? static_cast<float>(positioningAreaSize.width()) / imageIntrinsicSize.width() : 1;
829             float verticalScaleFactor = imageIntrinsicSize.height()
830                 ? static_cast<float>(positioningAreaSize.height()) / imageIntrinsicSize.height() : 1;
831             float scaleFactor = type == Contain ? min(horizontalScaleFactor, verticalScaleFactor) : max(horizontalScaleFactor, verticalScaleFactor);
832             return IntSize(max<int>(1, imageIntrinsicSize.width() * scaleFactor), max<int>(1, imageIntrinsicSize.height() * scaleFactor));
833         }
834         case SizeNone:
835             break;
836     }
837
838     return image->imageSize(this, style()->effectiveZoom());
839 }
840
841 void RenderBoxModelObject::BackgroundImageGeometry::setNoRepeatX(int xOffset)
842 {
843     m_destRect.move(max(xOffset, 0), 0);
844     m_phase.setX(-min(xOffset, 0));
845     m_destRect.setWidth(m_tileSize.width() + min(xOffset, 0));
846 }
847 void RenderBoxModelObject::BackgroundImageGeometry::setNoRepeatY(int yOffset)
848 {
849     m_destRect.move(0, max(yOffset, 0));
850     m_phase.setY(-min(yOffset, 0));
851     m_destRect.setHeight(m_tileSize.height() + min(yOffset, 0));
852 }
853
854 void RenderBoxModelObject::BackgroundImageGeometry::useFixedAttachment(const LayoutPoint& attachmentPoint)
855 {
856     m_phase.move(max(attachmentPoint.x() - m_destRect.x(), 0), max(attachmentPoint.y() - m_destRect.y(), 0));
857 }
858
859 void RenderBoxModelObject::BackgroundImageGeometry::clip(const LayoutRect& clipRect)
860 {
861     m_destRect.intersect(clipRect);
862 }
863
864 LayoutPoint RenderBoxModelObject::BackgroundImageGeometry::relativePhase() const
865 {
866     LayoutPoint phase = m_phase;
867     phase += m_destRect.location() - m_destOrigin;
868     return phase;
869 }
870
871 void RenderBoxModelObject::calculateBackgroundImageGeometry(const FillLayer* fillLayer, const IntRect& paintRect, 
872                                                             BackgroundImageGeometry& geometry)
873 {
874     int left = 0;
875     int top = 0;
876     IntSize positioningAreaSize;
877
878     // Determine the background positioning area and set destRect to the background painting area.
879     // destRect will be adjusted later if the background is non-repeating.
880     bool fixedAttachment = fillLayer->attachment() == FixedBackgroundAttachment;
881
882 #if ENABLE(FAST_MOBILE_SCROLLING)
883     if (view()->frameView() && view()->frameView()->canBlitOnScroll()) {
884         // As a side effect of an optimization to blit on scroll, we do not honor the CSS
885         // property "background-attachment: fixed" because it may result in rendering
886         // artifacts. Note, these artifacts only appear if we are blitting on scroll of
887         // a page that has fixed background images.
888         fixedAttachment = false;
889     }
890 #endif
891
892     if (!fixedAttachment) {
893         geometry.setDestRect(paintRect);
894
895         int right = 0;
896         int bottom = 0;
897         // Scroll and Local.
898         if (fillLayer->origin() != BorderFillBox) {
899             left = borderLeft();
900             right = borderRight();
901             top = borderTop();
902             bottom = borderBottom();
903             if (fillLayer->origin() == ContentFillBox) {
904                 left += paddingLeft();
905                 right += paddingRight();
906                 top += paddingTop();
907                 bottom += paddingBottom();
908             }
909         }
910
911         // The background of the box generated by the root element covers the entire canvas including
912         // its margins. Since those were added in already, we have to factor them out when computing
913         // the background positioning area.
914         if (isRoot()) {
915             positioningAreaSize = IntSize(toRenderBox(this)->width() - left - right, toRenderBox(this)->height() - top - bottom);
916             left += marginLeft();
917             top += marginTop();
918         } else
919             positioningAreaSize = IntSize(paintRect.width() - left - right, paintRect.height() - top - bottom);
920     } else {
921         geometry.setDestRect(viewRect());
922         positioningAreaSize = geometry.destRect().size();
923     }
924
925     geometry.setTileSize(calculateFillTileSize(fillLayer, positioningAreaSize));
926
927     EFillRepeat backgroundRepeatX = fillLayer->repeatX();
928     EFillRepeat backgroundRepeatY = fillLayer->repeatY();
929
930     int xPosition = fillLayer->xPosition().calcMinValue(positioningAreaSize.width() - geometry.tileSize().width(), true);
931     if (backgroundRepeatX == RepeatFill)
932         geometry.setPhaseX(geometry.tileSize().width() ? geometry.tileSize().width() - (xPosition + left) % geometry.tileSize().width() : 0);
933     else
934         geometry.setNoRepeatX(xPosition + left);
935
936     int yPosition = fillLayer->yPosition().calcMinValue(positioningAreaSize.height() - geometry.tileSize().height(), true);
937     if (backgroundRepeatY == RepeatFill)
938         geometry.setPhaseY(geometry.tileSize().height() ? geometry.tileSize().height() - (yPosition + top) % geometry.tileSize().height() : 0);
939     else 
940         geometry.setNoRepeatY(yPosition + top);
941
942     if (fixedAttachment)
943         geometry.useFixedAttachment(paintRect.location());
944
945     geometry.clip(paintRect);
946     geometry.setDestOrigin(geometry.destRect().location());
947 }
948
949 bool RenderBoxModelObject::paintNinePieceImage(GraphicsContext* graphicsContext, const IntRect& rect, const RenderStyle* style,
950                                                const NinePieceImage& ninePieceImage, CompositeOperator op)
951 {
952     StyleImage* styleImage = ninePieceImage.image();
953     if (!styleImage)
954         return false;
955
956     if (!styleImage->isLoaded())
957         return true; // Never paint a nine-piece image incrementally, but don't paint the fallback borders either.
958
959     if (!styleImage->canRender(style->effectiveZoom()))
960         return false;
961
962     // FIXME: border-image is broken with full page zooming when tiling has to happen, since the tiling function
963     // doesn't have any understanding of the zoom that is in effect on the tile.
964     styleImage->setImageContainerSize(rect.size());
965     IntSize imageSize = styleImage->imageSize(this, 1.0f);
966     int imageWidth = imageSize.width();
967     int imageHeight = imageSize.height();
968
969     int topSlice = min(imageHeight, ninePieceImage.slices().top().calcValue(imageHeight));
970     int bottomSlice = min(imageHeight, ninePieceImage.slices().bottom().calcValue(imageHeight));
971     int leftSlice = min(imageWidth, ninePieceImage.slices().left().calcValue(imageWidth));
972     int rightSlice = min(imageWidth, ninePieceImage.slices().right().calcValue(imageWidth));
973
974     ENinePieceImageRule hRule = ninePieceImage.horizontalRule();
975     ENinePieceImageRule vRule = ninePieceImage.verticalRule();
976
977     bool fitToBorder = style->borderImage() == ninePieceImage;
978     
979     int leftWidth = fitToBorder ? style->borderLeftWidth() : leftSlice;
980     int topWidth = fitToBorder ? style->borderTopWidth() : topSlice;
981     int rightWidth = fitToBorder ? style->borderRightWidth() : rightSlice;
982     int bottomWidth = fitToBorder ? style->borderBottomWidth() : bottomSlice;
983
984     bool drawLeft = leftSlice > 0 && leftWidth > 0;
985     bool drawTop = topSlice > 0 && topWidth > 0;
986     bool drawRight = rightSlice > 0 && rightWidth > 0;
987     bool drawBottom = bottomSlice > 0 && bottomWidth > 0;
988     bool drawMiddle = (imageWidth - leftSlice - rightSlice) > 0 && (rect.width() - leftWidth - rightWidth) > 0
989                       && (imageHeight - topSlice - bottomSlice) > 0 && (rect.height() - topWidth - bottomWidth) > 0;
990
991     RefPtr<Image> image = styleImage->image(this, imageSize);
992     ColorSpace colorSpace = style->colorSpace();
993
994     if (drawLeft) {
995         // Paint the top and bottom left corners.
996
997         // The top left corner rect is (tx, ty, leftWidth, topWidth)
998         // The rect to use from within the image is obtained from our slice, and is (0, 0, leftSlice, topSlice)
999         if (drawTop)
1000             graphicsContext->drawImage(image.get(), colorSpace, IntRect(rect.location(), IntSize(leftWidth, topWidth)),
1001                                        IntRect(0, 0, leftSlice, topSlice), op);
1002
1003         // The bottom left corner rect is (tx, ty + h - bottomWidth, leftWidth, bottomWidth)
1004         // The rect to use from within the image is (0, imageHeight - bottomSlice, leftSlice, botomSlice)
1005         if (drawBottom)
1006             graphicsContext->drawImage(image.get(), colorSpace, IntRect(rect.x(), rect.y() + rect.height() - bottomWidth, leftWidth, bottomWidth),
1007                                        IntRect(0, imageHeight - bottomSlice, leftSlice, bottomSlice), op);
1008
1009         // Paint the left edge.
1010         // Have to scale and tile into the border rect.
1011         graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(rect.x(), rect.y() + topWidth, leftWidth,
1012                                         rect.height() - topWidth - bottomWidth),
1013                                         IntRect(0, topSlice, leftSlice, imageHeight - topSlice - bottomSlice),
1014                                         Image::StretchTile, (Image::TileRule)vRule, op);
1015     }
1016
1017     if (drawRight) {
1018         // Paint the top and bottom right corners
1019         // The top right corner rect is (tx + w - rightWidth, ty, rightWidth, topWidth)
1020         // The rect to use from within the image is obtained from our slice, and is (imageWidth - rightSlice, 0, rightSlice, topSlice)
1021         if (drawTop)
1022             graphicsContext->drawImage(image.get(), colorSpace, IntRect(rect.x() + rect.width() - rightWidth, rect.y(), rightWidth, topWidth),
1023                                        IntRect(imageWidth - rightSlice, 0, rightSlice, topSlice), op);
1024
1025         // The bottom right corner rect is (tx + w - rightWidth, ty + h - bottomWidth, rightWidth, bottomWidth)
1026         // The rect to use from within the image is (imageWidth - rightSlice, imageHeight - bottomSlice, rightSlice, bottomSlice)
1027         if (drawBottom)
1028             graphicsContext->drawImage(image.get(), colorSpace, IntRect(rect.x() + rect.width() - rightWidth, rect.y() + rect.height() - bottomWidth, rightWidth, bottomWidth),
1029                                        IntRect(imageWidth - rightSlice, imageHeight - bottomSlice, rightSlice, bottomSlice), op);
1030
1031         // Paint the right edge.
1032         graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(rect.x() + rect.width() - rightWidth, rect.y() + topWidth, rightWidth,
1033                                         rect.height() - topWidth - bottomWidth),
1034                                         IntRect(imageWidth - rightSlice, topSlice, rightSlice, imageHeight - topSlice - bottomSlice),
1035                                         Image::StretchTile, (Image::TileRule)vRule, op);
1036     }
1037
1038     // Paint the top edge.
1039     if (drawTop)
1040         graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(rect.x() + leftWidth, rect.y(), rect.width() - leftWidth - rightWidth, topWidth),
1041                                         IntRect(leftSlice, 0, imageWidth - rightSlice - leftSlice, topSlice),
1042                                         (Image::TileRule)hRule, Image::StretchTile, op);
1043
1044     // Paint the bottom edge.
1045     if (drawBottom)
1046         graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(rect.x() + leftWidth, rect.y() + rect.height() - bottomWidth,
1047                                         rect.width() - leftWidth - rightWidth, bottomWidth),
1048                                         IntRect(leftSlice, imageHeight - bottomSlice, imageWidth - rightSlice - leftSlice, bottomSlice),
1049                                         (Image::TileRule)hRule, Image::StretchTile, op);
1050
1051     // Paint the middle.
1052     if (drawMiddle)
1053         graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(rect.x() + leftWidth, rect.y() + topWidth, rect.width() - leftWidth - rightWidth,
1054                                         rect.height() - topWidth - bottomWidth),
1055                                         IntRect(leftSlice, topSlice, imageWidth - rightSlice - leftSlice, imageHeight - topSlice - bottomSlice),
1056                                         (Image::TileRule)hRule, (Image::TileRule)vRule, op);
1057
1058     return true;
1059 }
1060
1061 class BorderEdge {
1062 public:
1063     BorderEdge(int edgeWidth, const Color& edgeColor, EBorderStyle edgeStyle, bool edgeIsTransparent, bool edgeIsPresent = true)
1064         : width(edgeWidth)
1065         , color(edgeColor)
1066         , style(edgeStyle)
1067         , isTransparent(edgeIsTransparent)
1068         , isPresent(edgeIsPresent)
1069     {
1070         if (style == DOUBLE && edgeWidth < 3)
1071             style = SOLID;
1072     }
1073     
1074     BorderEdge()
1075         : width(0)
1076         , style(BHIDDEN)
1077         , isTransparent(false)
1078         , isPresent(false)
1079     {
1080     }
1081     
1082     bool hasVisibleColorAndStyle() const { return style > BHIDDEN && !isTransparent; }
1083     bool shouldRender() const { return isPresent && hasVisibleColorAndStyle(); }
1084     bool presentButInvisible() const { return usedWidth() && !hasVisibleColorAndStyle(); }
1085     bool obscuresBackgroundEdge(float scale) const
1086     {
1087         if (!isPresent || isTransparent || width < (2 * scale) || color.hasAlpha() || style == BHIDDEN)
1088             return false;
1089
1090         if (style == DOTTED || style == DASHED)
1091             return false;
1092
1093         if (style == DOUBLE)
1094             return width >= 5 * scale; // The outer band needs to be >= 2px wide at unit scale.
1095
1096         return true;
1097     }
1098     bool obscuresBackground() const
1099     {
1100         if (!isPresent || isTransparent || color.hasAlpha() || style == BHIDDEN)
1101             return false;
1102
1103         if (style == DOTTED || style == DASHED || style == DOUBLE)
1104             return false;
1105
1106         return true;
1107     }
1108
1109     int usedWidth() const { return isPresent ? width : 0; }
1110     
1111     void getDoubleBorderStripeWidths(int& outerWidth, int& innerWidth) const
1112     {
1113         int fullWidth = usedWidth();
1114         outerWidth = fullWidth / 3;
1115         innerWidth = fullWidth * 2 / 3;
1116
1117         // We need certain integer rounding results
1118         if (fullWidth % 3 == 2)
1119             outerWidth += 1;
1120
1121         if (fullWidth % 3 == 1)
1122             innerWidth += 1;
1123     }
1124     
1125     int width;
1126     Color color;
1127     EBorderStyle style;
1128     bool isTransparent;
1129     bool isPresent;
1130 };
1131
1132 #if HAVE(PATH_BASED_BORDER_RADIUS_DRAWING)
1133 static bool borderWillArcInnerEdge(const IntSize& firstRadius, const IntSize& secondRadius)
1134 {
1135     return !firstRadius.isZero() || !secondRadius.isZero();
1136 }
1137
1138 enum BorderEdgeFlag {
1139     TopBorderEdge = 1 << BSTop,
1140     RightBorderEdge = 1 << BSRight,
1141     BottomBorderEdge = 1 << BSBottom,
1142     LeftBorderEdge = 1 << BSLeft,
1143     AllBorderEdges = TopBorderEdge | BottomBorderEdge | LeftBorderEdge | RightBorderEdge
1144 };
1145
1146 static inline BorderEdgeFlag edgeFlagForSide(BoxSide side)
1147 {
1148     return static_cast<BorderEdgeFlag>(1 << side);
1149 }
1150
1151 static inline bool includesEdge(BorderEdgeFlags flags, BoxSide side)
1152 {
1153     return flags & edgeFlagForSide(side);
1154 }
1155
1156 inline bool edgesShareColor(const BorderEdge& firstEdge, const BorderEdge& secondEdge)
1157 {
1158     return firstEdge.color == secondEdge.color;
1159 }
1160
1161 inline bool styleRequiresClipPolygon(EBorderStyle style)
1162 {
1163     return style == DOTTED || style == DASHED; // These are drawn with a stroke, so we have to clip to get corner miters.
1164 }
1165
1166 static bool borderStyleFillsBorderArea(EBorderStyle style)
1167 {
1168     return !(style == DOTTED || style == DASHED || style == DOUBLE);
1169 }
1170
1171 static bool borderStyleHasInnerDetail(EBorderStyle style)
1172 {
1173     return style == GROOVE || style == RIDGE || style == DOUBLE;
1174 }
1175
1176 static bool borderStyleIsDottedOrDashed(EBorderStyle style)
1177 {
1178     return style == DOTTED || style == DASHED;
1179 }
1180
1181 // OUTSET darkens the bottom and right (and maybe lightens the top and left)
1182 // INSET darkens the top and left (and maybe lightens the bottom and right)
1183 static inline bool borderStyleHasUnmatchedColorsAtCorner(EBorderStyle style, BoxSide side, BoxSide adjacentSide)
1184 {
1185     // These styles match at the top/left and bottom/right.
1186     if (style == INSET || style == GROOVE || style == RIDGE || style == OUTSET) {
1187         const BorderEdgeFlags topRightFlags = edgeFlagForSide(BSTop) | edgeFlagForSide(BSRight);
1188         const BorderEdgeFlags bottomLeftFlags = edgeFlagForSide(BSBottom) | edgeFlagForSide(BSLeft);
1189
1190         BorderEdgeFlags flags = edgeFlagForSide(side) | edgeFlagForSide(adjacentSide);
1191         return flags == topRightFlags || flags == bottomLeftFlags;
1192     }
1193     return false;
1194 }
1195
1196 static inline bool colorsMatchAtCorner(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1197 {
1198     if (edges[side].shouldRender() != edges[adjacentSide].shouldRender())
1199         return false;
1200
1201     if (!edgesShareColor(edges[side], edges[adjacentSide]))
1202         return false;
1203
1204     return !borderStyleHasUnmatchedColorsAtCorner(edges[side].style, side, adjacentSide);
1205 }
1206
1207 // This assumes that we draw in order: top, bottom, left, right.
1208 static inline bool willBeOverdrawn(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1209 {
1210     switch (side) {
1211     case BSTop:
1212     case BSBottom:
1213         if (edges[adjacentSide].presentButInvisible())
1214             return false;
1215
1216         if (!edgesShareColor(edges[side], edges[adjacentSide]) && edges[adjacentSide].color.hasAlpha())
1217             return false;
1218         
1219         if (!borderStyleFillsBorderArea(edges[adjacentSide].style))
1220             return false;
1221
1222         return true;
1223
1224     case BSLeft:
1225     case BSRight:
1226         // These draw last, so are never overdrawn.
1227         return false;
1228     }
1229     return false;
1230 }
1231
1232 static inline bool borderStylesRequireMitre(BoxSide side, BoxSide adjacentSide, EBorderStyle style, EBorderStyle adjacentStyle)
1233 {
1234     if (style == DOUBLE || adjacentStyle == DOUBLE || adjacentStyle == GROOVE || adjacentStyle == RIDGE)
1235         return true;
1236
1237     if (borderStyleIsDottedOrDashed(style) != borderStyleIsDottedOrDashed(adjacentStyle))
1238         return true;
1239
1240     if (style != adjacentStyle)
1241         return true;
1242
1243     return borderStyleHasUnmatchedColorsAtCorner(style, side, adjacentSide);
1244 }
1245
1246 static bool joinRequiresMitre(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[], bool allowOverdraw)
1247 {
1248     if ((edges[side].isTransparent && edges[adjacentSide].isTransparent) || !edges[adjacentSide].isPresent)
1249         return false;
1250
1251     if (allowOverdraw && willBeOverdrawn(side, adjacentSide, edges))
1252         return false;
1253
1254     if (!edgesShareColor(edges[side], edges[adjacentSide]))
1255         return true;
1256
1257     if (borderStylesRequireMitre(side, adjacentSide, edges[side].style, edges[adjacentSide].style))
1258         return true;
1259     
1260     return false;
1261 }
1262
1263 void RenderBoxModelObject::paintOneBorderSide(GraphicsContext* graphicsContext, const RenderStyle* style, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
1264     const IntRect& sideRect, BoxSide side, BoxSide adjacentSide1, BoxSide adjacentSide2, const BorderEdge edges[], const Path* path, 
1265     BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias, const Color* overrideColor)
1266 {
1267     const BorderEdge& edgeToRender = edges[side];
1268     const BorderEdge& adjacentEdge1 = edges[adjacentSide1];
1269     const BorderEdge& adjacentEdge2 = edges[adjacentSide2];
1270
1271     bool mitreAdjacentSide1 = joinRequiresMitre(side, adjacentSide1, edges, !antialias);
1272     bool mitreAdjacentSide2 = joinRequiresMitre(side, adjacentSide2, edges, !antialias);
1273     
1274     bool adjacentSide1StylesMatch = colorsMatchAtCorner(side, adjacentSide1, edges);
1275     bool adjacentSide2StylesMatch = colorsMatchAtCorner(side, adjacentSide2, edges);
1276
1277     const Color& colorToPaint = overrideColor ? *overrideColor : edgeToRender.color;
1278
1279     if (path) {
1280         GraphicsContextStateSaver stateSaver(*graphicsContext);
1281         clipBorderSidePolygon(graphicsContext, outerBorder, innerBorder, side, adjacentSide1StylesMatch, adjacentSide2StylesMatch);
1282         float thickness = max(max(edgeToRender.width, adjacentEdge1.width), adjacentEdge2.width);
1283         drawBoxSideFromPath(graphicsContext, outerBorder.rect(), *path, edges, edgeToRender.width, thickness, side, style,
1284             colorToPaint, edgeToRender.style, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
1285     } else {
1286         bool shouldClip = styleRequiresClipPolygon(edgeToRender.style) && (mitreAdjacentSide1 || mitreAdjacentSide2);
1287         
1288         GraphicsContextStateSaver clipStateSaver(*graphicsContext, shouldClip);
1289         if (shouldClip) {
1290             clipBorderSidePolygon(graphicsContext, outerBorder, innerBorder, side, !mitreAdjacentSide1, !mitreAdjacentSide2);
1291             // Since we clipped, no need to draw with a mitre.
1292             mitreAdjacentSide1 = false;
1293             mitreAdjacentSide2 = false;
1294         }
1295         
1296         drawLineForBoxSide(graphicsContext, sideRect.x(), sideRect.y(), sideRect.maxX(), sideRect.maxY(), side, colorToPaint, edgeToRender.style,
1297                 mitreAdjacentSide1 ? adjacentEdge1.width : 0, mitreAdjacentSide2 ? adjacentEdge2.width : 0, antialias);
1298     }
1299 }
1300
1301 void RenderBoxModelObject::paintBorderSides(GraphicsContext* graphicsContext, const RenderStyle* style, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
1302                                             const BorderEdge edges[], BorderEdgeFlags edgeSet, BackgroundBleedAvoidance bleedAvoidance,
1303                                             bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias, const Color* overrideColor)
1304 {
1305     bool renderRadii = outerBorder.isRounded();
1306
1307     Path roundedPath;
1308     if (renderRadii)
1309         roundedPath.addRoundedRect(outerBorder);
1310     
1311     if (edges[BSTop].shouldRender() && includesEdge(edgeSet, BSTop)) {
1312         LayoutRect sideRect = outerBorder.rect();
1313         sideRect.setHeight(edges[BSTop].width);
1314
1315         bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSTop].style) || borderWillArcInnerEdge(innerBorder.radii().topLeft(), innerBorder.radii().topRight()));
1316         paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSTop, BSLeft, BSRight, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1317     }
1318
1319     if (edges[BSBottom].shouldRender() && includesEdge(edgeSet, BSBottom)) {
1320         LayoutRect sideRect = outerBorder.rect();
1321         sideRect.shiftYEdgeTo(sideRect.maxY() - edges[BSBottom].width);
1322
1323         bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSBottom].style) || borderWillArcInnerEdge(innerBorder.radii().bottomLeft(), innerBorder.radii().bottomRight()));
1324         paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSBottom, BSLeft, BSRight, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1325     }
1326
1327     if (edges[BSLeft].shouldRender() && includesEdge(edgeSet, BSLeft)) {
1328         LayoutRect sideRect = outerBorder.rect();
1329         sideRect.setWidth(edges[BSLeft].width);
1330
1331         bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSLeft].style) || borderWillArcInnerEdge(innerBorder.radii().bottomLeft(), innerBorder.radii().topLeft()));
1332         paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSLeft, BSTop, BSBottom, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1333     }
1334
1335     if (edges[BSRight].shouldRender() && includesEdge(edgeSet, BSRight)) {
1336         LayoutRect sideRect = outerBorder.rect();
1337         sideRect.shiftXEdgeTo(sideRect.maxX() - edges[BSRight].width);
1338
1339         bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSRight].style) || borderWillArcInnerEdge(innerBorder.radii().bottomRight(), innerBorder.radii().topRight()));
1340         paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSRight, BSTop, BSBottom, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1341     }
1342 }
1343
1344 void RenderBoxModelObject::paintTranslucentBorderSides(GraphicsContext* graphicsContext, const RenderStyle* style, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
1345                                                        const BorderEdge edges[], BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias)
1346 {
1347     BorderEdgeFlags edgesToDraw = AllBorderEdges;
1348     while (edgesToDraw) {
1349         // Find undrawn edges sharing a color.
1350         Color commonColor;
1351         
1352         BorderEdgeFlags commonColorEdgeSet = 0;
1353         for (int i = BSTop; i <= BSLeft; ++i) {
1354             BoxSide currSide = static_cast<BoxSide>(i);
1355             if (!includesEdge(edgesToDraw, currSide))
1356                 continue;
1357
1358             bool includeEdge;
1359             if (!commonColorEdgeSet) {
1360                 commonColor = edges[currSide].color;
1361                 includeEdge = true;
1362             } else
1363                 includeEdge = edges[currSide].color == commonColor;
1364
1365             if (includeEdge)
1366                 commonColorEdgeSet |= edgeFlagForSide(currSide);
1367         }
1368
1369         bool useTransparencyLayer = commonColor.hasAlpha();
1370         if (useTransparencyLayer) {
1371             graphicsContext->beginTransparencyLayer(static_cast<float>(commonColor.alpha()) / 255);
1372             commonColor = Color(commonColor.red(), commonColor.green(), commonColor.blue());
1373         }
1374
1375         paintBorderSides(graphicsContext, style, outerBorder, innerBorder, edges, commonColorEdgeSet, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, &commonColor);
1376             
1377         if (useTransparencyLayer)
1378             graphicsContext->endTransparencyLayer();
1379         
1380         edgesToDraw &= ~commonColorEdgeSet;
1381     }
1382 }
1383
1384 static void unroundClippedCorners(RoundedRect& border, const LayoutRect& clipRect)
1385 {
1386     LayoutRect boundingRect = border.rect();
1387     if (!border.isRounded() || clipRect.contains(boundingRect))
1388         return;
1389
1390     RoundedRect::Radii adjustedRadii = border.radii();
1391     bool didAdjustRadii = false;
1392
1393     LayoutRect topLeftRect(boundingRect.location(), adjustedRadii.topLeft());
1394     if (!clipRect.intersects(topLeftRect)) {
1395         adjustedRadii.setTopLeft(IntSize());
1396         didAdjustRadii = true;
1397     }
1398
1399     LayoutRect topRightRect(boundingRect.location(), adjustedRadii.topRight());
1400     topRightRect.setX(boundingRect.maxX() - topRightRect.width());
1401     if (!clipRect.intersects(topRightRect)) {
1402         adjustedRadii.setTopRight(IntSize());
1403         didAdjustRadii = true;
1404     }
1405
1406     LayoutRect bottomLeftRect(boundingRect.location(), adjustedRadii.bottomLeft());
1407     bottomLeftRect.setY(boundingRect.maxY() - bottomLeftRect.height());
1408     if (!clipRect.intersects(bottomLeftRect)) {
1409         adjustedRadii.setBottomLeft(IntSize());
1410         didAdjustRadii = true;
1411     }
1412
1413     LayoutRect bottomRightRect(boundingRect.location(), adjustedRadii.bottomRight());
1414     bottomRightRect.setX(boundingRect.maxX() - bottomRightRect.width());
1415     bottomRightRect.setY(boundingRect.maxY() - bottomRightRect.height());
1416     if (!clipRect.intersects(bottomRightRect)) {
1417         adjustedRadii.setBottomRight(IntSize());
1418         didAdjustRadii = true;
1419     }
1420
1421     if (didAdjustRadii)
1422         border.setRadii(adjustedRadii);
1423 }
1424
1425 void RenderBoxModelObject::paintBorder(const PaintInfo& info, const IntRect& rect, const RenderStyle* style,
1426                                        BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
1427 {
1428     GraphicsContext* graphicsContext = info.context;
1429     // border-image is not affected by border-radius.
1430     if (paintNinePieceImage(graphicsContext, rect, style, style->borderImage()))
1431         return;
1432
1433     if (graphicsContext->paintingDisabled())
1434         return;
1435
1436     BorderEdge edges[4];
1437     getBorderEdgeInfo(edges, includeLogicalLeftEdge, includeLogicalRightEdge);
1438
1439     RoundedRect outerBorder = style->getRoundedBorderFor(rect, includeLogicalLeftEdge, includeLogicalRightEdge);
1440     RoundedRect innerBorder = style->getRoundedInnerBorderFor(rect, includeLogicalLeftEdge, includeLogicalRightEdge);
1441
1442     const AffineTransform& currentCTM = graphicsContext->getCTM();
1443     // FIXME: this isn't quite correct. We may want to antialias when scaled by a non-integral value, or when the translation is non-integral.
1444     bool antialias = !currentCTM.isIdentityOrTranslationOrFlipped();
1445     
1446     bool haveAlphaColor = false;
1447     bool haveAllSolidEdges = true;
1448     bool allEdgesVisible = true;
1449     bool allEdgesShareColor = true;
1450     int firstVisibleEdge = -1;
1451
1452     for (int i = BSTop; i <= BSLeft; ++i) {
1453         const BorderEdge& currEdge = edges[i];
1454         if (currEdge.presentButInvisible()) {
1455             allEdgesVisible = false;
1456             continue;
1457         }
1458         
1459         if (!currEdge.width) {
1460             allEdgesVisible = false;
1461             continue;
1462         }
1463
1464         if (firstVisibleEdge == -1)
1465             firstVisibleEdge = i;
1466         else if (currEdge.color != edges[firstVisibleEdge].color)
1467             allEdgesShareColor = false;
1468
1469         if (currEdge.color.hasAlpha())
1470             haveAlphaColor = true;
1471         
1472         if (currEdge.style != SOLID)
1473             haveAllSolidEdges = false;
1474     }
1475
1476     // If one of the corners falls outside the clip region, pretend it has no
1477     // radius to improve performance.
1478     if (haveAllSolidEdges)
1479         unroundClippedCorners(outerBorder, info.rect);
1480
1481     // isRenderable() check avoids issue described in https://bugs.webkit.org/show_bug.cgi?id=38787
1482     if (haveAllSolidEdges && allEdgesVisible && allEdgesShareColor && innerBorder.isRenderable()) {
1483         // Fast path for drawing all solid edges.
1484         if (outerBorder.isRounded() || haveAlphaColor) {
1485             Path path;
1486             
1487             if (outerBorder.isRounded() && bleedAvoidance != BackgroundBleedUseTransparencyLayer)
1488                 path.addRoundedRect(outerBorder);
1489             else
1490                 path.addRect(outerBorder.rect());
1491
1492             if (innerBorder.isRounded())
1493                 path.addRoundedRect(innerBorder);
1494             else
1495                 path.addRect(innerBorder.rect());
1496             
1497             graphicsContext->setFillRule(RULE_EVENODD);
1498             graphicsContext->setFillColor(edges[firstVisibleEdge].color, style->colorSpace());
1499             graphicsContext->fillPath(path);
1500         } else
1501             paintBorderSides(graphicsContext, style, outerBorder, innerBorder, edges, AllBorderEdges, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias);
1502     
1503         return;
1504     }
1505
1506     bool clipToOuterBorder = outerBorder.isRounded();
1507     GraphicsContextStateSaver stateSaver(*graphicsContext, clipToOuterBorder);
1508     if (clipToOuterBorder) {
1509         // Clip to the inner and outer radii rects.
1510         if (bleedAvoidance != BackgroundBleedUseTransparencyLayer)
1511             graphicsContext->addRoundedRectClip(outerBorder);
1512         graphicsContext->clipOutRoundedRect(innerBorder);
1513     }
1514
1515     if (haveAlphaColor)
1516         paintTranslucentBorderSides(graphicsContext, style, outerBorder, innerBorder, edges, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias);
1517     else
1518         paintBorderSides(graphicsContext, style, outerBorder, innerBorder, edges, AllBorderEdges, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias);
1519 }
1520
1521 void RenderBoxModelObject::drawBoxSideFromPath(GraphicsContext* graphicsContext, const IntRect& borderRect, const Path& borderPath, const BorderEdge edges[],
1522                                     float thickness, float drawThickness, BoxSide side, const RenderStyle* style, 
1523                                     Color color, EBorderStyle borderStyle, BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
1524 {
1525     if (thickness <= 0)
1526         return;
1527
1528     if (borderStyle == DOUBLE && thickness < 3)
1529         borderStyle = SOLID;
1530
1531     switch (borderStyle) {
1532     case BNONE:
1533     case BHIDDEN:
1534         return;
1535     case DOTTED:
1536     case DASHED: {
1537         graphicsContext->setStrokeColor(color, style->colorSpace());
1538
1539         // The stroke is doubled here because the provided path is the 
1540         // outside edge of the border so half the stroke is clipped off. 
1541         // The extra multiplier is so that the clipping mask can antialias
1542         // the edges to prevent jaggies.
1543         graphicsContext->setStrokeThickness(drawThickness * 2 * 1.1f);
1544         graphicsContext->setStrokeStyle(borderStyle == DASHED ? DashedStroke : DottedStroke);
1545
1546         // If the number of dashes that fit in the path is odd and non-integral then we
1547         // will have an awkwardly-sized dash at the end of the path. To try to avoid that
1548         // here, we simply make the whitespace dashes ever so slightly bigger.
1549         // FIXME: This could be even better if we tried to manipulate the dash offset
1550         // and possibly the gapLength to get the corners dash-symmetrical.
1551         float dashLength = thickness * ((borderStyle == DASHED) ? 3.0f : 1.0f);
1552         float gapLength = dashLength;
1553         float numberOfDashes = borderPath.length() / dashLength;
1554         // Don't try to show dashes if we have less than 2 dashes + 2 gaps.
1555         // FIXME: should do this test per side.
1556         if (numberOfDashes >= 4) {
1557             bool evenNumberOfFullDashes = !((int)numberOfDashes % 2);
1558             bool integralNumberOfDashes = !(numberOfDashes - (int)numberOfDashes);
1559             if (!evenNumberOfFullDashes && !integralNumberOfDashes) {
1560                 float numberOfGaps = numberOfDashes / 2;
1561                 gapLength += (dashLength  / numberOfGaps);
1562             }
1563
1564             DashArray lineDash;
1565             lineDash.append(dashLength);
1566             lineDash.append(gapLength);
1567             graphicsContext->setLineDash(lineDash, dashLength);
1568         }
1569         
1570         // FIXME: stroking the border path causes issues with tight corners:
1571         // https://bugs.webkit.org/show_bug.cgi?id=58711
1572         // Also, to get the best appearance we should stroke a path between the two borders.
1573         graphicsContext->strokePath(borderPath);
1574         return;
1575     }
1576     case DOUBLE: {
1577         // Get the inner border rects for both the outer border line and the inner border line
1578         int outerBorderTopWidth;
1579         int innerBorderTopWidth;
1580         edges[BSTop].getDoubleBorderStripeWidths(outerBorderTopWidth, innerBorderTopWidth);
1581
1582         int outerBorderRightWidth;
1583         int innerBorderRightWidth;
1584         edges[BSRight].getDoubleBorderStripeWidths(outerBorderRightWidth, innerBorderRightWidth);
1585
1586         int outerBorderBottomWidth;
1587         int innerBorderBottomWidth;
1588         edges[BSBottom].getDoubleBorderStripeWidths(outerBorderBottomWidth, innerBorderBottomWidth);
1589
1590         int outerBorderLeftWidth;
1591         int innerBorderLeftWidth;
1592         edges[BSLeft].getDoubleBorderStripeWidths(outerBorderLeftWidth, innerBorderLeftWidth);
1593
1594         // Draw inner border line
1595         {
1596             GraphicsContextStateSaver stateSaver(*graphicsContext);
1597             RoundedRect innerClip = style->getRoundedInnerBorderFor(borderRect,
1598                 innerBorderTopWidth, innerBorderBottomWidth, innerBorderLeftWidth, innerBorderRightWidth,
1599                 includeLogicalLeftEdge, includeLogicalRightEdge);
1600             
1601             graphicsContext->addRoundedRectClip(innerClip);
1602             drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, SOLID, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
1603         }
1604
1605         // Draw outer border line
1606         {
1607             GraphicsContextStateSaver stateSaver(*graphicsContext);
1608             IntRect outerRect = borderRect;
1609             if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
1610                 outerRect.inflate(1);
1611                 ++outerBorderTopWidth;
1612                 ++outerBorderBottomWidth;
1613                 ++outerBorderLeftWidth;
1614                 ++outerBorderRightWidth;
1615             }
1616                 
1617             RoundedRect outerClip = style->getRoundedInnerBorderFor(outerRect,
1618                 outerBorderTopWidth, outerBorderBottomWidth, outerBorderLeftWidth, outerBorderRightWidth,
1619                 includeLogicalLeftEdge, includeLogicalRightEdge);
1620             graphicsContext->clipOutRoundedRect(outerClip);
1621             drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, SOLID, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
1622         }
1623         return;
1624     }
1625     case RIDGE:
1626     case GROOVE:
1627     {
1628         EBorderStyle s1;
1629         EBorderStyle s2;
1630         if (borderStyle == GROOVE) {
1631             s1 = INSET;
1632             s2 = OUTSET;
1633         } else {
1634             s1 = OUTSET;
1635             s2 = INSET;
1636         }
1637         
1638         // Paint full border
1639         drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, s1, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
1640
1641         // Paint inner only
1642         GraphicsContextStateSaver stateSaver(*graphicsContext);
1643         LayoutUnit topWidth = edges[BSTop].usedWidth() / 2;
1644         LayoutUnit bottomWidth = edges[BSBottom].usedWidth() / 2;
1645         LayoutUnit leftWidth = edges[BSLeft].usedWidth() / 2;
1646         LayoutUnit rightWidth = edges[BSRight].usedWidth() / 2;
1647
1648         RoundedRect clipRect = style->getRoundedInnerBorderFor(borderRect,
1649             topWidth, bottomWidth, leftWidth, rightWidth,
1650             includeLogicalLeftEdge, includeLogicalRightEdge);
1651
1652         graphicsContext->addRoundedRectClip(clipRect);
1653         drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, s2, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
1654         return;
1655     }
1656     case INSET:
1657         if (side == BSTop || side == BSLeft)
1658             color = color.dark();
1659         break;
1660     case OUTSET:
1661         if (side == BSBottom || side == BSRight)
1662             color = color.dark();
1663         break;
1664     default:
1665         break;
1666     }
1667
1668     graphicsContext->setStrokeStyle(NoStroke);
1669     graphicsContext->setFillColor(color, style->colorSpace());
1670     graphicsContext->drawRect(borderRect);
1671 }
1672 #else
1673 void RenderBoxModelObject::paintBorder(const PaintInfo& info, const IntRect& rect, const RenderStyle* style,
1674                                        BackgroundBleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
1675 {
1676     GraphicsContext* graphicsContext = info.context;
1677     // FIXME: This old version of paintBorder should be removed when all ports implement 
1678     // GraphicsContext::clipConvexPolygon()!! This should happen soon.
1679     if (paintNinePieceImage(graphicsContext, rect, style, style->borderImage()))
1680         return;
1681
1682     const Color& topColor = style->visitedDependentColor(CSSPropertyBorderTopColor);
1683     const Color& bottomColor = style->visitedDependentColor(CSSPropertyBorderBottomColor);
1684     const Color& leftColor = style->visitedDependentColor(CSSPropertyBorderLeftColor);
1685     const Color& rightColor = style->visitedDependentColor(CSSPropertyBorderRightColor);
1686
1687     bool topTransparent = style->borderTopIsTransparent();
1688     bool bottomTransparent = style->borderBottomIsTransparent();
1689     bool rightTransparent = style->borderRightIsTransparent();
1690     bool leftTransparent = style->borderLeftIsTransparent();
1691
1692     EBorderStyle topStyle = style->borderTopStyle();
1693     EBorderStyle bottomStyle = style->borderBottomStyle();
1694     EBorderStyle leftStyle = style->borderLeftStyle();
1695     EBorderStyle rightStyle = style->borderRightStyle();
1696
1697     bool horizontal = style->isHorizontalWritingMode();
1698     bool renderTop = topStyle > BHIDDEN && !topTransparent && (horizontal || includeLogicalLeftEdge);
1699     bool renderLeft = leftStyle > BHIDDEN && !leftTransparent && (!horizontal || includeLogicalLeftEdge);
1700     bool renderRight = rightStyle > BHIDDEN && !rightTransparent && (!horizontal || includeLogicalRightEdge);
1701     bool renderBottom = bottomStyle > BHIDDEN && !bottomTransparent && (horizontal || includeLogicalRightEdge);
1702
1703
1704     RoundedRect border(rect);
1705     
1706     GraphicsContextStateSaver stateSaver(*graphicsContext, false);
1707     if (style->hasBorderRadius()) {
1708         border.includeLogicalEdges(style->getRoundedBorderFor(border.rect()).radii(),
1709                                    horizontal, includeLogicalLeftEdge, includeLogicalRightEdge);
1710         if (border.isRounded()) {
1711             stateSaver.save();
1712             graphicsContext->addRoundedRectClip(border);
1713         }
1714     }
1715
1716     int firstAngleStart, secondAngleStart, firstAngleSpan, secondAngleSpan;
1717     float thickness;
1718     bool renderRadii = border.isRounded();
1719     bool upperLeftBorderStylesMatch = renderLeft && (topStyle == leftStyle) && (topColor == leftColor);
1720     bool upperRightBorderStylesMatch = renderRight && (topStyle == rightStyle) && (topColor == rightColor) && (topStyle != OUTSET) && (topStyle != RIDGE) && (topStyle != INSET) && (topStyle != GROOVE);
1721     bool lowerLeftBorderStylesMatch = renderLeft && (bottomStyle == leftStyle) && (bottomColor == leftColor) && (bottomStyle != OUTSET) && (bottomStyle != RIDGE) && (bottomStyle != INSET) && (bottomStyle != GROOVE);
1722     bool lowerRightBorderStylesMatch = renderRight && (bottomStyle == rightStyle) && (bottomColor == rightColor);
1723
1724     if (renderTop) {
1725         bool ignoreLeft = (renderRadii && border.radii().topLeft().width() > 0)
1726             || (topColor == leftColor && topTransparent == leftTransparent && topStyle >= OUTSET
1727                 && (leftStyle == DOTTED || leftStyle == DASHED || leftStyle == SOLID || leftStyle == OUTSET));
1728         
1729         bool ignoreRight = (renderRadii && border.radii().topRight().width() > 0)
1730             || (topColor == rightColor && topTransparent == rightTransparent && topStyle >= OUTSET
1731                 && (rightStyle == DOTTED || rightStyle == DASHED || rightStyle == SOLID || rightStyle == INSET));
1732
1733         int x = rect.x();
1734         int x2 = rect.maxX();
1735         if (renderRadii) {
1736             x += border.radii().topLeft().width();
1737             x2 -= border.radii().topRight().width();
1738         }
1739
1740         drawLineForBoxSide(graphicsContext, x, rect.y(), x2, rect.y() + style->borderTopWidth(), BSTop, topColor, topStyle,
1741                    ignoreLeft ? 0 : style->borderLeftWidth(), ignoreRight ? 0 : style->borderRightWidth());
1742
1743         if (renderRadii) {
1744             int leftY = rect.y();
1745
1746             // We make the arc double thick and let the clip rect take care of clipping the extra off.
1747             // We're doing this because it doesn't seem possible to match the curve of the clip exactly
1748             // with the arc-drawing function.
1749             thickness = style->borderTopWidth() * 2;
1750
1751             if (border.radii().topLeft().width()) {
1752                 int leftX = rect.x();
1753                 // The inner clip clips inside the arc. This is especially important for 1px borders.
1754                 bool applyLeftInnerClip = (style->borderLeftWidth() < border.radii().topLeft().width())
1755                     && (style->borderTopWidth() < border.radii().topLeft().height())
1756                     && (topStyle != DOUBLE || style->borderTopWidth() > 6);
1757                 
1758                 GraphicsContextStateSaver stateSaver(*graphicsContext, applyLeftInnerClip);
1759                 if (applyLeftInnerClip)
1760                     graphicsContext->addInnerRoundedRectClip(IntRect(leftX, leftY, border.radii().topLeft().width() * 2, border.radii().topLeft().height() * 2),
1761                                                              style->borderTopWidth());
1762
1763                 firstAngleStart = 90;
1764                 firstAngleSpan = upperLeftBorderStylesMatch ? 90 : 45;
1765
1766                 // Draw upper left arc
1767                 drawArcForBoxSide(graphicsContext, leftX, leftY, thickness, border.radii().topLeft(), firstAngleStart, firstAngleSpan,
1768                               BSTop, topColor, topStyle, true);
1769             }
1770
1771             if (border.radii().topRight().width()) {
1772                 int rightX = rect.maxX() - border.radii().topRight().width() * 2;
1773                 bool applyRightInnerClip = (style->borderRightWidth() < border.radii().topRight().width())
1774                     && (style->borderTopWidth() < border.radii().topRight().height())
1775                     && (topStyle != DOUBLE || style->borderTopWidth() > 6);
1776
1777                 GraphicsContextStateSaver stateSaver(*graphicsContext, applyRightInnerClip);
1778                 if (applyRightInnerClip)
1779                     graphicsContext->addInnerRoundedRectClip(IntRect(rightX, leftY, border.radii().topRight().width() * 2, border.radii().topRight().height() * 2),
1780                                                              style->borderTopWidth());
1781
1782                 if (upperRightBorderStylesMatch) {
1783                     secondAngleStart = 0;
1784                     secondAngleSpan = 90;
1785                 } else {
1786                     secondAngleStart = 45;
1787                     secondAngleSpan = 45;
1788                 }
1789
1790                 // Draw upper right arc
1791                 drawArcForBoxSide(graphicsContext, rightX, leftY, thickness, border.radii().topRight(), secondAngleStart, secondAngleSpan,
1792                               BSTop, topColor, topStyle, false);
1793             }
1794         }
1795     }
1796
1797     if (renderBottom) {
1798         bool ignoreLeft = (renderRadii && border.radii().bottomLeft().width() > 0)
1799             || (bottomColor == leftColor && bottomTransparent == leftTransparent && bottomStyle >= OUTSET
1800                 && (leftStyle == DOTTED || leftStyle == DASHED || leftStyle == SOLID || leftStyle == OUTSET));
1801
1802         bool ignoreRight = (renderRadii && border.radii().bottomRight().width() > 0)
1803             || (bottomColor == rightColor && bottomTransparent == rightTransparent && bottomStyle >= OUTSET
1804                 && (rightStyle == DOTTED || rightStyle == DASHED || rightStyle == SOLID || rightStyle == INSET));
1805
1806         int x = rect.x();
1807         int x2 = rect.maxX();
1808         if (renderRadii) {
1809             x += border.radii().bottomLeft().width();
1810             x2 -= border.radii().bottomRight().width();
1811         }
1812
1813         drawLineForBoxSide(graphicsContext, x, rect.maxY() - style->borderBottomWidth(), x2, rect.maxY(), BSBottom, bottomColor, bottomStyle,
1814                    ignoreLeft ? 0 : style->borderLeftWidth(), ignoreRight ? 0 : style->borderRightWidth());
1815
1816         if (renderRadii) {
1817             thickness = style->borderBottomWidth() * 2;
1818
1819             if (border.radii().bottomLeft().width()) {
1820                 int leftX = rect.x();
1821                 int leftY = rect.maxY() - border.radii().bottomLeft().height() * 2;
1822                 bool applyLeftInnerClip = (style->borderLeftWidth() < border.radii().bottomLeft().width())
1823                     && (style->borderBottomWidth() < border.radii().bottomLeft().height())
1824                     && (bottomStyle != DOUBLE || style->borderBottomWidth() > 6);
1825
1826                 GraphicsContextStateSaver stateSaver(*graphicsContext, applyLeftInnerClip);
1827                 if (applyLeftInnerClip)
1828                     graphicsContext->addInnerRoundedRectClip(IntRect(leftX, leftY, border.radii().bottomLeft().width() * 2, border.radii().bottomLeft().height() * 2),
1829                                                              style->borderBottomWidth());
1830
1831                 if (lowerLeftBorderStylesMatch) {
1832                     firstAngleStart = 180;
1833                     firstAngleSpan = 90;
1834                 } else {
1835                     firstAngleStart = 225;
1836                     firstAngleSpan = 45;
1837                 }
1838
1839                 // Draw lower left arc
1840                 drawArcForBoxSide(graphicsContext, leftX, leftY, thickness, border.radii().bottomLeft(), firstAngleStart, firstAngleSpan,
1841                               BSBottom, bottomColor, bottomStyle, true);
1842             }
1843
1844             if (border.radii().bottomRight().width()) {
1845                 int rightY = rect.maxY() - border.radii().bottomRight().height() * 2;
1846                 int rightX = rect.maxX() - border.radii().bottomRight().width() * 2;
1847                 bool applyRightInnerClip = (style->borderRightWidth() < border.radii().bottomRight().width())
1848                     && (style->borderBottomWidth() < border.radii().bottomRight().height())
1849                     && (bottomStyle != DOUBLE || style->borderBottomWidth() > 6);
1850
1851                 GraphicsContextStateSaver stateSaver(*graphicsContext, applyRightInnerClip);
1852                 if (applyRightInnerClip)
1853                     graphicsContext->addInnerRoundedRectClip(IntRect(rightX, rightY, border.radii().bottomRight().width() * 2, border.radii().bottomRight().height() * 2),
1854                                                              style->borderBottomWidth());
1855
1856                 secondAngleStart = 270;
1857                 secondAngleSpan = lowerRightBorderStylesMatch ? 90 : 45;
1858
1859                 // Draw lower right arc
1860                 drawArcForBoxSide(graphicsContext, rightX, rightY, thickness, border.radii().bottomRight(), secondAngleStart, secondAngleSpan,
1861                               BSBottom, bottomColor, bottomStyle, false);
1862             }
1863         }
1864     }
1865
1866     if (renderLeft) {
1867         bool ignoreTop = (renderRadii && border.radii().topLeft().height() > 0)
1868             || (topColor == leftColor && topTransparent == leftTransparent && leftStyle >= OUTSET
1869                 && (topStyle == DOTTED || topStyle == DASHED || topStyle == SOLID || topStyle == OUTSET));
1870
1871         bool ignoreBottom = (renderRadii && border.radii().bottomLeft().height() > 0)
1872             || (bottomColor == leftColor && bottomTransparent == leftTransparent && leftStyle >= OUTSET
1873                 && (bottomStyle == DOTTED || bottomStyle == DASHED || bottomStyle == SOLID || bottomStyle == INSET));
1874
1875         int y = rect.y();
1876         int y2 = rect.maxY();
1877         if (renderRadii) {
1878             y += border.radii().topLeft().height();
1879             y2 -= border.radii().bottomLeft().height();
1880         }
1881
1882         drawLineForBoxSide(graphicsContext, rect.x(), y, rect.x() + style->borderLeftWidth(), y2, BSLeft, leftColor, leftStyle,
1883                    ignoreTop ? 0 : style->borderTopWidth(), ignoreBottom ? 0 : style->borderBottomWidth());
1884
1885         if (renderRadii && (!upperLeftBorderStylesMatch || !lowerLeftBorderStylesMatch)) {
1886             int topX = rect.x();
1887             thickness = style->borderLeftWidth() * 2;
1888
1889             if (!upperLeftBorderStylesMatch && border.radii().topLeft().width()) {
1890                 int topY = rect.y();
1891                 bool applyTopInnerClip = (style->borderLeftWidth() < border.radii().topLeft().width())
1892                     && (style->borderTopWidth() < border.radii().topLeft().height())
1893                     && (leftStyle != DOUBLE || style->borderLeftWidth() > 6);
1894
1895                 GraphicsContextStateSaver stateSaver(*graphicsContext, applyTopInnerClip);
1896                 if (applyTopInnerClip)
1897                     graphicsContext->addInnerRoundedRectClip(IntRect(topX, topY, border.radii().topLeft().width() * 2, border.radii().topLeft().height() * 2),
1898                                                              style->borderLeftWidth());
1899
1900                 firstAngleStart = 135;
1901                 firstAngleSpan = 45;
1902
1903                 // Draw top left arc
1904                 drawArcForBoxSide(graphicsContext, topX, topY, thickness, border.radii().topLeft(), firstAngleStart, firstAngleSpan,
1905                               BSLeft, leftColor, leftStyle, true);
1906             }
1907
1908             if (!lowerLeftBorderStylesMatch && border.radii().bottomLeft().width()) {
1909                 int bottomY = rect.maxY() - border.radii().bottomLeft().height() * 2;
1910                 bool applyBottomInnerClip = (style->borderLeftWidth() < border.radii().bottomLeft().width())
1911                     && (style->borderBottomWidth() < border.radii().bottomLeft().height())
1912                     && (leftStyle != DOUBLE || style->borderLeftWidth() > 6);
1913
1914                 GraphicsContextStateSaver stateSaver(*graphicsContext, applyBottomInnerClip);
1915                 if (applyBottomInnerClip)
1916                     graphicsContext->addInnerRoundedRectClip(IntRect(topX, bottomY, border.radii().bottomLeft().width() * 2, border.radii().bottomLeft().height() * 2),
1917                                                              style->borderLeftWidth());
1918
1919                 secondAngleStart = 180;
1920                 secondAngleSpan = 45;
1921
1922                 // Draw bottom left arc
1923                 drawArcForBoxSide(graphicsContext, topX, bottomY, thickness, border.radii().bottomLeft(), secondAngleStart, secondAngleSpan,
1924                               BSLeft, leftColor, leftStyle, false);
1925             }
1926         }
1927     }
1928
1929     if (renderRight) {
1930         bool ignoreTop = (renderRadii && border.radii().topRight().height() > 0)
1931             || ((topColor == rightColor) && (topTransparent == rightTransparent)
1932                 && (rightStyle >= DOTTED || rightStyle == INSET)
1933                 && (topStyle == DOTTED || topStyle == DASHED || topStyle == SOLID || topStyle == OUTSET));
1934
1935         bool ignoreBottom = (renderRadii && border.radii().bottomRight().height() > 0)
1936             || ((bottomColor == rightColor) && (bottomTransparent == rightTransparent)
1937                 && (rightStyle >= DOTTED || rightStyle == INSET)
1938                 && (bottomStyle == DOTTED || bottomStyle == DASHED || bottomStyle == SOLID || bottomStyle == INSET));
1939
1940         int y = rect.y();
1941         int y2 = rect.maxY();
1942         if (renderRadii) {
1943             y += border.radii().topRight().height();
1944             y2 -= border.radii().bottomRight().height();
1945         }
1946
1947         drawLineForBoxSide(graphicsContext, rect.maxX() - style->borderRightWidth(), y, rect.maxX(), y2, BSRight, rightColor, rightStyle,
1948                    ignoreTop ? 0 : style->borderTopWidth(), ignoreBottom ? 0 : style->borderBottomWidth());
1949
1950         if (renderRadii && (!upperRightBorderStylesMatch || !lowerRightBorderStylesMatch)) {
1951             thickness = style->borderRightWidth() * 2;
1952
1953             if (!upperRightBorderStylesMatch && border.radii().topRight().width()) {
1954                 int topX = rect.maxX() - border.radii().topRight().width() * 2;
1955                 int topY = rect.y();
1956                 bool applyTopInnerClip = (style->borderRightWidth() < border.radii().topRight().width())
1957                     && (style->borderTopWidth() < border.radii().topRight().height())
1958                     && (rightStyle != DOUBLE || style->borderRightWidth() > 6);
1959
1960                 GraphicsContextStateSaver stateSaver(*graphicsContext, applyTopInnerClip);
1961                 if (applyTopInnerClip)
1962                     graphicsContext->addInnerRoundedRectClip(IntRect(topX, topY, border.radii().topRight().width() * 2, border.radii().topRight().height() * 2),
1963                                                              style->borderRightWidth());
1964
1965                 firstAngleStart = 0;
1966                 firstAngleSpan = 45;
1967
1968                 // Draw top right arc
1969                 drawArcForBoxSide(graphicsContext, topX, topY, thickness, border.radii().topRight(), firstAngleStart, firstAngleSpan,
1970                               BSRight, rightColor, rightStyle, true);
1971             }
1972
1973             if (!lowerRightBorderStylesMatch && border.radii().bottomRight().width()) {
1974                 int bottomX = rect.maxX() - border.radii().bottomRight().width() * 2;
1975                 int bottomY = rect.maxY() - border.radii().bottomRight().height() * 2;
1976                 bool applyBottomInnerClip = (style->borderRightWidth() < border.radii().bottomRight().width())
1977                     && (style->borderBottomWidth() < border.radii().bottomRight().height())
1978                     && (rightStyle != DOUBLE || style->borderRightWidth() > 6);
1979
1980                 GraphicsContextStateSaver stateSaver(*graphicsContext, applyBottomInnerClip);
1981                 if (applyBottomInnerClip)
1982                     graphicsContext->addInnerRoundedRectClip(IntRect(bottomX, bottomY, border.radii().bottomRight().width() * 2, border.radii().bottomRight().height() * 2),
1983                                                              style->borderRightWidth());
1984
1985                 secondAngleStart = 315;
1986                 secondAngleSpan = 45;
1987
1988                 // Draw bottom right arc
1989                 drawArcForBoxSide(graphicsContext, bottomX, bottomY, thickness, border.radii().bottomRight(), secondAngleStart, secondAngleSpan,
1990                               BSRight, rightColor, rightStyle, false);
1991             }
1992         }
1993     }
1994 }
1995 #endif
1996
1997 static void findInnerVertex(const FloatPoint& outerCorner, const FloatPoint& innerCorner, const FloatPoint& centerPoint, FloatPoint& result)
1998 {
1999     // If the line between outer and inner corner is towards the horizontal, intersect with a vertical line through the center,
2000     // otherwise with a horizontal line through the center. The points that form this line are arbitrary (we use 0, 100).
2001     // Note that if findIntersection fails, it will leave result untouched.
2002     if (fabs(outerCorner.x() - innerCorner.x()) > fabs(outerCorner.y() - innerCorner.y()))
2003         findIntersection(outerCorner, innerCorner, FloatPoint(centerPoint.x(), 0), FloatPoint(centerPoint.x(), 100), result);
2004     else
2005         findIntersection(outerCorner, innerCorner, FloatPoint(0, centerPoint.y()), FloatPoint(100, centerPoint.y()), result);
2006 }
2007
2008 void RenderBoxModelObject::clipBorderSidePolygon(GraphicsContext* graphicsContext, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
2009                                                  BoxSide side, bool firstEdgeMatches, bool secondEdgeMatches)
2010 {
2011     FloatPoint quad[4];
2012
2013     const IntRect& outerRect = outerBorder.rect();
2014     const IntRect& innerRect = innerBorder.rect();
2015
2016     FloatPoint centerPoint(innerRect.location().x() + static_cast<float>(innerRect.width()) / 2, innerRect.location().y() + static_cast<float>(innerRect.height()) / 2);
2017
2018     // For each side, create a quad that encompasses all parts of that side that may draw,
2019     // including areas inside the innerBorder.
2020     //
2021     //         0----------------3
2022     //       0  \              /  0
2023     //       |\  1----------- 2  /|
2024     //       | 1                1 |   
2025     //       | |                | |
2026     //       | |                | |  
2027     //       | 2                2 |  
2028     //       |/  1------------2  \| 
2029     //       3  /              \  3   
2030     //         0----------------3
2031     //
2032     switch (side) {
2033     case BSTop:
2034         quad[0] = outerRect.minXMinYCorner();
2035         quad[1] = innerRect.minXMinYCorner();
2036         quad[2] = innerRect.maxXMinYCorner();
2037         quad[3] = outerRect.maxXMinYCorner();
2038
2039         if (!innerBorder.radii().topLeft().isZero())
2040             findInnerVertex(outerRect.minXMinYCorner(), innerRect.minXMinYCorner(), centerPoint, quad[1]);
2041
2042         if (!innerBorder.radii().topRight().isZero())
2043             findInnerVertex(outerRect.maxXMinYCorner(), innerRect.maxXMinYCorner(), centerPoint, quad[2]);
2044         break;
2045
2046     case BSLeft:
2047         quad[0] = outerRect.minXMinYCorner();
2048         quad[1] = innerRect.minXMinYCorner();
2049         quad[2] = innerRect.minXMaxYCorner();
2050         quad[3] = outerRect.minXMaxYCorner();
2051
2052         if (!innerBorder.radii().topLeft().isZero())
2053             findInnerVertex(outerRect.minXMinYCorner(), innerRect.minXMinYCorner(), centerPoint, quad[1]);
2054
2055         if (!innerBorder.radii().bottomLeft().isZero())
2056             findInnerVertex(outerRect.minXMaxYCorner(), innerRect.minXMaxYCorner(), centerPoint, quad[2]);
2057         break;
2058
2059     case BSBottom:
2060         quad[0] = outerRect.minXMaxYCorner();
2061         quad[1] = innerRect.minXMaxYCorner();
2062         quad[2] = innerRect.maxXMaxYCorner();
2063         quad[3] = outerRect.maxXMaxYCorner();
2064
2065         if (!innerBorder.radii().bottomLeft().isZero())
2066             findInnerVertex(outerRect.minXMaxYCorner(), innerRect.minXMaxYCorner(), centerPoint, quad[1]);
2067
2068         if (!innerBorder.radii().bottomRight().isZero())
2069             findInnerVertex(outerRect.maxXMaxYCorner(), innerRect.maxXMaxYCorner(), centerPoint, quad[2]);
2070         break;
2071
2072     case BSRight:
2073         quad[0] = outerRect.maxXMinYCorner();
2074         quad[1] = innerRect.maxXMinYCorner();
2075         quad[2] = innerRect.maxXMaxYCorner();
2076         quad[3] = outerRect.maxXMaxYCorner();
2077
2078         if (!innerBorder.radii().topRight().isZero())
2079             findInnerVertex(outerRect.maxXMinYCorner(), innerRect.maxXMinYCorner(), centerPoint, quad[1]);
2080
2081         if (!innerBorder.radii().bottomRight().isZero())
2082             findInnerVertex(outerRect.maxXMaxYCorner(), innerRect.maxXMaxYCorner(), centerPoint, quad[2]);
2083         break;
2084     }
2085
2086     // If the border matches both of its adjacent sides, don't anti-alias the clip, and
2087     // if neither side matches, anti-alias the clip.
2088     if (firstEdgeMatches == secondEdgeMatches) {
2089         graphicsContext->clipConvexPolygon(4, quad, !firstEdgeMatches);
2090         return;
2091     }
2092
2093     // Square off the end which shouldn't be affected by antialiasing, and clip.
2094     FloatPoint firstQuad[4];
2095     firstQuad[0] = quad[0];
2096     firstQuad[1] = quad[1];
2097     firstQuad[2] = side == BSTop || side == BSBottom ? FloatPoint(quad[3].x(), quad[2].y())
2098         : FloatPoint(quad[2].x(), quad[3].y());
2099     firstQuad[3] = quad[3];
2100     graphicsContext->clipConvexPolygon(4, firstQuad, !firstEdgeMatches);
2101
2102     FloatPoint secondQuad[4];
2103     secondQuad[0] = quad[0];
2104     secondQuad[1] = side == BSTop || side == BSBottom ? FloatPoint(quad[0].x(), quad[1].y())
2105         : FloatPoint(quad[1].x(), quad[0].y());
2106     secondQuad[2] = quad[2];
2107     secondQuad[3] = quad[3];
2108     // Antialiasing affects the second side.
2109     graphicsContext->clipConvexPolygon(4, secondQuad, !secondEdgeMatches);
2110 }
2111
2112 void RenderBoxModelObject::getBorderEdgeInfo(BorderEdge edges[], bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
2113 {
2114     const RenderStyle* style = this->style();
2115     bool horizontal = style->isHorizontalWritingMode();
2116
2117     edges[BSTop] = BorderEdge(style->borderTopWidth(),
2118         style->visitedDependentColor(CSSPropertyBorderTopColor),
2119         style->borderTopStyle(),
2120         style->borderTopIsTransparent(),
2121         horizontal || includeLogicalLeftEdge);
2122
2123     edges[BSRight] = BorderEdge(style->borderRightWidth(),
2124         style->visitedDependentColor(CSSPropertyBorderRightColor),
2125         style->borderRightStyle(),
2126         style->borderRightIsTransparent(),
2127         !horizontal || includeLogicalRightEdge);
2128
2129     edges[BSBottom] = BorderEdge(style->borderBottomWidth(),
2130         style->visitedDependentColor(CSSPropertyBorderBottomColor),
2131         style->borderBottomStyle(),
2132         style->borderBottomIsTransparent(),
2133         horizontal || includeLogicalRightEdge);
2134
2135     edges[BSLeft] = BorderEdge(style->borderLeftWidth(),
2136         style->visitedDependentColor(CSSPropertyBorderLeftColor),
2137         style->borderLeftStyle(),
2138         style->borderLeftIsTransparent(),
2139         !horizontal || includeLogicalLeftEdge);
2140 }
2141
2142 bool RenderBoxModelObject::borderObscuresBackgroundEdge(const FloatSize& contextScale) const
2143 {
2144     BorderEdge edges[4];
2145     getBorderEdgeInfo(edges);
2146
2147     for (int i = BSTop; i <= BSLeft; ++i) {
2148         const BorderEdge& currEdge = edges[i];
2149         // FIXME: for vertical text
2150         float axisScale = (i == BSTop || i == BSBottom) ? contextScale.height() : contextScale.width();
2151         if (!currEdge.obscuresBackgroundEdge(axisScale))
2152             return false;
2153     }
2154
2155     return true;
2156 }
2157
2158 bool RenderBoxModelObject::borderObscuresBackground() const
2159 {
2160     if (!style()->hasBorder())
2161         return false;
2162
2163     // Bail if we have any border-image for now. We could look at the image alpha to improve this.
2164     if (style()->borderImage().image())
2165         return false;
2166
2167     BorderEdge edges[4];
2168     getBorderEdgeInfo(edges);
2169
2170     for (int i = BSTop; i <= BSLeft; ++i) {
2171         const BorderEdge& currEdge = edges[i];
2172         if (!currEdge.obscuresBackground())
2173             return false;
2174     }
2175
2176     return true;
2177 }
2178
2179 static inline IntRect areaCastingShadowInHole(const IntRect& holeRect, int shadowBlur, int shadowSpread, const IntSize& shadowOffset)
2180 {
2181     IntRect bounds(holeRect);
2182     
2183     bounds.inflate(shadowBlur);
2184
2185     if (shadowSpread < 0)
2186         bounds.inflate(-shadowSpread);
2187     
2188     IntRect offsetBounds = bounds;
2189     offsetBounds.move(-shadowOffset);
2190     return unionRect(bounds, offsetBounds);
2191 }
2192
2193 void RenderBoxModelObject::paintBoxShadow(GraphicsContext* context, const LayoutRect& paintRect, const RenderStyle* s, ShadowStyle shadowStyle, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
2194 {
2195     // FIXME: Deal with border-image.  Would be great to use border-image as a mask.
2196
2197     if (context->paintingDisabled() || !s->boxShadow())
2198         return;
2199
2200     RoundedRect border = (shadowStyle == Inset) ? s->getRoundedInnerBorderFor(paintRect, includeLogicalLeftEdge, includeLogicalRightEdge)
2201                                                    : s->getRoundedBorderFor(paintRect, includeLogicalLeftEdge, includeLogicalRightEdge);
2202
2203     bool hasBorderRadius = s->hasBorderRadius();
2204     bool isHorizontal = s->isHorizontalWritingMode();
2205     
2206     bool hasOpaqueBackground = s->visitedDependentColor(CSSPropertyBackgroundColor).isValid() && s->visitedDependentColor(CSSPropertyBackgroundColor).alpha() == 255;
2207     for (const ShadowData* shadow = s->boxShadow(); shadow; shadow = shadow->next()) {
2208         if (shadow->style() != shadowStyle)
2209             continue;
2210
2211         LayoutSize shadowOffset(shadow->x(), shadow->y());
2212         LayoutUnit shadowBlur = shadow->blur();
2213         LayoutUnit shadowSpread = shadow->spread();
2214         
2215         if (shadowOffset.isZero() && !shadowBlur && !shadowSpread)
2216             continue;
2217         
2218         const Color& shadowColor = shadow->color();
2219
2220         if (shadow->style() == Normal) {
2221             RoundedRect fillRect = border;
2222             fillRect.inflate(shadowSpread);
2223             if (fillRect.isEmpty())
2224                 continue;
2225
2226             LayoutRect shadowRect(border.rect());
2227             shadowRect.inflate(shadowBlur + shadowSpread);
2228             shadowRect.move(shadowOffset);
2229
2230             GraphicsContextStateSaver stateSaver(*context);
2231             context->clip(shadowRect);
2232
2233             // Move the fill just outside the clip, adding 1 pixel separation so that the fill does not
2234             // bleed in (due to antialiasing) if the context is transformed.
2235             LayoutSize extraOffset(paintRect.width() + max<LayoutUnit>(0, shadowOffset.width()) + shadowBlur + 2 * shadowSpread + 1, 0);
2236             shadowOffset -= extraOffset;
2237             fillRect.move(extraOffset);
2238
2239             if (shadow->isWebkitBoxShadow())
2240                 context->setLegacyShadow(shadowOffset, shadowBlur, shadowColor, s->colorSpace());
2241             else
2242                 context->setShadow(shadowOffset, shadowBlur, shadowColor, s->colorSpace());
2243
2244             if (hasBorderRadius) {
2245                 RoundedRect rectToClipOut = border;
2246
2247                 // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
2248                 // when painting the shadow. On the other hand, it introduces subpixel gaps along the
2249                 // corners. Those are avoided by insetting the clipping path by one pixel.
2250                 if (hasOpaqueBackground) {
2251                     rectToClipOut.inflateWithRadii(-1);
2252                 }
2253
2254                 if (!rectToClipOut.isEmpty())
2255                     context->clipOutRoundedRect(rectToClipOut);
2256
2257                 fillRect.expandRadii(shadowSpread);
2258                 context->fillRoundedRect(fillRect, Color::black, s->colorSpace());
2259             } else {
2260                 LayoutRect rectToClipOut = border.rect();
2261
2262                 // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
2263                 // when painting the shadow. On the other hand, it introduces subpixel gaps along the
2264                 // edges if they are not pixel-aligned. Those are avoided by insetting the clipping path
2265                 // by one pixel.
2266                 if (hasOpaqueBackground) {
2267                     AffineTransform currentTransformation = context->getCTM();
2268                     if (currentTransformation.a() != 1 || (currentTransformation.d() != 1 && currentTransformation.d() != -1)
2269                             || currentTransformation.b() || currentTransformation.c())
2270                         rectToClipOut.inflate(-1);
2271                 }
2272
2273                 if (!rectToClipOut.isEmpty())
2274                     context->clipOut(rectToClipOut);
2275                 context->fillRect(fillRect.rect(), Color::black, s->colorSpace());
2276             }
2277         } else {
2278             // Inset shadow.
2279             LayoutRect holeRect(border.rect());
2280             holeRect.inflate(-shadowSpread);
2281
2282             if (holeRect.isEmpty()) {
2283                 if (hasBorderRadius)
2284                     context->fillRoundedRect(border, shadowColor, s->colorSpace());
2285                 else
2286                     context->fillRect(border.rect(), shadowColor, s->colorSpace());
2287                 continue;
2288             }
2289
2290             if (!includeLogicalLeftEdge) {
2291                 if (isHorizontal) {
2292                     holeRect.move(-max<LayoutUnit>(shadowOffset.width(), 0) - shadowBlur, 0);
2293                     holeRect.setWidth(holeRect.width() + max<LayoutUnit>(shadowOffset.width(), 0) + shadowBlur);
2294                 } else {
2295                     holeRect.move(0, -max<LayoutUnit>(shadowOffset.height(), 0) - shadowBlur);
2296                     holeRect.setHeight(holeRect.height() + max<LayoutUnit>(shadowOffset.height(), 0) + shadowBlur);
2297                 }
2298             }
2299             if (!includeLogicalRightEdge) {
2300                 if (isHorizontal)
2301                     holeRect.setWidth(holeRect.width() - min<LayoutUnit>(shadowOffset.width(), 0) + shadowBlur);
2302                 else
2303                     holeRect.setHeight(holeRect.height() - min<LayoutUnit>(shadowOffset.height(), 0) + shadowBlur);
2304             }
2305
2306             Color fillColor(shadowColor.red(), shadowColor.green(), shadowColor.blue(), 255);
2307
2308             LayoutRect outerRect = areaCastingShadowInHole(border.rect(), shadowBlur, shadowSpread, shadowOffset);
2309             RoundedRect roundedHole(holeRect, border.radii());
2310
2311             GraphicsContextStateSaver stateSaver(*context);
2312             if (hasBorderRadius) {
2313                 Path path;
2314                 path.addRoundedRect(border);
2315                 context->clip(path);
2316                 roundedHole.shrinkRadii(shadowSpread);
2317             } else
2318                 context->clip(border.rect());
2319
2320             LayoutSize extraOffset(2 * paintRect.width() + max<LayoutUnit>(0, shadowOffset.width()) + shadowBlur - 2 * shadowSpread + 1, 0);
2321             context->translate(extraOffset.width(), extraOffset.height());
2322             shadowOffset -= extraOffset;
2323
2324             if (shadow->isWebkitBoxShadow())
2325                 context->setLegacyShadow(shadowOffset, shadowBlur, shadowColor, s->colorSpace());
2326             else
2327                 context->setShadow(shadowOffset, shadowBlur, shadowColor, s->colorSpace());
2328
2329             context->fillRectWithRoundedHole(outerRect, roundedHole, fillColor, s->colorSpace());
2330         }
2331     }
2332 }
2333
2334 int RenderBoxModelObject::containingBlockLogicalWidthForContent() const
2335 {
2336     return containingBlock()->availableLogicalWidth();
2337 }
2338
2339 RenderBoxModelObject* RenderBoxModelObject::continuation() const
2340 {
2341     if (!continuationMap)
2342         return 0;
2343     return continuationMap->get(this);
2344 }
2345
2346 void RenderBoxModelObject::setContinuation(RenderBoxModelObject* continuation)
2347 {
2348     if (continuation) {
2349         if (!continuationMap)
2350             continuationMap = new ContinuationMap;
2351         continuationMap->set(this, continuation);
2352     } else {
2353         if (continuationMap)
2354             continuationMap->remove(this);
2355     }
2356 }
2357
2358 } // namespace WebCore