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