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