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