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