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