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