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