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