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