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