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