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