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