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