Implement rendering support for the color-filter CSS property
[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->hasOverrideContainingBlockLogicalHeight())
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 & PaintBehaviorSnapshotting)
378         return DecodingMode::Synchronous;
379     if (!settings().largeImageAsyncDecodingEnabled())
380         return DecodingMode::Synchronous;
381     if (!bitmapImage.canUseAsyncDecodingForLargeImages())
382         return DecodingMode::Synchronous;
383     if (paintInfo.paintBehavior & PaintBehaviorTileFirstPaint)
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, PaintPhaseTextClip, PaintBehaviorForceBlackText);
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() == LocalBackgroundAttachment;
753     bool isBorderFill = bgLayer.clip() == BorderFillBox;
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     bool forceBackgroundToWhite = false;
761     if (document().printing()) {
762         if (style().printColorAdjust() == PrintColorAdjustEconomy)
763             forceBackgroundToWhite = true;
764         if (settings().shouldPrintBackgrounds())
765             forceBackgroundToWhite = false;
766     }
767
768     // When printing backgrounds is disabled or using economy mode,
769     // change existing background colors and images to a solid white background.
770     // If there's no bg color or image, leave it untouched to avoid affecting transparency.
771     // We don't try to avoid loading the background images, because this style flag is only set
772     // when printing, and at that point we've already loaded the background images anyway. (To avoid
773     // loading the background images we'd have to do this check when applying styles rather than
774     // while rendering.)
775     if (forceBackgroundToWhite) {
776         // Note that we can't reuse this variable below because the bgColor might be changed
777         bool shouldPaintBackgroundColor = !bgLayer.next() && bgColor.isVisible();
778         if (shouldPaintBackgroundImage || shouldPaintBackgroundColor) {
779             bgColor = Color::white;
780             shouldPaintBackgroundImage = false;
781         }
782     }
783
784     bool baseBgColorOnly = (baseBgColorUsage == BaseBackgroundColorOnly);
785     if (baseBgColorOnly && (!isRoot || bgLayer.next() || bgColor.isOpaque()))
786         return;
787
788     bool colorVisible = bgColor.isVisible();
789     float deviceScaleFactor = document().deviceScaleFactor();
790     FloatRect pixelSnappedRect = snapRectToDevicePixels(rect, deviceScaleFactor);
791
792     // Fast path for drawing simple color backgrounds.
793     if (!isRoot && !clippedWithLocalScrolling && !shouldPaintBackgroundImage && isBorderFill && !bgLayer.next()) {
794         if (!colorVisible)
795             return;
796
797         bool boxShadowShouldBeAppliedToBackground = this->boxShadowShouldBeAppliedToBackground(rect.location(), bleedAvoidance, box);
798         GraphicsContextStateSaver shadowStateSaver(context, boxShadowShouldBeAppliedToBackground);
799         if (boxShadowShouldBeAppliedToBackground)
800             applyBoxShadowForBackground(context, style());
801
802         if (hasRoundedBorder && bleedAvoidance != BackgroundBleedUseTransparencyLayer) {
803             FloatRoundedRect pixelSnappedBorder = backgroundRoundedRectAdjustedForBleedAvoidance(context, rect, bleedAvoidance, box, boxSize,
804                 includeLeftEdge, includeRightEdge).pixelSnappedRoundedRectForPainting(deviceScaleFactor);
805             if (pixelSnappedBorder.isRenderable())
806                 context.fillRoundedRect(pixelSnappedBorder, bgColor);
807             else {
808                 context.save();
809                 clipRoundedInnerRect(context, pixelSnappedRect, pixelSnappedBorder);
810                 context.fillRect(pixelSnappedBorder.rect(), bgColor);
811                 context.restore();
812             }
813         } else
814             context.fillRect(pixelSnappedRect, bgColor);
815
816         return;
817     }
818
819     // BorderFillBox radius clipping is taken care of by BackgroundBleedUseTransparencyLayer
820     bool clipToBorderRadius = hasRoundedBorder && !(isBorderFill && bleedAvoidance == BackgroundBleedUseTransparencyLayer);
821     GraphicsContextStateSaver clipToBorderStateSaver(context, clipToBorderRadius);
822     if (clipToBorderRadius) {
823         RoundedRect border = isBorderFill ? backgroundRoundedRectAdjustedForBleedAvoidance(context, rect, bleedAvoidance, box, boxSize, includeLeftEdge, includeRightEdge) : getBackgroundRoundedRect(rect, box, boxSize.width(), boxSize.height(), includeLeftEdge, includeRightEdge);
824
825         // Clip to the padding or content boxes as necessary.
826         if (bgLayer.clip() == ContentFillBox) {
827             border = style().getRoundedInnerBorderFor(border.rect(),
828                 paddingTop() + borderTop(), paddingBottom() + borderBottom(), paddingLeft() + borderLeft(), paddingRight() + borderRight(), includeLeftEdge, includeRightEdge);
829         } else if (bgLayer.clip() == PaddingFillBox)
830             border = style().getRoundedInnerBorderFor(border.rect(), includeLeftEdge, includeRightEdge);
831
832         clipRoundedInnerRect(context, pixelSnappedRect, border.pixelSnappedRoundedRectForPainting(deviceScaleFactor));
833     }
834     
835     LayoutUnit bLeft = includeLeftEdge ? borderLeft() : LayoutUnit::fromPixel(0);
836     LayoutUnit bRight = includeRightEdge ? borderRight() : LayoutUnit::fromPixel(0);
837     LayoutUnit pLeft = includeLeftEdge ? paddingLeft() : LayoutUnit();
838     LayoutUnit pRight = includeRightEdge ? paddingRight() : LayoutUnit();
839
840     GraphicsContextStateSaver clipWithScrollingStateSaver(context, clippedWithLocalScrolling);
841     LayoutRect scrolledPaintRect = rect;
842     if (clippedWithLocalScrolling) {
843         // Clip to the overflow area.
844         auto& thisBox = downcast<RenderBox>(*this);
845         context.clip(thisBox.overflowClipRect(rect.location()));
846         
847         // Adjust the paint rect to reflect a scrolled content box with borders at the ends.
848         scrolledPaintRect.moveBy(-thisBox.scrollPosition());
849         scrolledPaintRect.setWidth(bLeft + layer()->scrollWidth() + bRight);
850         scrolledPaintRect.setHeight(borderTop() + layer()->scrollHeight() + borderBottom());
851     }
852     
853     GraphicsContextStateSaver backgroundClipStateSaver(context, false);
854     std::unique_ptr<ImageBuffer> maskImage;
855     IntRect maskRect;
856
857     if (bgLayer.clip() == PaddingFillBox || bgLayer.clip() == ContentFillBox) {
858         // Clip to the padding or content boxes as necessary.
859         if (!clipToBorderRadius) {
860             bool includePadding = bgLayer.clip() == ContentFillBox;
861             LayoutRect clipRect = LayoutRect(scrolledPaintRect.x() + bLeft + (includePadding ? pLeft : LayoutUnit()),
862                 scrolledPaintRect.y() + borderTop() + (includePadding ? paddingTop() : LayoutUnit()),
863                 scrolledPaintRect.width() - bLeft - bRight - (includePadding ? pLeft + pRight : LayoutUnit()),
864                 scrolledPaintRect.height() - borderTop() - borderBottom() - (includePadding ? paddingTop() + paddingBottom() : LayoutUnit()));
865             backgroundClipStateSaver.save();
866             context.clip(clipRect);
867         }
868     } else if (bgLayer.clip() == TextFillBox) {
869         // We have to draw our text into a mask that can then be used to clip background drawing.
870         // First figure out how big the mask has to be.  It should be no bigger than what we need
871         // to actually render, so we should intersect the dirty rect with the border box of the background.
872         maskRect = snappedIntRect(rect);
873         maskRect.intersect(snappedIntRect(paintInfo.rect));
874
875         // Now create the mask.
876         maskImage = ImageBuffer::createCompatibleBuffer(maskRect.size(), ColorSpaceSRGB, context);
877         if (!maskImage)
878             return;
879         paintMaskForTextFillBox(maskImage.get(), maskRect, box, scrolledPaintRect);
880
881         // The mask has been created.  Now we just need to clip to it.
882         backgroundClipStateSaver.save();
883         context.clip(maskRect);
884         context.beginTransparencyLayer(1);
885     }
886
887     // Only fill with a base color (e.g., white) if we're the root document, since iframes/frames with
888     // no background in the child document should show the parent's background.
889     bool isOpaqueRoot = false;
890     if (isRoot) {
891         isOpaqueRoot = true;
892         if (!bgLayer.next() && !bgColor.isOpaque()) {
893             HTMLFrameOwnerElement* ownerElement = document().ownerElement();
894             if (ownerElement) {
895                 if (!ownerElement->hasTagName(frameTag)) {
896                     // Locate the <body> element using the DOM.  This is easier than trying
897                     // to crawl around a render tree with potential :before/:after content and
898                     // anonymous blocks created by inline <body> tags etc.  We can locate the <body>
899                     // render object very easily via the DOM.
900                     if (HTMLElement* body = document().bodyOrFrameset()) {
901                         // Can't scroll a frameset document anyway.
902                         isOpaqueRoot = is<HTMLFrameSetElement>(*body);
903                     } else {
904                         // SVG documents and XML documents with SVG root nodes are transparent.
905                         isOpaqueRoot = !document().hasSVGRootNode();
906                     }
907                 }
908             } else
909                 isOpaqueRoot = !view().frameView().isTransparent();
910         }
911         view().frameView().setContentIsOpaque(isOpaqueRoot);
912     }
913
914     // Paint the color first underneath all images, culled if background image occludes it.
915     // FIXME: In the bgLayer.hasFiniteBounds() case, we could improve the culling test
916     // by verifying whether the background image covers the entire layout rect.
917     if (!bgLayer.next()) {
918         LayoutRect backgroundRect(scrolledPaintRect);
919         bool boxShadowShouldBeAppliedToBackground = this->boxShadowShouldBeAppliedToBackground(rect.location(), bleedAvoidance, box);
920         if (boxShadowShouldBeAppliedToBackground || !shouldPaintBackgroundImage || !bgLayer.hasOpaqueImage(*this) || !bgLayer.hasRepeatXY()) {
921             if (!boxShadowShouldBeAppliedToBackground)
922                 backgroundRect.intersect(paintInfo.rect);
923
924             // If we have an alpha and we are painting the root element, blend with the base background color.
925             Color baseColor;
926             bool shouldClearBackground = false;
927             if ((baseBgColorUsage != BaseBackgroundColorSkip) && isOpaqueRoot) {
928                 baseColor = view().frameView().baseBackgroundColor();
929                 if (!baseColor.isVisible())
930                     shouldClearBackground = true;
931             }
932
933             GraphicsContextStateSaver shadowStateSaver(context, boxShadowShouldBeAppliedToBackground);
934             if (boxShadowShouldBeAppliedToBackground)
935                 applyBoxShadowForBackground(context, style());
936
937             FloatRect backgroundRectForPainting = snapRectToDevicePixels(backgroundRect, deviceScaleFactor);
938             if (baseColor.isVisible()) {
939                 if (!baseBgColorOnly && bgColor.isVisible())
940                     baseColor = baseColor.blend(bgColor);
941                 context.fillRect(backgroundRectForPainting, baseColor, CompositeCopy);
942             } else if (!baseBgColorOnly && bgColor.isVisible()) {
943                 auto operation = shouldClearBackground ? CompositeCopy : context.compositeOperation();
944                 context.fillRect(backgroundRectForPainting, bgColor, operation);
945             } else if (shouldClearBackground)
946                 context.clearRect(backgroundRectForPainting);
947         }
948     }
949
950     // no progressive loading of the background image
951     if (!baseBgColorOnly && shouldPaintBackgroundImage) {
952         auto geometry = calculateBackgroundImageGeometry(paintInfo.paintContainer, bgLayer, rect.location(), scrolledPaintRect, backgroundObject);
953         geometry.clip(LayoutRect(pixelSnappedRect));
954         RefPtr<Image> image;
955         if (!geometry.destRect().isEmpty() && (image = bgImage->image(backgroundObject ? backgroundObject : this, geometry.tileSize()))) {
956             auto compositeOp = op == CompositeSourceOver ? bgLayer.composite() : op;
957             context.setDrawLuminanceMask(bgLayer.maskSourceType() == MaskLuminance);
958
959             if (is<BitmapImage>(image))
960                 downcast<BitmapImage>(*image).updateFromSettings(settings());
961
962             auto interpolation = chooseInterpolationQuality(context, *image, &bgLayer, geometry.tileSize());
963             auto decodingMode = decodingModeForImageDraw(*image, paintInfo);
964             auto drawResult = context.drawTiledImage(*image, geometry.destRect(), toLayoutPoint(geometry.relativePhase()), geometry.tileSize(), geometry.spaceSize(), ImagePaintingOptions(compositeOp, bgLayer.blendMode(), decodingMode, ImageOrientationDescription(), interpolation));
965             if (drawResult == ImageDrawResult::DidRequestDecoding) {
966                 ASSERT(bgImage->isCachedImage());
967                 bgImage->cachedImage()->addPendingImageDrawingClient(*this);
968             }
969         }
970     }
971
972     if (maskImage && bgLayer.clip() == TextFillBox) {
973         context.drawConsumingImageBuffer(WTFMove(maskImage), maskRect, CompositeDestinationIn);
974         context.endTransparencyLayer();
975     }
976 }
977
978 static inline LayoutUnit resolveWidthForRatio(LayoutUnit height, const LayoutSize& intrinsicRatio)
979 {
980     return height * intrinsicRatio.width() / intrinsicRatio.height();
981 }
982
983 static inline LayoutUnit resolveHeightForRatio(LayoutUnit width, const LayoutSize& intrinsicRatio)
984 {
985     return width * intrinsicRatio.height() / intrinsicRatio.width();
986 }
987
988 static inline LayoutSize resolveAgainstIntrinsicWidthOrHeightAndRatio(const LayoutSize& size, const LayoutSize& intrinsicRatio, LayoutUnit useWidth, LayoutUnit useHeight)
989 {
990     if (intrinsicRatio.isEmpty()) {
991         if (useWidth)
992             return LayoutSize(useWidth, size.height());
993         return LayoutSize(size.width(), useHeight);
994     }
995
996     if (useWidth)
997         return LayoutSize(useWidth, resolveHeightForRatio(useWidth, intrinsicRatio));
998     return LayoutSize(resolveWidthForRatio(useHeight, intrinsicRatio), useHeight);
999 }
1000
1001 static inline LayoutSize resolveAgainstIntrinsicRatio(const LayoutSize& size, const LayoutSize& intrinsicRatio)
1002 {
1003     // Two possible solutions: (size.width(), solutionHeight) or (solutionWidth, size.height())
1004     // "... must be assumed to be the largest dimensions..." = easiest answer: the rect with the largest surface area.
1005
1006     LayoutUnit solutionWidth = resolveWidthForRatio(size.height(), intrinsicRatio);
1007     LayoutUnit solutionHeight = resolveHeightForRatio(size.width(), intrinsicRatio);
1008     if (solutionWidth <= size.width()) {
1009         if (solutionHeight <= size.height()) {
1010             // If both solutions fit, choose the one covering the larger area.
1011             LayoutUnit areaOne = solutionWidth * size.height();
1012             LayoutUnit areaTwo = size.width() * solutionHeight;
1013             if (areaOne < areaTwo)
1014                 return LayoutSize(size.width(), solutionHeight);
1015             return LayoutSize(solutionWidth, size.height());
1016         }
1017
1018         // Only the first solution fits.
1019         return LayoutSize(solutionWidth, size.height());
1020     }
1021
1022     // Only the second solution fits, assert that.
1023     ASSERT(solutionHeight <= size.height());
1024     return LayoutSize(size.width(), solutionHeight);
1025 }
1026
1027 LayoutSize RenderBoxModelObject::calculateImageIntrinsicDimensions(StyleImage* image, const LayoutSize& positioningAreaSize, ScaleByEffectiveZoomOrNot shouldScaleOrNot) const
1028 {
1029     // A generated image without a fixed size, will always return the container size as intrinsic size.
1030     if (image->isGeneratedImage() && image->usesImageContainerSize())
1031         return LayoutSize(positioningAreaSize.width(), positioningAreaSize.height());
1032
1033     Length intrinsicWidth;
1034     Length intrinsicHeight;
1035     FloatSize intrinsicRatio;
1036     image->computeIntrinsicDimensions(this, intrinsicWidth, intrinsicHeight, intrinsicRatio);
1037
1038     ASSERT(!intrinsicWidth.isPercentOrCalculated());
1039     ASSERT(!intrinsicHeight.isPercentOrCalculated());
1040
1041     LayoutSize resolvedSize(intrinsicWidth.value(), intrinsicHeight.value());
1042     LayoutSize minimumSize(resolvedSize.width() > 0 ? 1 : 0, resolvedSize.height() > 0 ? 1 : 0);
1043
1044     if (shouldScaleOrNot == ScaleByEffectiveZoom)
1045         resolvedSize.scale(style().effectiveZoom());
1046     resolvedSize.clampToMinimumSize(minimumSize);
1047
1048     if (!resolvedSize.isEmpty())
1049         return resolvedSize;
1050
1051     // If the image has one of either an intrinsic width or an intrinsic height:
1052     // * and an intrinsic aspect ratio, then the missing dimension is calculated from the given dimension and the ratio.
1053     // * and no intrinsic aspect ratio, then the missing dimension is assumed to be the size of the rectangle that
1054     //   establishes the coordinate system for the 'background-position' property.
1055     if (resolvedSize.width() > 0 || resolvedSize.height() > 0)
1056         return resolveAgainstIntrinsicWidthOrHeightAndRatio(positioningAreaSize, LayoutSize(intrinsicRatio), resolvedSize.width(), resolvedSize.height());
1057
1058     // If the image has no intrinsic dimensions and has an intrinsic ratio the dimensions must be assumed to be the
1059     // largest dimensions at that ratio such that neither dimension exceeds the dimensions of the rectangle that
1060     // establishes the coordinate system for the 'background-position' property.
1061     if (!intrinsicRatio.isEmpty())
1062         return resolveAgainstIntrinsicRatio(positioningAreaSize, LayoutSize(intrinsicRatio));
1063
1064     // If the image has no intrinsic ratio either, then the dimensions must be assumed to be the rectangle that
1065     // establishes the coordinate system for the 'background-position' property.
1066     return positioningAreaSize;
1067 }
1068
1069 LayoutSize RenderBoxModelObject::calculateFillTileSize(const FillLayer& fillLayer, const LayoutSize& positioningAreaSize) const
1070 {
1071     StyleImage* image = fillLayer.image();
1072     EFillSizeType type = fillLayer.size().type;
1073
1074     LayoutSize imageIntrinsicSize;
1075     if (image) {
1076         imageIntrinsicSize = calculateImageIntrinsicDimensions(image, positioningAreaSize, ScaleByEffectiveZoom);
1077         imageIntrinsicSize.scale(1 / image->imageScaleFactor(), 1 / image->imageScaleFactor());
1078     } else
1079         imageIntrinsicSize = positioningAreaSize;
1080
1081     switch (type) {
1082         case SizeLength: {
1083             LayoutSize tileSize = positioningAreaSize;
1084
1085             Length layerWidth = fillLayer.size().size.width;
1086             Length layerHeight = fillLayer.size().size.height;
1087
1088             if (layerWidth.isFixed())
1089                 tileSize.setWidth(layerWidth.value());
1090             else if (layerWidth.isPercentOrCalculated())
1091                 tileSize.setWidth(valueForLength(layerWidth, positioningAreaSize.width()));
1092             
1093             if (layerHeight.isFixed())
1094                 tileSize.setHeight(layerHeight.value());
1095             else if (layerHeight.isPercentOrCalculated())
1096                 tileSize.setHeight(valueForLength(layerHeight, positioningAreaSize.height()));
1097
1098             // If one of the values is auto we have to use the appropriate
1099             // scale to maintain our aspect ratio.
1100             if (layerWidth.isAuto() && !layerHeight.isAuto()) {
1101                 if (imageIntrinsicSize.height())
1102                     tileSize.setWidth(imageIntrinsicSize.width() * tileSize.height() / imageIntrinsicSize.height());
1103             } else if (!layerWidth.isAuto() && layerHeight.isAuto()) {
1104                 if (imageIntrinsicSize.width())
1105                     tileSize.setHeight(imageIntrinsicSize.height() * tileSize.width() / imageIntrinsicSize.width());
1106             } else if (layerWidth.isAuto() && layerHeight.isAuto()) {
1107                 // If both width and height are auto, use the image's intrinsic size.
1108                 tileSize = imageIntrinsicSize;
1109             }
1110
1111             tileSize.clampNegativeToZero();
1112             return tileSize;
1113         }
1114         case SizeNone: {
1115             // If both values are ‘auto’ then the intrinsic width and/or height of the image should be used, if any.
1116             if (!imageIntrinsicSize.isEmpty())
1117                 return imageIntrinsicSize;
1118
1119             // If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for ‘contain’.
1120             type = Contain;
1121         }
1122         FALLTHROUGH;
1123         case Contain:
1124         case Cover: {
1125             // Scale computation needs higher precision than what LayoutUnit can offer.
1126             FloatSize localImageIntrinsicSize = imageIntrinsicSize;
1127             FloatSize localPositioningAreaSize = positioningAreaSize;
1128
1129             float horizontalScaleFactor = localImageIntrinsicSize.width() ? (localPositioningAreaSize.width() / localImageIntrinsicSize.width()) : 1;
1130             float verticalScaleFactor = localImageIntrinsicSize.height() ? (localPositioningAreaSize.height() / localImageIntrinsicSize.height()) : 1;
1131             float scaleFactor = type == Contain ? std::min(horizontalScaleFactor, verticalScaleFactor) : std::max(horizontalScaleFactor, verticalScaleFactor);
1132             float deviceScaleFactor = document().deviceScaleFactor();
1133             return LayoutSize(std::max<LayoutUnit>(1 / deviceScaleFactor, localImageIntrinsicSize.width() * scaleFactor),
1134                 std::max<LayoutUnit>(1 / deviceScaleFactor, localImageIntrinsicSize.height() * scaleFactor));
1135        }
1136     }
1137
1138     ASSERT_NOT_REACHED();
1139     return LayoutSize();
1140 }
1141
1142 static void pixelSnapBackgroundImageGeometryForPainting(LayoutRect& destinationRect, LayoutSize& tileSize, LayoutSize& phase, LayoutSize& space, float scaleFactor)
1143 {
1144     tileSize = LayoutSize(snapRectToDevicePixels(LayoutRect(destinationRect.location(), tileSize), scaleFactor).size());
1145     phase = LayoutSize(snapRectToDevicePixels(LayoutRect(destinationRect.location(), phase), scaleFactor).size());
1146     space = LayoutSize(snapRectToDevicePixels(LayoutRect(LayoutPoint(), space), scaleFactor).size());
1147     destinationRect = LayoutRect(snapRectToDevicePixels(destinationRect, scaleFactor));
1148 }
1149
1150 bool RenderBoxModelObject::fixedBackgroundPaintsInLocalCoordinates() const
1151 {
1152     if (!isDocumentElementRenderer())
1153         return false;
1154
1155     if (view().frameView().paintBehavior() & PaintBehaviorFlattenCompositingLayers)
1156         return false;
1157
1158     RenderLayer* rootLayer = view().layer();
1159     if (!rootLayer || !rootLayer->isComposited())
1160         return false;
1161
1162     return rootLayer->backing()->backgroundLayerPaintsFixedRootBackground();
1163 }
1164
1165 static inline LayoutUnit getSpace(LayoutUnit areaSize, LayoutUnit tileSize)
1166 {
1167     int numberOfTiles = areaSize / tileSize;
1168     LayoutUnit space = -1;
1169
1170     if (numberOfTiles > 1)
1171         space = (areaSize - numberOfTiles * tileSize) / (numberOfTiles - 1);
1172
1173     return space;
1174 }
1175
1176 static LayoutUnit resolveEdgeRelativeLength(const Length& length, Edge edge, LayoutUnit availableSpace, const LayoutSize& areaSize, const LayoutSize& tileSize)
1177 {
1178     LayoutUnit result = minimumValueForLength(length, availableSpace);
1179
1180     if (edge == Edge::Right)
1181         return areaSize.width() - tileSize.width() - result;
1182     
1183     if (edge == Edge::Bottom)
1184         return areaSize.height() - tileSize.height() - result;
1185
1186     return result;
1187 }
1188
1189 BackgroundImageGeometry RenderBoxModelObject::calculateBackgroundImageGeometry(const RenderLayerModelObject* paintContainer, const FillLayer& fillLayer, const LayoutPoint& paintOffset,
1190     const LayoutRect& borderBoxRect, RenderElement* backgroundObject) const
1191 {
1192     LayoutUnit left = 0;
1193     LayoutUnit top = 0;
1194     LayoutSize positioningAreaSize;
1195     // Determine the background positioning area and set destination rect to the background painting area.
1196     // Destination rect will be adjusted later if the background is non-repeating.
1197     // FIXME: transforms spec says that fixed backgrounds behave like scroll inside transforms. https://bugs.webkit.org/show_bug.cgi?id=15679
1198     LayoutRect destinationRect(borderBoxRect);
1199     bool fixedAttachment = fillLayer.attachment() == FixedBackgroundAttachment;
1200     float deviceScaleFactor = document().deviceScaleFactor();
1201     if (!fixedAttachment) {
1202         LayoutUnit right = 0;
1203         LayoutUnit bottom = 0;
1204         // Scroll and Local.
1205         if (fillLayer.origin() != BorderFillBox) {
1206             left = borderLeft();
1207             right = borderRight();
1208             top = borderTop();
1209             bottom = borderBottom();
1210             if (fillLayer.origin() == ContentFillBox) {
1211                 left += paddingLeft();
1212                 right += paddingRight();
1213                 top += paddingTop();
1214                 bottom += paddingBottom();
1215             }
1216         }
1217
1218         // The background of the box generated by the root element covers the entire canvas including
1219         // its margins. Since those were added in already, we have to factor them out when computing
1220         // the background positioning area.
1221         if (isDocumentElementRenderer()) {
1222             positioningAreaSize = downcast<RenderBox>(*this).size() - LayoutSize(left + right, top + bottom);
1223             positioningAreaSize = LayoutSize(snapSizeToDevicePixel(positioningAreaSize, LayoutPoint(), deviceScaleFactor));
1224             if (view().frameView().hasExtendedBackgroundRectForPainting()) {
1225                 LayoutRect extendedBackgroundRect = view().frameView().extendedBackgroundRectForPainting();
1226                 left += (marginLeft() - extendedBackgroundRect.x());
1227                 top += (marginTop() - extendedBackgroundRect.y());
1228             }
1229         } else {
1230             positioningAreaSize = borderBoxRect.size() - LayoutSize(left + right, top + bottom);
1231             positioningAreaSize = LayoutSize(snapRectToDevicePixels(LayoutRect(paintOffset, positioningAreaSize), deviceScaleFactor).size());
1232         }
1233     } else {
1234         LayoutRect viewportRect;
1235         float topContentInset = 0;
1236         if (settings().fixedBackgroundsPaintRelativeToDocument())
1237             viewportRect = view().unscaledDocumentRect();
1238         else {
1239             FrameView& frameView = view().frameView();
1240             bool useFixedLayout = frameView.useFixedLayout() && !frameView.fixedLayoutSize().isEmpty();
1241
1242             if (useFixedLayout) {
1243                 // Use the fixedLayoutSize() when useFixedLayout() because the rendering will scale
1244                 // down the frameView to to fit in the current viewport.
1245                 viewportRect.setSize(frameView.fixedLayoutSize());
1246             } else
1247                 viewportRect.setSize(frameView.sizeForVisibleContent());
1248
1249             if (fixedBackgroundPaintsInLocalCoordinates()) {
1250                 if (!useFixedLayout) {
1251                     // Shifting location up by topContentInset is needed for layout tests which expect
1252                     // layout to be shifted down when calling window.internals.setTopContentInset().
1253                     topContentInset = frameView.topContentInset(ScrollView::TopContentInsetType::WebCoreOrPlatformContentInset);
1254                     viewportRect.setLocation(LayoutPoint(0, -topContentInset));
1255                 }
1256             } else if (useFixedLayout || frameView.frameScaleFactor() != 1) {
1257                 // scrollPositionForFixedPosition() is adjusted for page scale and it does not include
1258                 // topContentInset so do not add it to the calculation below.
1259                 viewportRect.setLocation(frameView.scrollPositionForFixedPosition());
1260             } else {
1261                 // documentScrollPositionRelativeToViewOrigin() includes -topContentInset in its height
1262                 // so we need to account for that in calculating the phase size
1263                 topContentInset = frameView.topContentInset(ScrollView::TopContentInsetType::WebCoreOrPlatformContentInset);
1264                 viewportRect.setLocation(frameView.documentScrollPositionRelativeToViewOrigin());
1265             }
1266
1267             top += topContentInset;
1268         }
1269         
1270         if (paintContainer)
1271             viewportRect.moveBy(LayoutPoint(-paintContainer->localToAbsolute(FloatPoint())));
1272
1273         destinationRect = viewportRect;
1274         positioningAreaSize = destinationRect.size();
1275         positioningAreaSize.setHeight(positioningAreaSize.height() - topContentInset);
1276         positioningAreaSize = LayoutSize(snapRectToDevicePixels(LayoutRect(destinationRect.location(), positioningAreaSize), deviceScaleFactor).size());
1277     }
1278
1279     auto clientForBackgroundImage = backgroundObject ? backgroundObject : this;
1280     LayoutSize tileSize = calculateFillTileSize(fillLayer, positioningAreaSize);
1281     if (StyleImage* layerImage = fillLayer.image())
1282         layerImage->setContainerContextForRenderer(*clientForBackgroundImage, tileSize, style().effectiveZoom());
1283     
1284     EFillRepeat backgroundRepeatX = fillLayer.repeatX();
1285     EFillRepeat backgroundRepeatY = fillLayer.repeatY();
1286     LayoutUnit availableWidth = positioningAreaSize.width() - tileSize.width();
1287     LayoutUnit availableHeight = positioningAreaSize.height() - tileSize.height();
1288
1289     LayoutSize spaceSize;
1290     LayoutSize phase;
1291     LayoutSize noRepeat;
1292     LayoutUnit computedXPosition = resolveEdgeRelativeLength(fillLayer.xPosition(), fillLayer.backgroundXOrigin(), availableWidth, positioningAreaSize, tileSize);
1293     if (backgroundRepeatX == RoundFill && positioningAreaSize.width() > 0 && tileSize.width() > 0) {
1294         int numTiles = std::max(1, roundToInt(positioningAreaSize.width() / tileSize.width()));
1295         if (fillLayer.size().size.height.isAuto() && backgroundRepeatY != RoundFill)
1296             tileSize.setHeight(tileSize.height() * positioningAreaSize.width() / (numTiles * tileSize.width()));
1297
1298         tileSize.setWidth(positioningAreaSize.width() / numTiles);
1299         phase.setWidth(tileSize.width() ? tileSize.width() - fmodf((computedXPosition + left), tileSize.width()) : 0);
1300     }
1301
1302     LayoutUnit computedYPosition = resolveEdgeRelativeLength(fillLayer.yPosition(), fillLayer.backgroundYOrigin(), availableHeight, positioningAreaSize, tileSize);
1303     if (backgroundRepeatY == RoundFill && positioningAreaSize.height() > 0 && tileSize.height() > 0) {
1304         int numTiles = std::max(1, roundToInt(positioningAreaSize.height() / tileSize.height()));
1305         if (fillLayer.size().size.width.isAuto() && backgroundRepeatX != RoundFill)
1306             tileSize.setWidth(tileSize.width() * positioningAreaSize.height() / (numTiles * tileSize.height()));
1307
1308         tileSize.setHeight(positioningAreaSize.height() / numTiles);
1309         phase.setHeight(tileSize.height() ? tileSize.height() - fmodf((computedYPosition + top), tileSize.height()) : 0);
1310     }
1311
1312     if (backgroundRepeatX == RepeatFill) {
1313         phase.setWidth(tileSize.width() ? tileSize.width() - fmodf(computedXPosition + left, tileSize.width()) : 0);
1314         spaceSize.setWidth(0);
1315     } else if (backgroundRepeatX == SpaceFill && tileSize.width() > 0) {
1316         LayoutUnit space = getSpace(positioningAreaSize.width(), tileSize.width());
1317         if (space >= 0) {
1318             LayoutUnit actualWidth = tileSize.width() + space;
1319             computedXPosition = minimumValueForLength(Length(), availableWidth);
1320             spaceSize.setWidth(space);
1321             spaceSize.setHeight(0);
1322             phase.setWidth(actualWidth ? actualWidth - fmodf((computedXPosition + left), actualWidth) : 0);
1323         } else
1324             backgroundRepeatX = NoRepeatFill;
1325     }
1326
1327     if (backgroundRepeatX == NoRepeatFill) {
1328         LayoutUnit xOffset = left + computedXPosition;
1329         if (xOffset > 0)
1330             destinationRect.move(xOffset, 0);
1331         xOffset = std::min<LayoutUnit>(xOffset, 0);
1332         phase.setWidth(-xOffset);
1333         destinationRect.setWidth(tileSize.width() + xOffset);
1334         spaceSize.setWidth(0);
1335     }
1336
1337     if (backgroundRepeatY == RepeatFill) {
1338         phase.setHeight(tileSize.height() ? tileSize.height() - fmodf(computedYPosition + top, tileSize.height()) : 0);
1339         spaceSize.setHeight(0);
1340     } else if (backgroundRepeatY == SpaceFill && tileSize.height() > 0) {
1341         LayoutUnit space = getSpace(positioningAreaSize.height(), tileSize.height());
1342
1343         if (space >= 0) {
1344             LayoutUnit actualHeight = tileSize.height() + space;
1345             computedYPosition = minimumValueForLength(Length(), availableHeight);
1346             spaceSize.setHeight(space);
1347             phase.setHeight(actualHeight ? actualHeight - fmodf((computedYPosition + top), actualHeight) : 0);
1348         } else
1349             backgroundRepeatY = NoRepeatFill;
1350     }
1351     if (backgroundRepeatY == NoRepeatFill) {
1352         LayoutUnit yOffset = top + computedYPosition;
1353         if (yOffset > 0)
1354             destinationRect.move(0, yOffset);
1355         yOffset = std::min<LayoutUnit>(yOffset, 0);
1356         phase.setHeight(-yOffset);
1357         destinationRect.setHeight(tileSize.height() + yOffset);
1358         spaceSize.setHeight(0);
1359     }
1360
1361     if (fixedAttachment) {
1362         LayoutPoint attachmentPoint = borderBoxRect.location();
1363         phase.expand(std::max<LayoutUnit>(attachmentPoint.x() - destinationRect.x(), 0), std::max<LayoutUnit>(attachmentPoint.y() - destinationRect.y(), 0));
1364     }
1365
1366     destinationRect.intersect(borderBoxRect);
1367     pixelSnapBackgroundImageGeometryForPainting(destinationRect, tileSize, phase, spaceSize, deviceScaleFactor);
1368     return BackgroundImageGeometry(destinationRect, tileSize, phase, spaceSize, fixedAttachment);
1369 }
1370
1371 void RenderBoxModelObject::getGeometryForBackgroundImage(const RenderLayerModelObject* paintContainer, const LayoutPoint& paintOffset, FloatRect& destRect, FloatSize& phase, FloatSize& tileSize) const
1372 {
1373     LayoutRect paintRect(destRect);
1374     auto geometry = calculateBackgroundImageGeometry(paintContainer, style().backgroundLayers(), paintOffset, paintRect);
1375     phase = geometry.phase();
1376     tileSize = geometry.tileSize();
1377     destRect = geometry.destRect();
1378 }
1379
1380 bool RenderBoxModelObject::paintNinePieceImage(GraphicsContext& graphicsContext, const LayoutRect& rect, const RenderStyle& style,
1381                                                const NinePieceImage& ninePieceImage, CompositeOperator op)
1382 {
1383     StyleImage* styleImage = ninePieceImage.image();
1384     if (!styleImage)
1385         return false;
1386
1387     if (!styleImage->isLoaded())
1388         return true; // Never paint a nine-piece image incrementally, but don't paint the fallback borders either.
1389
1390     if (!styleImage->canRender(this, style.effectiveZoom()))
1391         return false;
1392
1393     // FIXME: border-image is broken with full page zooming when tiling has to happen, since the tiling function
1394     // doesn't have any understanding of the zoom that is in effect on the tile.
1395     float deviceScaleFactor = document().deviceScaleFactor();
1396
1397     LayoutRect rectWithOutsets = rect;
1398     rectWithOutsets.expand(style.imageOutsets(ninePieceImage));
1399     LayoutRect destination = LayoutRect(snapRectToDevicePixels(rectWithOutsets, deviceScaleFactor));
1400
1401     LayoutSize source = calculateImageIntrinsicDimensions(styleImage, destination.size(), DoNotScaleByEffectiveZoom);
1402
1403     // If both values are ‘auto’ then the intrinsic width and/or height of the image should be used, if any.
1404     styleImage->setContainerContextForRenderer(*this, source, style.effectiveZoom());
1405
1406     ninePieceImage.paint(graphicsContext, this, style, destination, source, deviceScaleFactor, op);
1407     return true;
1408 }
1409
1410 static bool allCornersClippedOut(const RoundedRect& border, const LayoutRect& clipRect)
1411 {
1412     LayoutRect boundingRect = border.rect();
1413     if (clipRect.contains(boundingRect))
1414         return false;
1415
1416     RoundedRect::Radii radii = border.radii();
1417
1418     LayoutRect topLeftRect(boundingRect.location(), radii.topLeft());
1419     if (clipRect.intersects(topLeftRect))
1420         return false;
1421
1422     LayoutRect topRightRect(boundingRect.location(), radii.topRight());
1423     topRightRect.setX(boundingRect.maxX() - topRightRect.width());
1424     if (clipRect.intersects(topRightRect))
1425         return false;
1426
1427     LayoutRect bottomLeftRect(boundingRect.location(), radii.bottomLeft());
1428     bottomLeftRect.setY(boundingRect.maxY() - bottomLeftRect.height());
1429     if (clipRect.intersects(bottomLeftRect))
1430         return false;
1431
1432     LayoutRect bottomRightRect(boundingRect.location(), radii.bottomRight());
1433     bottomRightRect.setX(boundingRect.maxX() - bottomRightRect.width());
1434     bottomRightRect.setY(boundingRect.maxY() - bottomRightRect.height());
1435     if (clipRect.intersects(bottomRightRect))
1436         return false;
1437
1438     return true;
1439 }
1440
1441 static bool borderWillArcInnerEdge(const LayoutSize& firstRadius, const FloatSize& secondRadius)
1442 {
1443     return !firstRadius.isZero() || !secondRadius.isZero();
1444 }
1445
1446 inline bool styleRequiresClipPolygon(EBorderStyle style)
1447 {
1448     return style == DOTTED || style == DASHED; // These are drawn with a stroke, so we have to clip to get corner miters.
1449 }
1450
1451 static bool borderStyleFillsBorderArea(EBorderStyle style)
1452 {
1453     return !(style == DOTTED || style == DASHED || style == DOUBLE);
1454 }
1455
1456 static bool borderStyleHasInnerDetail(EBorderStyle style)
1457 {
1458     return style == GROOVE || style == RIDGE || style == DOUBLE;
1459 }
1460
1461 static bool borderStyleIsDottedOrDashed(EBorderStyle style)
1462 {
1463     return style == DOTTED || style == DASHED;
1464 }
1465
1466 // OUTSET darkens the bottom and right (and maybe lightens the top and left)
1467 // INSET darkens the top and left (and maybe lightens the bottom and right)
1468 static inline bool borderStyleHasUnmatchedColorsAtCorner(EBorderStyle style, BoxSide side, BoxSide adjacentSide)
1469 {
1470     // These styles match at the top/left and bottom/right.
1471     if (style == INSET || style == GROOVE || style == RIDGE || style == OUTSET) {
1472         const BorderEdgeFlags topRightFlags = edgeFlagForSide(BSTop) | edgeFlagForSide(BSRight);
1473         const BorderEdgeFlags bottomLeftFlags = edgeFlagForSide(BSBottom) | edgeFlagForSide(BSLeft);
1474
1475         BorderEdgeFlags flags = edgeFlagForSide(side) | edgeFlagForSide(adjacentSide);
1476         return flags == topRightFlags || flags == bottomLeftFlags;
1477     }
1478     return false;
1479 }
1480
1481 static inline bool colorsMatchAtCorner(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1482 {
1483     if (edges[side].shouldRender() != edges[adjacentSide].shouldRender())
1484         return false;
1485
1486     if (!edgesShareColor(edges[side], edges[adjacentSide]))
1487         return false;
1488
1489     return !borderStyleHasUnmatchedColorsAtCorner(edges[side].style(), side, adjacentSide);
1490 }
1491
1492
1493 static inline bool colorNeedsAntiAliasAtCorner(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1494 {
1495     if (edges[side].color().isOpaque())
1496         return false;
1497
1498     if (edges[side].shouldRender() != edges[adjacentSide].shouldRender())
1499         return false;
1500
1501     if (!edgesShareColor(edges[side], edges[adjacentSide]))
1502         return true;
1503
1504     return borderStyleHasUnmatchedColorsAtCorner(edges[side].style(), side, adjacentSide);
1505 }
1506
1507 // This assumes that we draw in order: top, bottom, left, right.
1508 static inline bool willBeOverdrawn(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1509 {
1510     switch (side) {
1511     case BSTop:
1512     case BSBottom:
1513         if (edges[adjacentSide].presentButInvisible())
1514             return false;
1515
1516         if (!edgesShareColor(edges[side], edges[adjacentSide]) && !edges[adjacentSide].color().isOpaque())
1517             return false;
1518         
1519         if (!borderStyleFillsBorderArea(edges[adjacentSide].style()))
1520             return false;
1521
1522         return true;
1523
1524     case BSLeft:
1525     case BSRight:
1526         // These draw last, so are never overdrawn.
1527         return false;
1528     }
1529     return false;
1530 }
1531
1532 static inline bool borderStylesRequireMitre(BoxSide side, BoxSide adjacentSide, EBorderStyle style, EBorderStyle adjacentStyle)
1533 {
1534     if (style == DOUBLE || adjacentStyle == DOUBLE || adjacentStyle == GROOVE || adjacentStyle == RIDGE)
1535         return true;
1536
1537     if (borderStyleIsDottedOrDashed(style) != borderStyleIsDottedOrDashed(adjacentStyle))
1538         return true;
1539
1540     if (style != adjacentStyle)
1541         return true;
1542
1543     return borderStyleHasUnmatchedColorsAtCorner(style, side, adjacentSide);
1544 }
1545
1546 static bool joinRequiresMitre(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[], bool allowOverdraw)
1547 {
1548     if ((edges[side].isTransparent() && edges[adjacentSide].isTransparent()) || !edges[adjacentSide].isPresent())
1549         return false;
1550
1551     if (allowOverdraw && willBeOverdrawn(side, adjacentSide, edges))
1552         return false;
1553
1554     if (!edgesShareColor(edges[side], edges[adjacentSide]))
1555         return true;
1556
1557     if (borderStylesRequireMitre(side, adjacentSide, edges[side].style(), edges[adjacentSide].style()))
1558         return true;
1559     
1560     return false;
1561 }
1562
1563 static RoundedRect calculateAdjustedInnerBorder(const RoundedRect&innerBorder, BoxSide side)
1564 {
1565     // Expand the inner border as necessary to make it a rounded rect (i.e. radii contained within each edge).
1566     // This function relies on the fact we only get radii not contained within each edge if one of the radii
1567     // for an edge is zero, so we can shift the arc towards the zero radius corner.
1568     RoundedRect::Radii newRadii = innerBorder.radii();
1569     LayoutRect newRect = innerBorder.rect();
1570
1571     float overshoot;
1572     float maxRadii;
1573
1574     switch (side) {
1575     case BSTop:
1576         overshoot = newRadii.topLeft().width() + newRadii.topRight().width() - newRect.width();
1577         if (overshoot > 0) {
1578             ASSERT(!(newRadii.topLeft().width() && newRadii.topRight().width()));
1579             newRect.setWidth(newRect.width() + overshoot);
1580             if (!newRadii.topLeft().width())
1581                 newRect.move(-overshoot, 0);
1582         }
1583         newRadii.setBottomLeft(IntSize(0, 0));
1584         newRadii.setBottomRight(IntSize(0, 0));
1585         maxRadii = std::max(newRadii.topLeft().height(), newRadii.topRight().height());
1586         if (maxRadii > newRect.height())
1587             newRect.setHeight(maxRadii);
1588         break;
1589
1590     case BSBottom:
1591         overshoot = newRadii.bottomLeft().width() + newRadii.bottomRight().width() - newRect.width();
1592         if (overshoot > 0) {
1593             ASSERT(!(newRadii.bottomLeft().width() && newRadii.bottomRight().width()));
1594             newRect.setWidth(newRect.width() + overshoot);
1595             if (!newRadii.bottomLeft().width())
1596                 newRect.move(-overshoot, 0);
1597         }
1598         newRadii.setTopLeft(IntSize(0, 0));
1599         newRadii.setTopRight(IntSize(0, 0));
1600         maxRadii = std::max(newRadii.bottomLeft().height(), newRadii.bottomRight().height());
1601         if (maxRadii > newRect.height()) {
1602             newRect.move(0, newRect.height() - maxRadii);
1603             newRect.setHeight(maxRadii);
1604         }
1605         break;
1606
1607     case BSLeft:
1608         overshoot = newRadii.topLeft().height() + newRadii.bottomLeft().height() - newRect.height();
1609         if (overshoot > 0) {
1610             ASSERT(!(newRadii.topLeft().height() && newRadii.bottomLeft().height()));
1611             newRect.setHeight(newRect.height() + overshoot);
1612             if (!newRadii.topLeft().height())
1613                 newRect.move(0, -overshoot);
1614         }
1615         newRadii.setTopRight(IntSize(0, 0));
1616         newRadii.setBottomRight(IntSize(0, 0));
1617         maxRadii = std::max(newRadii.topLeft().width(), newRadii.bottomLeft().width());
1618         if (maxRadii > newRect.width())
1619             newRect.setWidth(maxRadii);
1620         break;
1621
1622     case BSRight:
1623         overshoot = newRadii.topRight().height() + newRadii.bottomRight().height() - newRect.height();
1624         if (overshoot > 0) {
1625             ASSERT(!(newRadii.topRight().height() && newRadii.bottomRight().height()));
1626             newRect.setHeight(newRect.height() + overshoot);
1627             if (!newRadii.topRight().height())
1628                 newRect.move(0, -overshoot);
1629         }
1630         newRadii.setTopLeft(IntSize(0, 0));
1631         newRadii.setBottomLeft(IntSize(0, 0));
1632         maxRadii = std::max(newRadii.topRight().width(), newRadii.bottomRight().width());
1633         if (maxRadii > newRect.width()) {
1634             newRect.move(newRect.width() - maxRadii, 0);
1635             newRect.setWidth(maxRadii);
1636         }
1637         break;
1638     }
1639
1640     return RoundedRect(newRect, newRadii);
1641 }
1642
1643 void RenderBoxModelObject::paintOneBorderSide(GraphicsContext& graphicsContext, const RenderStyle& style, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
1644     const LayoutRect& sideRect, BoxSide side, BoxSide adjacentSide1, BoxSide adjacentSide2, const BorderEdge edges[], const Path* path,
1645     BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias, const Color* overrideColor)
1646 {
1647     const BorderEdge& edgeToRender = edges[side];
1648     ASSERT(edgeToRender.widthForPainting());
1649     const BorderEdge& adjacentEdge1 = edges[adjacentSide1];
1650     const BorderEdge& adjacentEdge2 = edges[adjacentSide2];
1651
1652     bool mitreAdjacentSide1 = joinRequiresMitre(side, adjacentSide1, edges, !antialias);
1653     bool mitreAdjacentSide2 = joinRequiresMitre(side, adjacentSide2, edges, !antialias);
1654     
1655     bool adjacentSide1StylesMatch = colorsMatchAtCorner(side, adjacentSide1, edges);
1656     bool adjacentSide2StylesMatch = colorsMatchAtCorner(side, adjacentSide2, edges);
1657
1658     const Color& colorToPaint = overrideColor ? *overrideColor : edgeToRender.color();
1659
1660     if (path) {
1661         GraphicsContextStateSaver stateSaver(graphicsContext);
1662
1663         clipBorderSidePolygon(graphicsContext, outerBorder, innerBorder, side, adjacentSide1StylesMatch, adjacentSide2StylesMatch);
1664
1665         if (!innerBorder.isRenderable())
1666             graphicsContext.clipOutRoundedRect(FloatRoundedRect(calculateAdjustedInnerBorder(innerBorder, side)));
1667
1668         float thickness = std::max(std::max(edgeToRender.widthForPainting(), adjacentEdge1.widthForPainting()), adjacentEdge2.widthForPainting());
1669         drawBoxSideFromPath(graphicsContext, outerBorder.rect(), *path, edges, edgeToRender.widthForPainting(), thickness, side, style,
1670             colorToPaint, edgeToRender.style(), bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
1671     } else {
1672         bool clipForStyle = styleRequiresClipPolygon(edgeToRender.style()) && (mitreAdjacentSide1 || mitreAdjacentSide2);
1673         bool clipAdjacentSide1 = colorNeedsAntiAliasAtCorner(side, adjacentSide1, edges) && mitreAdjacentSide1;
1674         bool clipAdjacentSide2 = colorNeedsAntiAliasAtCorner(side, adjacentSide2, edges) && mitreAdjacentSide2;
1675         bool shouldClip = clipForStyle || clipAdjacentSide1 || clipAdjacentSide2;
1676         
1677         GraphicsContextStateSaver clipStateSaver(graphicsContext, shouldClip);
1678         if (shouldClip) {
1679             bool aliasAdjacentSide1 = clipAdjacentSide1 || (clipForStyle && mitreAdjacentSide1);
1680             bool aliasAdjacentSide2 = clipAdjacentSide2 || (clipForStyle && mitreAdjacentSide2);
1681             clipBorderSidePolygon(graphicsContext, outerBorder, innerBorder, side, !aliasAdjacentSide1, !aliasAdjacentSide2);
1682             // Since we clipped, no need to draw with a mitre.
1683             mitreAdjacentSide1 = false;
1684             mitreAdjacentSide2 = false;
1685         }
1686         drawLineForBoxSide(graphicsContext, sideRect, side, colorToPaint, edgeToRender.style(), mitreAdjacentSide1 ? adjacentEdge1.widthForPainting() : 0, mitreAdjacentSide2 ? adjacentEdge2.widthForPainting() : 0, antialias);
1687     }
1688 }
1689
1690 static LayoutRect calculateSideRect(const RoundedRect& outerBorder, const BorderEdge edges[], int side)
1691 {
1692     LayoutRect sideRect = outerBorder.rect();
1693     float width = edges[side].widthForPainting();
1694
1695     if (side == BSTop)
1696         sideRect.setHeight(width);
1697     else if (side == BSBottom)
1698         sideRect.shiftYEdgeTo(sideRect.maxY() - width);
1699     else if (side == BSLeft)
1700         sideRect.setWidth(width);
1701     else
1702         sideRect.shiftXEdgeTo(sideRect.maxX() - width);
1703
1704     return sideRect;
1705 }
1706
1707 void RenderBoxModelObject::paintBorderSides(GraphicsContext& graphicsContext, const RenderStyle& style, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
1708     const IntPoint& innerBorderAdjustment, const BorderEdge edges[], BorderEdgeFlags edgeSet, BackgroundBleedAvoidance bleedAvoidance,
1709     bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias, const Color* overrideColor)
1710 {
1711     bool renderRadii = outerBorder.isRounded();
1712
1713     Path roundedPath;
1714     if (renderRadii)
1715         roundedPath.addRoundedRect(outerBorder);
1716     
1717     // The inner border adjustment for bleed avoidance mode BackgroundBleedBackgroundOverBorder
1718     // is only applied to sideRect, which is okay since BackgroundBleedBackgroundOverBorder
1719     // is only to be used for solid borders and the shape of the border painted by drawBoxSideFromPath
1720     // only depends on sideRect when painting solid borders.
1721
1722     if (edges[BSTop].shouldRender() && includesEdge(edgeSet, BSTop)) {
1723         LayoutRect sideRect = outerBorder.rect();
1724         sideRect.setHeight(edges[BSTop].widthForPainting() + innerBorderAdjustment.y());
1725
1726         bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSTop].style()) || borderWillArcInnerEdge(innerBorder.radii().topLeft(), innerBorder.radii().topRight()));
1727         paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSTop, BSLeft, BSRight, edges, usePath ? &roundedPath : nullptr, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1728     }
1729
1730     if (edges[BSBottom].shouldRender() && includesEdge(edgeSet, BSBottom)) {
1731         LayoutRect sideRect = outerBorder.rect();
1732         sideRect.shiftYEdgeTo(sideRect.maxY() - edges[BSBottom].widthForPainting() - innerBorderAdjustment.y());
1733
1734         bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSBottom].style()) || borderWillArcInnerEdge(innerBorder.radii().bottomLeft(), innerBorder.radii().bottomRight()));
1735         paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSBottom, BSLeft, BSRight, edges, usePath ? &roundedPath : nullptr, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1736     }
1737
1738     if (edges[BSLeft].shouldRender() && includesEdge(edgeSet, BSLeft)) {
1739         LayoutRect sideRect = outerBorder.rect();
1740         sideRect.setWidth(edges[BSLeft].widthForPainting() + innerBorderAdjustment.x());
1741
1742         bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSLeft].style()) || borderWillArcInnerEdge(innerBorder.radii().bottomLeft(), innerBorder.radii().topLeft()));
1743         paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSLeft, BSTop, BSBottom, edges, usePath ? &roundedPath : nullptr, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1744     }
1745
1746     if (edges[BSRight].shouldRender() && includesEdge(edgeSet, BSRight)) {
1747         LayoutRect sideRect = outerBorder.rect();
1748         sideRect.shiftXEdgeTo(sideRect.maxX() - edges[BSRight].widthForPainting() - innerBorderAdjustment.x());
1749
1750         bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSRight].style()) || borderWillArcInnerEdge(innerBorder.radii().bottomRight(), innerBorder.radii().topRight()));
1751         paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSRight, BSTop, BSBottom, edges, usePath ? &roundedPath : nullptr, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1752     }
1753 }
1754
1755 void RenderBoxModelObject::paintTranslucentBorderSides(GraphicsContext& graphicsContext, const RenderStyle& style, const RoundedRect& outerBorder, const RoundedRect& innerBorder, const IntPoint& innerBorderAdjustment,
1756     const BorderEdge edges[], BorderEdgeFlags edgesToDraw, BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias)
1757 {
1758     // willBeOverdrawn assumes that we draw in order: top, bottom, left, right.
1759     // This is different from BoxSide enum order.
1760     static const BoxSide paintOrder[] = { BSTop, BSBottom, BSLeft, BSRight };
1761
1762     while (edgesToDraw) {
1763         // Find undrawn edges sharing a color.
1764         Color commonColor;
1765         
1766         BorderEdgeFlags commonColorEdgeSet = 0;
1767         for (size_t i = 0; i < sizeof(paintOrder) / sizeof(paintOrder[0]); ++i) {
1768             BoxSide currSide = paintOrder[i];
1769             if (!includesEdge(edgesToDraw, currSide))
1770                 continue;
1771
1772             bool includeEdge;
1773             if (!commonColorEdgeSet) {
1774                 commonColor = edges[currSide].color();
1775                 includeEdge = true;
1776             } else
1777                 includeEdge = edges[currSide].color() == commonColor;
1778
1779             if (includeEdge)
1780                 commonColorEdgeSet |= edgeFlagForSide(currSide);
1781         }
1782
1783         bool useTransparencyLayer = includesAdjacentEdges(commonColorEdgeSet) && !commonColor.isOpaque();
1784         if (useTransparencyLayer) {
1785             graphicsContext.beginTransparencyLayer(commonColor.alphaAsFloat());
1786             commonColor = commonColor.opaqueColor();
1787         }
1788
1789         paintBorderSides(graphicsContext, style, outerBorder, innerBorder, innerBorderAdjustment, edges, commonColorEdgeSet, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, &commonColor);
1790             
1791         if (useTransparencyLayer)
1792             graphicsContext.endTransparencyLayer();
1793         
1794         edgesToDraw &= ~commonColorEdgeSet;
1795     }
1796 }
1797
1798 void RenderBoxModelObject::paintBorder(const PaintInfo& info, const LayoutRect& rect, const RenderStyle& style,
1799                                        BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
1800 {
1801     GraphicsContext& graphicsContext = info.context();
1802
1803     if (graphicsContext.paintingDisabled())
1804         return;
1805
1806     if (rect.isEmpty())
1807         return;
1808
1809     auto rectToClipOut = paintRectToClipOutFromBorder(rect);
1810     bool appliedClipAlready = !rectToClipOut.isEmpty();
1811     GraphicsContextStateSaver stateSave(graphicsContext, appliedClipAlready);
1812     if (!rectToClipOut.isEmpty())
1813         graphicsContext.clipOut(snapRectToDevicePixels(rectToClipOut, document().deviceScaleFactor()));
1814
1815     // border-image is not affected by border-radius.
1816     if (paintNinePieceImage(graphicsContext, rect, style, style.borderImage()))
1817         return;
1818
1819     BorderEdge edges[4];
1820     BorderEdge::getBorderEdgeInfo(edges, style, document().deviceScaleFactor(), includeLogicalLeftEdge, includeLogicalRightEdge);
1821     RoundedRect outerBorder = style.getRoundedBorderFor(rect, includeLogicalLeftEdge, includeLogicalRightEdge);
1822     RoundedRect innerBorder = style.getRoundedInnerBorderFor(borderInnerRectAdjustedForBleedAvoidance(graphicsContext, rect, bleedAvoidance), includeLogicalLeftEdge, includeLogicalRightEdge);
1823
1824     // If no borders intersects with the dirty area, we can skip the border painting.
1825     if (innerBorder.contains(info.rect))
1826         return;
1827
1828     bool haveAlphaColor = false;
1829     bool haveAllSolidEdges = true;
1830     bool haveAllDoubleEdges = true;
1831     int numEdgesVisible = 4;
1832     bool allEdgesShareColor = true;
1833     int firstVisibleEdge = -1;
1834     BorderEdgeFlags edgesToDraw = 0;
1835
1836     for (int i = BSTop; i <= BSLeft; ++i) {
1837         const BorderEdge& currEdge = edges[i];
1838
1839         if (edges[i].shouldRender())
1840             edgesToDraw |= edgeFlagForSide(static_cast<BoxSide>(i));
1841
1842         if (currEdge.presentButInvisible()) {
1843             --numEdgesVisible;
1844             allEdgesShareColor = false;
1845             continue;
1846         }
1847         
1848         if (!currEdge.widthForPainting()) {
1849             --numEdgesVisible;
1850             continue;
1851         }
1852
1853         if (firstVisibleEdge == -1)
1854             firstVisibleEdge = i;
1855         else if (currEdge.color() != edges[firstVisibleEdge].color())
1856             allEdgesShareColor = false;
1857
1858         if (!currEdge.color().isOpaque())
1859             haveAlphaColor = true;
1860         
1861         if (currEdge.style() != SOLID)
1862             haveAllSolidEdges = false;
1863
1864         if (currEdge.style() != DOUBLE)
1865             haveAllDoubleEdges = false;
1866     }
1867
1868     // If no corner intersects the clip region, we can pretend outerBorder is
1869     // rectangular to improve performance.
1870     if (haveAllSolidEdges && outerBorder.isRounded() && allCornersClippedOut(outerBorder, info.rect))
1871         outerBorder.setRadii(RoundedRect::Radii());
1872
1873     float deviceScaleFactor = document().deviceScaleFactor();
1874     // isRenderable() check avoids issue described in https://bugs.webkit.org/show_bug.cgi?id=38787
1875     if ((haveAllSolidEdges || haveAllDoubleEdges) && allEdgesShareColor && innerBorder.isRenderable()) {
1876         // Fast path for drawing all solid edges and all unrounded double edges
1877         if (numEdgesVisible == 4 && (outerBorder.isRounded() || haveAlphaColor)
1878             && (haveAllSolidEdges || (!outerBorder.isRounded() && !innerBorder.isRounded()))) {
1879             Path path;
1880             
1881             FloatRoundedRect pixelSnappedOuterBorder = outerBorder.pixelSnappedRoundedRectForPainting(deviceScaleFactor);
1882             if (pixelSnappedOuterBorder.isRounded() && bleedAvoidance != BackgroundBleedUseTransparencyLayer)
1883                 path.addRoundedRect(pixelSnappedOuterBorder);
1884             else
1885                 path.addRect(pixelSnappedOuterBorder.rect());
1886
1887             if (haveAllDoubleEdges) {
1888                 LayoutRect innerThirdRect = outerBorder.rect();
1889                 LayoutRect outerThirdRect = outerBorder.rect();
1890                 for (int side = BSTop; side <= BSLeft; ++side) {
1891                     LayoutUnit outerWidth;
1892                     LayoutUnit innerWidth;
1893                     edges[side].getDoubleBorderStripeWidths(outerWidth, innerWidth);
1894
1895                     if (side == BSTop) {
1896                         innerThirdRect.shiftYEdgeTo(innerThirdRect.y() + innerWidth);
1897                         outerThirdRect.shiftYEdgeTo(outerThirdRect.y() + outerWidth);
1898                     } else if (side == BSBottom) {
1899                         innerThirdRect.setHeight(innerThirdRect.height() - innerWidth);
1900                         outerThirdRect.setHeight(outerThirdRect.height() - outerWidth);
1901                     } else if (side == BSLeft) {
1902                         innerThirdRect.shiftXEdgeTo(innerThirdRect.x() + innerWidth);
1903                         outerThirdRect.shiftXEdgeTo(outerThirdRect.x() + outerWidth);
1904                     } else {
1905                         innerThirdRect.setWidth(innerThirdRect.width() - innerWidth);
1906                         outerThirdRect.setWidth(outerThirdRect.width() - outerWidth);
1907                     }
1908                 }
1909
1910                 FloatRoundedRect pixelSnappedOuterThird = outerBorder.pixelSnappedRoundedRectForPainting(deviceScaleFactor);
1911                 pixelSnappedOuterThird.setRect(snapRectToDevicePixels(outerThirdRect, deviceScaleFactor));
1912
1913                 if (pixelSnappedOuterThird.isRounded() && bleedAvoidance != BackgroundBleedUseTransparencyLayer)
1914                     path.addRoundedRect(pixelSnappedOuterThird);
1915                 else
1916                     path.addRect(pixelSnappedOuterThird.rect());
1917
1918                 FloatRoundedRect pixelSnappedInnerThird = innerBorder.pixelSnappedRoundedRectForPainting(deviceScaleFactor);
1919                 pixelSnappedInnerThird.setRect(snapRectToDevicePixels(innerThirdRect, deviceScaleFactor));
1920                 if (pixelSnappedInnerThird.isRounded() && bleedAvoidance != BackgroundBleedUseTransparencyLayer)
1921                     path.addRoundedRect(pixelSnappedInnerThird);
1922                 else
1923                     path.addRect(pixelSnappedInnerThird.rect());
1924             }
1925
1926             FloatRoundedRect pixelSnappedInnerBorder = innerBorder.pixelSnappedRoundedRectForPainting(deviceScaleFactor);
1927             if (pixelSnappedInnerBorder.isRounded())
1928                 path.addRoundedRect(pixelSnappedInnerBorder);
1929             else
1930                 path.addRect(pixelSnappedInnerBorder.rect());
1931             
1932             graphicsContext.setFillRule(RULE_EVENODD);
1933             graphicsContext.setFillColor(edges[firstVisibleEdge].color());
1934             graphicsContext.fillPath(path);
1935             return;
1936         } 
1937         // Avoid creating transparent layers
1938         if (haveAllSolidEdges && numEdgesVisible != 4 && !outerBorder.isRounded() && haveAlphaColor) {
1939             Path path;
1940
1941             for (int i = BSTop; i <= BSLeft; ++i) {
1942                 const BorderEdge& currEdge = edges[i];
1943                 if (currEdge.shouldRender()) {
1944                     LayoutRect sideRect = calculateSideRect(outerBorder, edges, i);
1945                     path.addRect(sideRect);
1946                 }
1947             }
1948
1949             graphicsContext.setFillRule(RULE_NONZERO);
1950             graphicsContext.setFillColor(edges[firstVisibleEdge].color());
1951             graphicsContext.fillPath(path);
1952             return;
1953         }
1954     }
1955
1956     bool clipToOuterBorder = outerBorder.isRounded();
1957     GraphicsContextStateSaver stateSaver(graphicsContext, clipToOuterBorder && !appliedClipAlready);
1958     if (clipToOuterBorder) {
1959         // Clip to the inner and outer radii rects.
1960         if (bleedAvoidance != BackgroundBleedUseTransparencyLayer)
1961             graphicsContext.clipRoundedRect(outerBorder.pixelSnappedRoundedRectForPainting(deviceScaleFactor));
1962         // isRenderable() check avoids issue described in https://bugs.webkit.org/show_bug.cgi?id=38787
1963         // The inside will be clipped out later (in clipBorderSideForComplexInnerPath)
1964         if (innerBorder.isRenderable())
1965             graphicsContext.clipOutRoundedRect(innerBorder.pixelSnappedRoundedRectForPainting(deviceScaleFactor));
1966     }
1967
1968     // If only one edge visible antialiasing doesn't create seams
1969     bool antialias = shouldAntialiasLines(graphicsContext) || numEdgesVisible == 1;
1970     RoundedRect unadjustedInnerBorder = (bleedAvoidance == BackgroundBleedBackgroundOverBorder) ? style.getRoundedInnerBorderFor(rect, includeLogicalLeftEdge, includeLogicalRightEdge) : innerBorder;
1971     IntPoint innerBorderAdjustment(innerBorder.rect().x() - unadjustedInnerBorder.rect().x(), innerBorder.rect().y() - unadjustedInnerBorder.rect().y());
1972     if (haveAlphaColor)
1973         paintTranslucentBorderSides(graphicsContext, style, outerBorder, unadjustedInnerBorder, innerBorderAdjustment, edges, edgesToDraw, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias);
1974     else
1975         paintBorderSides(graphicsContext, style, outerBorder, unadjustedInnerBorder, innerBorderAdjustment, edges, edgesToDraw, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias);
1976 }
1977
1978 void RenderBoxModelObject::drawBoxSideFromPath(GraphicsContext& graphicsContext, const LayoutRect& borderRect, const Path& borderPath, const BorderEdge edges[],
1979     float thickness, float drawThickness, BoxSide side, const RenderStyle& style, Color color, EBorderStyle borderStyle, BackgroundBleedAvoidance bleedAvoidance,
1980     bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
1981 {
1982     if (thickness <= 0)
1983         return;
1984
1985     if (borderStyle == DOUBLE && thickness < 3)
1986         borderStyle = SOLID;
1987
1988     switch (borderStyle) {
1989     case BNONE:
1990     case BHIDDEN:
1991         return;
1992     case DOTTED:
1993     case DASHED: {
1994         graphicsContext.setStrokeColor(color);
1995
1996         // The stroke is doubled here because the provided path is the 
1997         // outside edge of the border so half the stroke is clipped off. 
1998         // The extra multiplier is so that the clipping mask can antialias
1999         // the edges to prevent jaggies.
2000         graphicsContext.setStrokeThickness(drawThickness * 2 * 1.1f);
2001         graphicsContext.setStrokeStyle(borderStyle == DASHED ? DashedStroke : DottedStroke);
2002
2003         // If the number of dashes that fit in the path is odd and non-integral then we
2004         // will have an awkwardly-sized dash at the end of the path. To try to avoid that
2005         // here, we simply make the whitespace dashes ever so slightly bigger.
2006         // FIXME: This could be even better if we tried to manipulate the dash offset
2007         // and possibly the gapLength to get the corners dash-symmetrical.
2008         float dashLength = thickness * ((borderStyle == DASHED) ? 3.0f : 1.0f);
2009         float gapLength = dashLength;
2010         float numberOfDashes = borderPath.length() / dashLength;
2011         // Don't try to show dashes if we have less than 2 dashes + 2 gaps.
2012         // FIXME: should do this test per side.
2013         if (numberOfDashes >= 4) {
2014             bool evenNumberOfFullDashes = !((int)numberOfDashes % 2);
2015             bool integralNumberOfDashes = !(numberOfDashes - (int)numberOfDashes);
2016             if (!evenNumberOfFullDashes && !integralNumberOfDashes) {
2017                 float numberOfGaps = numberOfDashes / 2;
2018                 gapLength += (dashLength  / numberOfGaps);
2019             }
2020
2021             DashArray lineDash;
2022             lineDash.append(dashLength);
2023             lineDash.append(gapLength);
2024             graphicsContext.setLineDash(lineDash, dashLength);
2025         }
2026         
2027         // FIXME: stroking the border path causes issues with tight corners:
2028         // https://bugs.webkit.org/show_bug.cgi?id=58711
2029         // Also, to get the best appearance we should stroke a path between the two borders.
2030         graphicsContext.strokePath(borderPath);
2031         return;
2032     }
2033     case DOUBLE: {
2034         // Get the inner border rects for both the outer border line and the inner border line
2035         LayoutUnit outerBorderTopWidth;
2036         LayoutUnit innerBorderTopWidth;
2037         edges[BSTop].getDoubleBorderStripeWidths(outerBorderTopWidth, innerBorderTopWidth);
2038
2039         LayoutUnit outerBorderRightWidth;
2040         LayoutUnit innerBorderRightWidth;
2041         edges[BSRight].getDoubleBorderStripeWidths(outerBorderRightWidth, innerBorderRightWidth);
2042
2043         LayoutUnit outerBorderBottomWidth;
2044         LayoutUnit innerBorderBottomWidth;
2045         edges[BSBottom].getDoubleBorderStripeWidths(outerBorderBottomWidth, innerBorderBottomWidth);
2046
2047         LayoutUnit outerBorderLeftWidth;
2048         LayoutUnit innerBorderLeftWidth;
2049         edges[BSLeft].getDoubleBorderStripeWidths(outerBorderLeftWidth, innerBorderLeftWidth);
2050
2051         // Draw inner border line
2052         {
2053             GraphicsContextStateSaver stateSaver(graphicsContext);
2054             RoundedRect innerClip = style.getRoundedInnerBorderFor(borderRect,
2055                 innerBorderTopWidth, innerBorderBottomWidth, innerBorderLeftWidth, innerBorderRightWidth,
2056                 includeLogicalLeftEdge, includeLogicalRightEdge);
2057             
2058             graphicsContext.clipRoundedRect(FloatRoundedRect(innerClip));
2059             drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, SOLID, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
2060         }
2061
2062         // Draw outer border line
2063         {
2064             GraphicsContextStateSaver stateSaver(graphicsContext);
2065             LayoutRect outerRect = borderRect;
2066             if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
2067                 outerRect.inflate(1);
2068                 ++outerBorderTopWidth;
2069                 ++outerBorderBottomWidth;
2070                 ++outerBorderLeftWidth;
2071                 ++outerBorderRightWidth;
2072             }
2073                 
2074             RoundedRect outerClip = style.getRoundedInnerBorderFor(outerRect,
2075                 outerBorderTopWidth, outerBorderBottomWidth, outerBorderLeftWidth, outerBorderRightWidth,
2076                 includeLogicalLeftEdge, includeLogicalRightEdge);
2077             graphicsContext.clipOutRoundedRect(FloatRoundedRect(outerClip));
2078             drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, SOLID, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
2079         }
2080         return;
2081     }
2082     case RIDGE:
2083     case GROOVE:
2084     {
2085         EBorderStyle s1;
2086         EBorderStyle s2;
2087         if (borderStyle == GROOVE) {
2088             s1 = INSET;
2089             s2 = OUTSET;
2090         } else {
2091             s1 = OUTSET;
2092             s2 = INSET;
2093         }
2094         
2095         // Paint full border
2096         drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, s1, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
2097
2098         // Paint inner only
2099         GraphicsContextStateSaver stateSaver(graphicsContext);
2100         LayoutUnit topWidth = edges[BSTop].widthForPainting() / 2;
2101         LayoutUnit bottomWidth = edges[BSBottom].widthForPainting() / 2;
2102         LayoutUnit leftWidth = edges[BSLeft].widthForPainting() / 2;
2103         LayoutUnit rightWidth = edges[BSRight].widthForPainting() / 2;
2104
2105         RoundedRect clipRect = style.getRoundedInnerBorderFor(borderRect,
2106             topWidth, bottomWidth, leftWidth, rightWidth,
2107             includeLogicalLeftEdge, includeLogicalRightEdge);
2108
2109         graphicsContext.clipRoundedRect(FloatRoundedRect(clipRect));
2110         drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, s2, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
2111         return;
2112     }
2113     case INSET:
2114     case OUTSET:
2115         calculateBorderStyleColor(borderStyle, side, color);
2116         break;
2117     default:
2118         break;
2119     }
2120
2121     graphicsContext.setStrokeStyle(NoStroke);
2122     graphicsContext.setFillColor(color);
2123     graphicsContext.drawRect(snapRectToDevicePixels(borderRect, document().deviceScaleFactor()));
2124 }
2125
2126 void RenderBoxModelObject::clipBorderSidePolygon(GraphicsContext& graphicsContext, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
2127                                                  BoxSide side, bool firstEdgeMatches, bool secondEdgeMatches)
2128 {
2129     float deviceScaleFactor = document().deviceScaleFactor();
2130     const FloatRect& outerRect = snapRectToDevicePixels(outerBorder.rect(), deviceScaleFactor);
2131     const FloatRect& innerRect = snapRectToDevicePixels(innerBorder.rect(), deviceScaleFactor);
2132
2133     // For each side, create a quad that encompasses all parts of that side that may draw,
2134     // including areas inside the innerBorder.
2135     //
2136     //         0----------------3
2137     //       0  \              /  0
2138     //       |\  1----------- 2  /|
2139     //       | 1                1 |   
2140     //       | |                | |
2141     //       | |                | |  
2142     //       | 2                2 |  
2143     //       |/  1------------2  \| 
2144     //       3  /              \  3   
2145     //         0----------------3
2146     //
2147     Vector<FloatPoint> quad;
2148     quad.reserveInitialCapacity(4);
2149     switch (side) {
2150     case BSTop:
2151         quad.uncheckedAppend(outerRect.minXMinYCorner());
2152         quad.uncheckedAppend(innerRect.minXMinYCorner());
2153         quad.uncheckedAppend(innerRect.maxXMinYCorner());
2154         quad.uncheckedAppend(outerRect.maxXMinYCorner());
2155
2156         if (!innerBorder.radii().topLeft().isZero())
2157             findIntersection(outerRect.minXMinYCorner(), innerRect.minXMinYCorner(), innerRect.minXMaxYCorner(), innerRect.maxXMinYCorner(), quad[1]);
2158
2159         if (!innerBorder.radii().topRight().isZero())
2160             findIntersection(outerRect.maxXMinYCorner(), innerRect.maxXMinYCorner(), innerRect.minXMinYCorner(), innerRect.maxXMaxYCorner(), quad[2]);
2161         break;
2162
2163     case BSLeft:
2164         quad.uncheckedAppend(outerRect.minXMinYCorner());
2165         quad.uncheckedAppend(innerRect.minXMinYCorner());
2166         quad.uncheckedAppend(innerRect.minXMaxYCorner());
2167         quad.uncheckedAppend(outerRect.minXMaxYCorner());
2168
2169         if (!innerBorder.radii().topLeft().isZero())
2170             findIntersection(outerRect.minXMinYCorner(), innerRect.minXMinYCorner(), innerRect.minXMaxYCorner(), innerRect.maxXMinYCorner(), quad[1]);
2171
2172         if (!innerBorder.radii().bottomLeft().isZero())
2173             findIntersection(outerRect.minXMaxYCorner(), innerRect.minXMaxYCorner(), innerRect.minXMinYCorner(), innerRect.maxXMaxYCorner(), quad[2]);
2174         break;
2175
2176     case BSBottom:
2177         quad.uncheckedAppend(outerRect.minXMaxYCorner());
2178         quad.uncheckedAppend(innerRect.minXMaxYCorner());
2179         quad.uncheckedAppend(innerRect.maxXMaxYCorner());
2180         quad.uncheckedAppend(outerRect.maxXMaxYCorner());
2181
2182         if (!innerBorder.radii().bottomLeft().isZero())
2183             findIntersection(outerRect.minXMaxYCorner(), innerRect.minXMaxYCorner(), innerRect.minXMinYCorner(), innerRect.maxXMaxYCorner(), quad[1]);
2184
2185         if (!innerBorder.radii().bottomRight().isZero())
2186             findIntersection(outerRect.maxXMaxYCorner(), innerRect.maxXMaxYCorner(), innerRect.maxXMinYCorner(), innerRect.minXMaxYCorner(), quad[2]);
2187         break;
2188
2189     case BSRight:
2190         quad.uncheckedAppend(outerRect.maxXMinYCorner());
2191         quad.uncheckedAppend(innerRect.maxXMinYCorner());
2192         quad.uncheckedAppend(innerRect.maxXMaxYCorner());
2193         quad.uncheckedAppend(outerRect.maxXMaxYCorner());
2194
2195         if (!innerBorder.radii().topRight().isZero())
2196             findIntersection(outerRect.maxXMinYCorner(), innerRect.maxXMinYCorner(), innerRect.minXMinYCorner(), innerRect.maxXMaxYCorner(), quad[1]);
2197
2198         if (!innerBorder.radii().bottomRight().isZero())
2199             findIntersection(outerRect.maxXMaxYCorner(), innerRect.maxXMaxYCorner(), innerRect.maxXMinYCorner(), innerRect.minXMaxYCorner(), quad[2]);
2200         break;
2201     }
2202
2203     // If the border matches both of its adjacent sides, don't anti-alias the clip, and
2204     // if neither side matches, anti-alias the clip.
2205     if (firstEdgeMatches == secondEdgeMatches) {
2206         bool wasAntialiased = graphicsContext.shouldAntialias();
2207         graphicsContext.setShouldAntialias(!firstEdgeMatches);
2208         graphicsContext.clipPath(Path::polygonPathFromPoints(quad), RULE_NONZERO);
2209         graphicsContext.setShouldAntialias(wasAntialiased);
2210         return;
2211     }
2212
2213     // Square off the end which shouldn't be affected by antialiasing, and clip.
2214     Vector<FloatPoint> firstQuad = {
2215         quad[0],
2216         quad[1],
2217         quad[2],
2218         side == BSTop || side == BSBottom ? FloatPoint(quad[3].x(), quad[2].y()) : FloatPoint(quad[2].x(), quad[3].y()),
2219         quad[3]
2220     };
2221     bool wasAntialiased = graphicsContext.shouldAntialias();
2222     graphicsContext.setShouldAntialias(!firstEdgeMatches);
2223     graphicsContext.clipPath(Path::polygonPathFromPoints(firstQuad), RULE_NONZERO);
2224
2225     Vector<FloatPoint> secondQuad = {
2226         quad[0],
2227         side == BSTop || side == BSBottom ? FloatPoint(quad[0].x(), quad[1].y()) : FloatPoint(quad[1].x(), quad[0].y()),
2228         quad[1],
2229         quad[2],
2230         quad[3]
2231     };
2232     // Antialiasing affects the second side.
2233     graphicsContext.setShouldAntialias(!secondEdgeMatches);
2234     graphicsContext.clipPath(Path::polygonPathFromPoints(secondQuad), RULE_NONZERO);
2235
2236     graphicsContext.setShouldAntialias(wasAntialiased);
2237 }
2238
2239 bool RenderBoxModelObject::borderObscuresBackgroundEdge(const FloatSize& contextScale) const
2240 {
2241     BorderEdge edges[4];
2242     BorderEdge::getBorderEdgeInfo(edges, style(), document().deviceScaleFactor());
2243
2244     for (int i = BSTop; i <= BSLeft; ++i) {
2245         const BorderEdge& currEdge = edges[i];
2246         // FIXME: for vertical text
2247         float axisScale = (i == BSTop || i == BSBottom) ? contextScale.height() : contextScale.width();
2248         if (!currEdge.obscuresBackgroundEdge(axisScale))
2249             return false;
2250     }
2251
2252     return true;
2253 }
2254
2255 bool RenderBoxModelObject::borderObscuresBackground() const
2256 {
2257     if (!style().hasBorder())
2258         return false;
2259
2260     // Bail if we have any border-image for now. We could look at the image alpha to improve this.
2261     if (style().borderImage().image())
2262         return false;
2263
2264     BorderEdge edges[4];
2265     BorderEdge::getBorderEdgeInfo(edges, style(), document().deviceScaleFactor());
2266
2267     for (int i = BSTop; i <= BSLeft; ++i) {
2268         const BorderEdge& currEdge = edges[i];
2269         if (!currEdge.obscuresBackground())
2270             return false;
2271     }
2272
2273     return true;
2274 }
2275
2276 bool RenderBoxModelObject::boxShadowShouldBeAppliedToBackground(const LayoutPoint&, BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* inlineFlowBox) const
2277 {
2278     if (bleedAvoidance != BackgroundBleedNone)
2279         return false;
2280
2281     if (style().hasAppearance())
2282         return false;
2283
2284     bool hasOneNormalBoxShadow = false;
2285     for (const ShadowData* currentShadow = style().boxShadow(); currentShadow; currentShadow = currentShadow->next()) {
2286         if (currentShadow->style() != Normal)
2287             continue;
2288
2289         if (hasOneNormalBoxShadow)
2290             return false;
2291         hasOneNormalBoxShadow = true;
2292
2293         if (currentShadow->spread())
2294             return false;
2295     }
2296
2297     if (!hasOneNormalBoxShadow)
2298         return false;
2299
2300     Color backgroundColor = style().visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor);
2301     if (!backgroundColor.isOpaque())
2302         return false;
2303
2304     auto* lastBackgroundLayer = &style().backgroundLayers();
2305     while (auto* next = lastBackgroundLayer->next())
2306         lastBackgroundLayer = next;
2307
2308     if (lastBackgroundLayer->clip() != BorderFillBox)
2309         return false;
2310
2311     if (lastBackgroundLayer->image() && style().hasBorderRadius())
2312         return false;
2313
2314     if (inlineFlowBox && !inlineFlowBox->boxShadowCanBeAppliedToBackground(*lastBackgroundLayer))
2315         return false;
2316
2317     if (hasOverflowClip() && lastBackgroundLayer->attachment() == LocalBackgroundAttachment)
2318         return false;
2319
2320     return true;
2321 }
2322
2323 static inline LayoutRect areaCastingShadowInHole(const LayoutRect& holeRect, int shadowExtent, int shadowSpread, const IntSize& shadowOffset)
2324 {
2325     LayoutRect bounds(holeRect);
2326     
2327     bounds.inflate(shadowExtent);
2328
2329     if (shadowSpread < 0)
2330         bounds.inflate(-shadowSpread);
2331     
2332     LayoutRect offsetBounds = bounds;
2333     offsetBounds.move(-shadowOffset);
2334     return unionRect(bounds, offsetBounds);
2335 }
2336
2337 void RenderBoxModelObject::paintBoxShadow(const PaintInfo& info, const LayoutRect& paintRect, const RenderStyle& style, ShadowStyle shadowStyle, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
2338 {
2339     // FIXME: Deal with border-image.  Would be great to use border-image as a mask.
2340     GraphicsContext& context = info.context();
2341     if (context.paintingDisabled() || !style.boxShadow())
2342         return;
2343
2344     RoundedRect border = (shadowStyle == Inset) ? style.getRoundedInnerBorderFor(paintRect, includeLogicalLeftEdge, includeLogicalRightEdge)
2345         : style.getRoundedBorderFor(paintRect, includeLogicalLeftEdge, includeLogicalRightEdge);
2346
2347     bool hasBorderRadius = style.hasBorderRadius();
2348     bool isHorizontal = style.isHorizontalWritingMode();
2349     float deviceScaleFactor = document().deviceScaleFactor();
2350
2351     bool hasOpaqueBackground = style.visitedDependentColorWithColorFilter(CSSPropertyBackgroundColor).isOpaque();
2352     for (const ShadowData* shadow = style.boxShadow(); shadow; shadow = shadow->next()) {
2353         if (shadow->style() != shadowStyle)
2354             continue;
2355
2356         // FIXME: Add subpixel support for the shadow values. Soon after the shadow offset becomes fractional,
2357         // all the early snappings here need to be pushed to the actual painting operations.
2358         IntSize shadowOffset(shadow->x(), shadow->y());
2359         int shadowRadius = shadow->radius();
2360         int shadowPaintingExtent = shadow->paintingExtent();
2361         int shadowSpread = shadow->spread();
2362         
2363         if (shadowOffset.isZero() && !shadowRadius && !shadowSpread)
2364             continue;
2365         
2366         Color shadowColor = style.colorByApplyingColorFilter(shadow->color());
2367
2368         if (shadow->style() == Normal) {
2369             RoundedRect fillRect = border;
2370             fillRect.inflate(shadowSpread);
2371             if (fillRect.isEmpty())
2372                 continue;
2373
2374             FloatRect pixelSnappedShadowRect = snapRectToDevicePixels(border.rect(), deviceScaleFactor);
2375             pixelSnappedShadowRect.inflate(shadowPaintingExtent + shadowSpread);
2376             pixelSnappedShadowRect.move(shadowOffset);
2377
2378             GraphicsContextStateSaver stateSaver(context);
2379             context.clip(pixelSnappedShadowRect);
2380
2381             // Move the fill just outside the clip, adding 1 pixel separation so that the fill does not
2382             // bleed in (due to antialiasing) if the context is transformed.
2383             IntSize extraOffset(roundToInt(paintRect.width()) + std::max(0, shadowOffset.width()) + shadowPaintingExtent + 2 * shadowSpread + 1, 0);
2384             shadowOffset -= extraOffset;
2385             fillRect.move(extraOffset);
2386
2387             if (shadow->isWebkitBoxShadow())
2388                 context.setLegacyShadow(shadowOffset, shadowRadius, shadowColor);
2389             else
2390                 context.setShadow(shadowOffset, shadowRadius, shadowColor);
2391
2392             FloatRoundedRect rectToClipOut = border.pixelSnappedRoundedRectForPainting(deviceScaleFactor);
2393             FloatRoundedRect pixelSnappedFillRect = fillRect.pixelSnappedRoundedRectForPainting(deviceScaleFactor);
2394             if (hasBorderRadius) {
2395                 // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
2396                 // when painting the shadow. On the other hand, it introduces subpixel gaps along the
2397                 // corners. Those are avoided by insetting the clipping path by one pixel.
2398                 if (hasOpaqueBackground)
2399                     rectToClipOut.inflateWithRadii(LayoutUnit::fromPixel(-1));
2400
2401                 if (!rectToClipOut.isEmpty())
2402                     context.clipOutRoundedRect(rectToClipOut);
2403
2404                 RoundedRect influenceRect(LayoutRect(pixelSnappedShadowRect), border.radii());
2405                 influenceRect.expandRadii(2 * shadowPaintingExtent + shadowSpread);
2406
2407                 if (allCornersClippedOut(influenceRect, info.rect))
2408                     context.fillRect(pixelSnappedFillRect.rect(), Color::black);
2409                 else {
2410                     pixelSnappedFillRect.expandRadii(shadowSpread);
2411                     if (!pixelSnappedFillRect.isRenderable())
2412                         pixelSnappedFillRect.adjustRadii();
2413                     context.fillRoundedRect(pixelSnappedFillRect, Color::black);
2414                 }
2415             } else {
2416                 // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
2417                 // when painting the shadow. On the other hand, it introduces subpixel gaps along the
2418                 // edges if they are not pixel-aligned. Those are avoided by insetting the clipping path
2419                 // by one pixel.
2420                 if (hasOpaqueBackground) {
2421                     // FIXME: The function to decide on the policy based on the transform should be a named function.
2422                     // FIXME: It's not clear if this check is right. What about integral scale factors?
2423                     AffineTransform transform = context.getCTM();
2424                     if (transform.a() != 1 || (transform.d() != 1 && transform.d() != -1) || transform.b() || transform.c())
2425                         rectToClipOut.inflate(LayoutUnit::fromPixel(-1).toFloat());
2426                 }
2427
2428                 if (!rectToClipOut.isEmpty())
2429                     context.clipOut(rectToClipOut.rect());
2430                 context.fillRect(pixelSnappedFillRect.rect(), Color::black);
2431             }
2432         } else {
2433             // Inset shadow.
2434             FloatRoundedRect pixelSnappedBorderRect = border.pixelSnappedRoundedRectForPainting(deviceScaleFactor);
2435             FloatRect pixelSnappedHoleRect = pixelSnappedBorderRect.rect();
2436             pixelSnappedHoleRect.inflate(-shadowSpread);
2437
2438             if (pixelSnappedHoleRect.isEmpty()) {
2439                 if (hasBorderRadius)
2440                     context.fillRoundedRect(pixelSnappedBorderRect, shadowColor);
2441                 else
2442                     context.fillRect(pixelSnappedBorderRect.rect(), shadowColor);
2443                 continue;
2444             }
2445
2446             if (!includeLogicalLeftEdge) {
2447                 if (isHorizontal) {
2448                     pixelSnappedHoleRect.move(-std::max(shadowOffset.width(), 0) - shadowPaintingExtent, 0);
2449                     pixelSnappedHoleRect.setWidth(pixelSnappedHoleRect.width() + std::max(shadowOffset.width(), 0) + shadowPaintingExtent);
2450                 } else {
2451                     pixelSnappedHoleRect.move(0, -std::max(shadowOffset.height(), 0) - shadowPaintingExtent);
2452                     pixelSnappedHoleRect.setHeight(pixelSnappedHoleRect.height() + std::max(shadowOffset.height(), 0) + shadowPaintingExtent);
2453                 }
2454             }
2455             if (!includeLogicalRightEdge) {
2456                 if (isHorizontal)
2457                     pixelSnappedHoleRect.setWidth(pixelSnappedHoleRect.width() - std::min(shadowOffset.width(), 0) + shadowPaintingExtent);
2458                 else
2459                     pixelSnappedHoleRect.setHeight(pixelSnappedHoleRect.height() - std::min(shadowOffset.height(), 0) + shadowPaintingExtent);
2460             }
2461
2462             Color fillColor(shadowColor.red(), shadowColor.green(), shadowColor.blue(), 255);
2463
2464             FloatRect pixelSnappedOuterRect = snapRectToDevicePixels(areaCastingShadowInHole(LayoutRect(pixelSnappedBorderRect.rect()), shadowPaintingExtent, shadowSpread, shadowOffset), deviceScaleFactor);
2465             FloatRoundedRect pixelSnappedRoundedHole = FloatRoundedRect(pixelSnappedHoleRect, pixelSnappedBorderRect.radii());
2466
2467             GraphicsContextStateSaver stateSaver(context);
2468             if (hasBorderRadius) {
2469                 context.clipRoundedRect(pixelSnappedBorderRect);
2470                 pixelSnappedRoundedHole.shrinkRadii(shadowSpread);
2471             } else
2472                 context.clip(pixelSnappedBorderRect.rect());
2473
2474             IntSize extraOffset(2 * roundToInt(paintRect.width()) + std::max(0, shadowOffset.width()) + shadowPaintingExtent - 2 * shadowSpread + 1, 0);
2475             context.translate(extraOffset);
2476             shadowOffset -= extraOffset;
2477
2478             if (shadow->isWebkitBoxShadow())
2479                 context.setLegacyShadow(shadowOffset, shadowRadius, shadowColor);
2480             else
2481                 context.setShadow(shadowOffset, shadowRadius, shadowColor);
2482
2483             context.fillRectWithRoundedHole(pixelSnappedOuterRect, pixelSnappedRoundedHole, fillColor);
2484         }
2485     }
2486 }
2487
2488 LayoutUnit RenderBoxModelObject::containingBlockLogicalWidthForContent() const
2489 {
2490     if (auto* containingBlock = this->containingBlock())
2491         return containingBlock->availableLogicalWidth();
2492     return { };
2493 }
2494
2495 RenderBoxModelObject* RenderBoxModelObject::continuation() const
2496 {
2497     if (!hasContinuationChainNode())
2498         return nullptr;
2499
2500     auto& continuationChainNode = *continuationChainNodeMap().get(this);
2501     if (!continuationChainNode.next)
2502         return nullptr;
2503     return continuationChainNode.next->renderer.get();
2504 }
2505
2506 RenderInline* RenderBoxModelObject::inlineContinuation() const
2507 {
2508     if (!hasContinuationChainNode())
2509         return nullptr;
2510
2511     for (auto* next = continuationChainNodeMap().get(this)->next; next; next = next->next) {
2512         if (is<RenderInline>(*next->renderer))
2513             return downcast<RenderInline>(next->renderer.get());
2514     }
2515     return nullptr;
2516 }
2517
2518 RenderBoxModelObject::ContinuationChainNode* RenderBoxModelObject::continuationChainNode() const
2519 {
2520     return continuationChainNodeMap().get(this);
2521 }
2522
2523 void RenderBoxModelObject::insertIntoContinuationChainAfter(RenderBoxModelObject& afterRenderer)
2524 {
2525     ASSERT(isContinuation());
2526     ASSERT(!continuationChainNodeMap().contains(this));
2527
2528     auto& after = afterRenderer.ensureContinuationChainNode();
2529     ensureContinuationChainNode().insertAfter(after);
2530 }
2531
2532 void RenderBoxModelObject::removeFromContinuationChain()
2533 {
2534     ASSERT(hasContinuationChainNode());
2535     ASSERT(continuationChainNodeMap().contains(this));
2536     setHasContinuationChainNode(false);
2537     continuationChainNodeMap().remove(this);
2538 }
2539
2540 auto RenderBoxModelObject::ensureContinuationChainNode() -> ContinuationChainNode&
2541 {
2542     setHasContinuationChainNode(true);
2543     return *continuationChainNodeMap().ensure(this, [&] {
2544         return std::make_unique<ContinuationChainNode>(*this);
2545     }).iterator->value;
2546 }
2547
2548 RenderTextFragment* RenderBoxModelObject::firstLetterRemainingText() const
2549 {
2550     if (!isFirstLetter())
2551         return nullptr;
2552     return firstLetterRemainingTextMap().get(this).get();
2553 }
2554
2555 void RenderBoxModelObject::setFirstLetterRemainingText(RenderTextFragment& remainingText)
2556 {
2557     ASSERT(isFirstLetter());
2558     firstLetterRemainingTextMap().set(this, makeWeakPtr(remainingText));
2559 }
2560
2561 void RenderBoxModelObject::clearFirstLetterRemainingText()
2562 {
2563     ASSERT(isFirstLetter());
2564     firstLetterRemainingTextMap().remove(this);
2565 }
2566
2567 LayoutRect RenderBoxModelObject::localCaretRectForEmptyElement(LayoutUnit width, LayoutUnit textIndentOffset)
2568 {
2569     ASSERT(!firstChild());
2570
2571     // FIXME: This does not take into account either :first-line or :first-letter
2572     // However, as soon as some content is entered, the line boxes will be
2573     // constructed and this kludge is not called any more. So only the caret size
2574     // of an empty :first-line'd block is wrong. I think we can live with that.
2575     const RenderStyle& currentStyle = firstLineStyle();
2576     LayoutUnit height = lineHeight(true, currentStyle.isHorizontalWritingMode() ? HorizontalLine : VerticalLine);
2577
2578     enum CaretAlignment { alignLeft, alignRight, alignCenter };
2579
2580     CaretAlignment alignment = alignLeft;
2581
2582     switch (currentStyle.textAlign()) {
2583     case LEFT:
2584     case WEBKIT_LEFT:
2585         break;
2586     case CENTER:
2587     case WEBKIT_CENTER:
2588         alignment = alignCenter;
2589         break;
2590     case RIGHT:
2591     case WEBKIT_RIGHT:
2592         alignment = alignRight;
2593         break;
2594     case JUSTIFY:
2595     case TASTART:
2596         if (!currentStyle.isLeftToRightDirection())
2597             alignment = alignRight;
2598         break;
2599     case TAEND:
2600         if (currentStyle.isLeftToRightDirection())
2601             alignment = alignRight;
2602         break;
2603     }
2604
2605     LayoutUnit x = borderLeft() + paddingLeft();
2606     LayoutUnit maxX = width - borderRight() - paddingRight();
2607
2608     switch (alignment) {
2609     case alignLeft:
2610         if (currentStyle.isLeftToRightDirection())
2611             x += textIndentOffset;
2612         break;
2613     case alignCenter:
2614         x = (x + maxX) / 2;
2615         if (currentStyle.isLeftToRightDirection())
2616             x += textIndentOffset / 2;
2617         else
2618             x -= textIndentOffset / 2;
2619         break;
2620     case alignRight:
2621         x = maxX - caretWidth;
2622         if (!currentStyle.isLeftToRightDirection())
2623             x -= textIndentOffset;
2624         break;
2625     }
2626     x = std::min(x, std::max<LayoutUnit>(maxX - caretWidth, 0));
2627
2628     LayoutUnit y = paddingTop() + borderTop();
2629
2630     return currentStyle.isHorizontalWritingMode() ? LayoutRect(x, y, caretWidth, height) : LayoutRect(y, x, height, caretWidth);
2631 }
2632
2633 bool RenderBoxModelObject::shouldAntialiasLines(GraphicsContext& context)
2634 {
2635     // FIXME: We may want to not antialias when scaled by an integral value,
2636     // and we may want to antialias when translated by a non-integral value.
2637     return !context.getCTM().isIdentityOrTranslationOrFlipped();
2638 }
2639
2640 void RenderBoxModelObject::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
2641 {
2642     RenderElement* container = this->container();
2643     if (!container)
2644         return;
2645     
2646     // FIXME: This code is wrong for named flow threads since it only works for content in the first region.
2647     // We also don't want to run it for multicolumn flow threads, since we can use our knowledge of column
2648     // geometry to actually get a better result.
2649     // The point inside a box that's inside a region has its coordinates relative to the region,
2650     // not the FragmentedFlow that is its container in the RenderObject tree.
2651     if (is<RenderBox>(*this) && container->isOutOfFlowRenderFragmentedFlow()) {
2652         RenderFragmentContainer* startFragment = nullptr;
2653         RenderFragmentContainer* endFragment = nullptr;
2654         if (downcast<RenderFragmentedFlow>(*container).getFragmentRangeForBox(downcast<RenderBox>(this), startFragment, endFragment))
2655             container = startFragment;
2656     }
2657
2658     container->mapAbsoluteToLocalPoint(mode, transformState);
2659
2660     LayoutSize containerOffset = offsetFromContainer(*container, LayoutPoint());
2661
2662     bool preserve3D = mode & UseTransforms && (container->style().preserves3D() || style().preserves3D());
2663     if (mode & UseTransforms && shouldUseTransformFromContainer(container)) {
2664         TransformationMatrix t;
2665         getTransformFromContainer(container, containerOffset, t);
2666         transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
2667     } else
2668         transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
2669 }
2670
2671 } // namespace WebCore