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