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