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