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