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