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