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.
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.
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.
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.
27 #include "core/rendering/RenderBoxModelObject.h"
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"
55 using namespace HTMLNames;
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;
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;
72 void RenderBoxModelObject::setSelectionState(SelectionState state)
74 if (state == SelectionInside && selectionState() != SelectionNone)
77 if ((state == SelectionStart && selectionState() == SelectionEnd)
78 || (state == SelectionEnd && selectionState() == SelectionStart))
79 RenderObject::setSelectionState(SelectionBoth);
81 RenderObject::setSelectionState(state);
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);
91 void RenderBoxModelObject::contentChanged(ContentChangeType changeType)
96 layer()->contentChanged(changeType);
99 bool RenderBoxModelObject::hasAcceleratedCompositing() const
101 return view()->compositor()->hasAcceleratedCompositing();
104 InterpolationQuality RenderBoxModelObject::chooseInterpolationQuality(GraphicsContext* context, Image* image, const void* layer, const LayoutSize& size)
106 return ImageQualityController::imageQualityController()->chooseInterpolationQuality(context, this, image, layer, size);
109 RenderBoxModelObject::RenderBoxModelObject(ContainerNode* node)
110 : RenderLayerModelObject(node)
114 RenderBoxModelObject::~RenderBoxModelObject()
116 ImageQualityController::remove(this);
119 void RenderBoxModelObject::willBeDestroyed()
121 // A continuation of this RenderObject should be destroyed at subclasses.
122 ASSERT(!continuation());
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);
129 RenderLayerModelObject::willBeDestroyed();
132 bool RenderBoxModelObject::calculateHasBoxDecorations() const
134 RenderStyle* styleToUse = style();
136 return hasBackground() || styleToUse->hasBorder() || styleToUse->hasAppearance() || styleToUse->boxShadow();
139 void RenderBoxModelObject::updateFromStyle()
141 RenderLayerModelObject::updateFromStyle();
143 RenderStyle* styleToUse = style();
144 setHasBoxDecorationBackground(calculateHasBoxDecorations());
145 setInline(styleToUse->isDisplayInlineType());
146 setPositionState(styleToUse->position());
147 setHorizontalWritingMode(styleToUse->isHorizontalWritingMode());
150 static LayoutSize accumulateInFlowPositionOffsets(const RenderObject* child)
152 if (!child->isAnonymousBlock() || !child->isRelPositioned())
155 RenderObject* p = toRenderBlock(child)->inlineElementContinuation();
156 while (p && p->isRenderInline()) {
157 if (p->isRelPositioned()) {
158 RenderInline* renderInline = toRenderInline(p);
159 offset += renderInline->offsetForInFlowPosition();
166 bool RenderBoxModelObject::hasAutoHeightOrContainingBlockWithAutoHeight() const
168 Length logicalHeightLength = style()->logicalHeight();
169 if (logicalHeightLength.isAuto())
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())
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();
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())
191 // Match RenderBox::availableLogicalHeightUsing by special casing
192 // the render view. The available height is taken from the frame.
193 if (cb->isRenderView())
196 if (cb->isOutOfFlowPositioned() && !cb->style()->logicalTop().isAuto() && !cb->style()->logicalBottom().isAuto())
199 // If the height of the containing block computes to 'auto', then it hasn't been 'specified explicitly'.
200 return cb->hasAutoHeightOrContainingBlockWithAutoHeight();
203 LayoutSize RenderBoxModelObject::relativePositionOffset() const
205 LayoutSize offset = accumulateInFlowPositionOffsets(this);
207 RenderBlock* containingBlock = this->containingBlock();
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()));
217 offset.expand(valueForLength(style()->left(), containingBlock->availableWidth()), 0);
218 } else if (!style()->right().isAuto()) {
219 offset.expand(-valueForLength(style()->right(), containingBlock->availableWidth()), 0);
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()));
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()));
243 LayoutPoint RenderBoxModelObject::adjustedPositionRelativeToOffsetParent(const LayoutPoint& startPoint) const
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();
250 LayoutPoint referencePoint = startPoint;
251 referencePoint.move(parent()->columnOffset(referencePoint));
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();
258 return referencePoint;
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());
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));
277 if (offsetParent->isBox() && offsetParent->isBody() && !offsetParent->isPositioned())
278 referencePoint.moveBy(toRenderBox(offsetParent)->topLeftLocation());
282 return referencePoint;
285 LayoutSize RenderBoxModelObject::offsetForInFlowPosition() const
287 return isRelPositioned() ? relativePositionOffset() : LayoutSize();
290 LayoutUnit RenderBoxModelObject::offsetLeft() const
292 // Note that RenderInline and RenderBox override this to pass a different
293 // startPoint to adjustedPositionRelativeToOffsetParent.
294 return adjustedPositionRelativeToOffsetParent(LayoutPoint()).x();
297 LayoutUnit RenderBoxModelObject::offsetTop() const
299 // Note that RenderInline and RenderBox override this to pass a different
300 // startPoint to adjustedPositionRelativeToOffsetParent.
301 return adjustedPositionRelativeToOffsetParent(LayoutPoint()).y();
304 int RenderBoxModelObject::pixelSnappedOffsetWidth() const
306 return snapSizeToPixel(offsetWidth(), offsetLeft());
309 int RenderBoxModelObject::pixelSnappedOffsetHeight() const
311 return snapSizeToPixel(offsetHeight(), offsetTop());
314 LayoutUnit RenderBoxModelObject::computedCSSPadding(const Length& padding) const
317 if (padding.isPercent())
318 w = containingBlockLogicalWidthForContent();
319 return minimumValueForLength(padding, w);
322 RoundedRect RenderBoxModelObject::getBackgroundRoundedRect(const LayoutRect& borderRect, InlineFlowBox* box, LayoutUnit inlineBoxWidth, LayoutUnit inlineBoxHeight,
323 bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
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());
334 void RenderBoxModelObject::clipRoundedInnerRect(GraphicsContext * context, const LayoutRect& rect, const RoundedRect& clipRect)
336 if (clipRect.isRenderable())
337 context->clipRoundedRect(clipRect);
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));
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));
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));
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));
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)
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())));
377 LayoutRect RenderBoxModelObject::borderInnerRectAdjustedForBleedAvoidance(GraphicsContext* context, const LayoutRect& rect, BackgroundBleedAvoidance bleedAvoidance) const
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;
383 RoundedRect RenderBoxModelObject::backgroundRoundedRectAdjustedForBleedAvoidance(GraphicsContext* context, const LayoutRect& borderRect, BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* box, const LayoutSize& boxSize, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
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);
389 if (bleedAvoidance == BackgroundBleedBackgroundOverBorder)
390 return style()->getRoundedInnerBorderFor(borderRect, includeLogicalLeftEdge, includeLogicalRightEdge);
392 return getBackgroundRoundedRect(borderRect, box, boxSize.width(), boxSize.height(), includeLogicalLeftEdge, includeLogicalRightEdge);
395 static void applyBoxShadowForBackground(GraphicsContext* context, const RenderObject* renderer)
397 const ShadowList* shadowList = renderer->style()->boxShadow();
399 for (size_t i = shadowList->shadows().size(); i--; ) {
400 const ShadowData& boxShadow = shadowList->shadows()[i];
401 if (boxShadow.style() != Normal)
403 FloatSize shadowOffset(boxShadow.x(), boxShadow.y());
404 context->setShadow(shadowOffset, boxShadow.blur(), boxShadow.color(),
405 DrawLooperBuilder::ShadowRespectsTransforms, DrawLooperBuilder::ShadowIgnoresAlpha);
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)
413 GraphicsContext* context = paintInfo.context;
417 bool includeLeftEdge = box ? box->includeLogicalLeftEdge() : true;
418 bool includeRightEdge = box ? box->includeLogicalRightEdge() : true;
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();
425 Color bgColor = color;
426 StyleImage* bgImage = bgLayer.image();
427 bool shouldPaintBackgroundImage = bgImage && bgImage->canRender(*this, style()->effectiveZoom());
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;
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
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;
453 bool colorVisible = bgColor.alpha();
455 // Fast path for drawing simple color backgrounds.
456 if (!isRoot && !clippedWithLocalScrolling && !shouldPaintBackgroundImage && isBorderFill && !bgLayer.next()) {
460 bool boxShadowShouldBeAppliedToBackground = this->boxShadowShouldBeAppliedToBackground(bleedAvoidance, box);
461 GraphicsContextStateSaver shadowStateSaver(*context, boxShadowShouldBeAppliedToBackground);
462 if (boxShadowShouldBeAppliedToBackground)
463 applyBoxShadowForBackground(context, this);
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);
471 clipRoundedInnerRect(context, rect, border);
472 context->fillRect(border.rect(), bgColor);
476 context->fillRect(pixelSnappedIntRect(rect), bgColor);
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);
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);
495 clipRoundedInnerRect(context, rect, border);
498 int bLeft = includeLeftEdge ? borderLeft() : 0;
499 int bRight = includeRightEdge ? borderRight() : 0;
500 LayoutUnit pLeft = includeLeftEdge ? paddingLeft() : LayoutUnit();
501 LayoutUnit pRight = includeRightEdge ? paddingRight() : LayoutUnit();
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()));
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());
517 GraphicsContextStateSaver backgroundClipStateSaver(*context, false);
520 switch (bgLayer.clip()) {
522 case ContentFillBox: {
523 if (clipToBorderRadius)
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);
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);
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);
554 ASSERT_NOT_REACHED();
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;
563 if (!bgLayer.next() && bgColor.hasAlpha() && view()->frameView()) {
564 Element* ownerElement = document().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();
573 // Can't scroll a frameset document anyway.
574 isOpaqueRoot = body->hasTagName(framesetTag);
576 // SVG documents and XML documents with SVG root nodes are transparent.
577 isOpaqueRoot = !document().hasSVGRootNode();
581 isOpaqueRoot = !view()->frameView()->isTransparent();
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);
596 GraphicsContextStateSaver shadowStateSaver(*context, boxShadowShouldBeAppliedToBackground);
597 if (boxShadowShouldBeAppliedToBackground)
598 applyBoxShadowForBackground(context, this);
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();
606 if (baseColor.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);
615 } else if (bgColor.alpha()) {
616 context->fillRect(backgroundRect, bgColor, context->compositeOperation());
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);
641 if (bgLayer.clip() == TextFillBox) {
642 // Create the text mask layer.
643 context->setCompositeOperation(CompositeDestinationIn);
644 context->beginTransparencyLayer(1);
646 // FIXME: Workaround for https://code.google.com/p/skia/issues/detail?id=1291.
647 context->clearRect(maskRect);
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);
654 RootInlineBox& root = box->root();
655 box->paint(info, LayoutPoint(scrolledPaintRect.x() - box->x(), scrolledPaintRect.y() - box->y()), root.lineTop(), root.lineBottom());
657 LayoutSize localOffset = isBox() ? toRenderBox(this)->locationOffset() : LayoutSize();
658 paint(info, scrolledPaintRect.location() - localOffset);
666 static inline int resolveWidthForRatio(int height, const FloatSize& intrinsicRatio)
668 return ceilf(height * intrinsicRatio.width() / intrinsicRatio.height());
671 static inline int resolveHeightForRatio(int width, const FloatSize& intrinsicRatio)
673 return ceilf(width * intrinsicRatio.height() / intrinsicRatio.width());
676 static inline IntSize resolveAgainstIntrinsicWidthOrHeightAndRatio(const IntSize& size, const FloatSize& intrinsicRatio, int useWidth, int useHeight)
678 if (intrinsicRatio.isEmpty()) {
680 return IntSize(useWidth, size.height());
681 return IntSize(size.width(), useHeight);
685 return IntSize(useWidth, resolveHeightForRatio(useWidth, intrinsicRatio));
686 return IntSize(resolveWidthForRatio(useHeight, intrinsicRatio), useHeight);
689 static inline IntSize resolveAgainstIntrinsicRatio(const IntSize& size, const FloatSize& intrinsicRatio)
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.
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());
706 // Only the first solution fits.
707 return IntSize(solutionWidth, size.height());
710 // Only the second solution fits, assert that.
711 ASSERT(solutionHeight <= size.height());
712 return IntSize(size.width(), solutionHeight);
715 IntSize RenderBoxModelObject::calculateImageIntrinsicDimensions(StyleImage* image, const IntSize& positioningAreaSize, ScaleByEffectiveZoomOrNot shouldScaleOrNot) const
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());
721 Length intrinsicWidth;
722 Length intrinsicHeight;
723 FloatSize intrinsicRatio;
724 image->computeIntrinsicDimensions(this, intrinsicWidth, intrinsicHeight, intrinsicRatio);
726 ASSERT(!intrinsicWidth.isPercent());
727 ASSERT(!intrinsicHeight.isPercent());
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);
735 if (!resolvedSize.isEmpty())
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());
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);
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;
756 static inline void applySubPixelHeuristicForTileSize(LayoutSize& tileSize, const IntSize& positioningAreaSize)
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());
762 IntSize RenderBoxModelObject::calculateFillTileSize(const FillLayer& fillLayer, const IntSize& positioningAreaSize) const
764 StyleImage* image = fillLayer.image();
765 EFillSizeType type = fillLayer.size().type;
767 IntSize imageIntrinsicSize = calculateImageIntrinsicDimensions(image, positioningAreaSize, ScaleByEffectiveZoom);
768 imageIntrinsicSize.scale(1 / image->imageScaleFactor(), 1 / image->imageScaleFactor());
771 LayoutSize tileSize = positioningAreaSize;
773 Length layerWidth = fillLayer.size().size.width();
774 Length layerHeight = fillLayer.size().size.height();
776 if (layerWidth.isFixed())
777 tileSize.setWidth(layerWidth.value());
778 else if (layerWidth.isPercent())
779 tileSize.setWidth(valueForLength(layerWidth, positioningAreaSize.width()));
781 if (layerHeight.isFixed())
782 tileSize.setHeight(layerHeight.value());
783 else if (layerHeight.isPercent())
784 tileSize.setHeight(valueForLength(layerHeight, positioningAreaSize.height()));
786 applySubPixelHeuristicForTileSize(tileSize, positioningAreaSize);
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;
801 tileSize.clampNegativeToZero();
802 return flooredIntSize(tileSize);
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;
809 // If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for ‘contain’.
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)));
823 ASSERT_NOT_REACHED();
827 void RenderBoxModelObject::BackgroundImageGeometry::setNoRepeatX(int xOffset)
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));
833 void RenderBoxModelObject::BackgroundImageGeometry::setNoRepeatY(int yOffset)
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));
840 void RenderBoxModelObject::BackgroundImageGeometry::useFixedAttachment(const IntPoint& attachmentPoint)
842 IntPoint alignedPoint = attachmentPoint;
843 m_phase.move(std::max(alignedPoint.x() - m_destRect.x(), 0), std::max(alignedPoint.y() - m_destRect.y(), 0));
846 void RenderBoxModelObject::BackgroundImageGeometry::clip(const IntRect& clipRect)
848 m_destRect.intersect(clipRect);
851 IntPoint RenderBoxModelObject::BackgroundImageGeometry::relativePhase() const
853 IntPoint phase = m_phase;
854 phase += m_destRect.location() - m_destOrigin;
858 bool RenderBoxModelObject::fixedBackgroundPaintsInLocalCoordinates() const
860 if (!isDocumentElement())
863 if (view()->frameView() && view()->frameView()->paintBehavior() & PaintBehaviorFlattenCompositingLayers)
866 RenderLayer* rootLayer = view()->layer();
867 if (!rootLayer || rootLayer->compositingState() == NotComposited)
870 return rootLayer->compositedLayerMapping()->backgroundLayerPaintsFixedRootBackground();
873 static inline int getSpace(int areaSize, int tileSize)
875 int numberOfTiles = areaSize / tileSize;
878 if (numberOfTiles > 1)
879 space = lroundf((float)(areaSize - numberOfTiles * tileSize) / (numberOfTiles - 1));
884 void RenderBoxModelObject::calculateBackgroundImageGeometry(const RenderLayerModelObject* paintContainer, const FillLayer& fillLayer, const LayoutRect& paintRect,
885 BackgroundImageGeometry& geometry, RenderObject* backgroundObject) const
889 IntSize positioningAreaSize;
890 IntRect snappedPaintRect = pixelSnappedIntRect(paintRect);
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;
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;
905 if (!fixedAttachment) {
906 geometry.setDestRect(snappedPaintRect);
908 LayoutUnit right = 0;
909 LayoutUnit bottom = 0;
911 if (fillLayer.origin() != BorderFillBox) {
913 right = borderRight();
915 bottom = borderBottom();
916 if (fillLayer.origin() == ContentFillBox) {
917 left += paddingLeft();
918 right += paddingRight();
920 bottom += paddingBottom();
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();
932 positioningAreaSize = pixelSnappedIntSize(paintRect.size() - LayoutSize(left + right, top + bottom), paintRect.location());
934 geometry.setHasNonLocalGeometry();
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()));
942 if (paintContainer) {
943 IntPoint absoluteContainerOffset = roundedIntPoint(paintContainer->localToAbsolute(FloatPoint()));
944 viewportRect.moveBy(-absoluteContainerOffset);
947 geometry.setDestRect(pixelSnappedIntRect(viewportRect));
948 positioningAreaSize = geometry.destRect().size();
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);
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();
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()));
965 if (fillLayer.size().size.height().isAuto() && backgroundRepeatY != RoundFill) {
966 fillTileSize.setHeight(fillTileSize.height() * positioningAreaSize.width() / (nrTiles * fillTileSize.width()));
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());
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()));
979 if (fillLayer.size().size.width().isAuto() && backgroundRepeatX != RoundFill) {
980 fillTileSize.setWidth(fillTileSize.width() * positioningAreaSize.height() / (nrTiles * fillTileSize.height()));
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());
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;
997 computedXPosition = roundedMinimumValueForLength(Length(), availableWidth);
998 geometry.setSpaceSize(IntSize(space, 0));
999 geometry.setPhaseX(actualWidth ? actualWidth - roundToInt(computedXPosition + left) % actualWidth : 0);
1001 backgroundRepeatX = NoRepeatFill;
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()));
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;
1018 computedYPosition = roundedMinimumValueForLength(Length(), availableHeight);
1019 geometry.setSpaceSize(IntSize(geometry.spaceSize().width(), space));
1020 geometry.setPhaseY(actualHeight ? actualHeight - roundToInt(computedYPosition + top) % actualHeight : 0);
1022 backgroundRepeatY = NoRepeatFill;
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));
1031 if (fixedAttachment)
1032 geometry.useFixedAttachment(snappedPaintRect.location());
1034 geometry.clip(snappedPaintRect);
1035 geometry.setDestOrigin(geometry.destRect().location());
1038 static LayoutUnit computeBorderImageSide(const BorderImageLength& borderSlice, LayoutUnit borderSide, LayoutUnit imageSide, LayoutUnit boxExtent)
1040 if (borderSlice.isNumber())
1041 return borderSlice.number() * borderSide;
1042 if (borderSlice.length().isAuto())
1044 return valueForLength(borderSlice.length(), boxExtent);
1047 bool RenderBoxModelObject::paintNinePieceImage(GraphicsContext* graphicsContext, const LayoutRect& rect, const RenderStyle* style,
1048 const NinePieceImage& ninePieceImage, CompositeOperator op)
1050 StyleImage* styleImage = ninePieceImage.image();
1054 if (!styleImage->isLoaded())
1055 return true; // Never paint a nine-piece image incrementally, but don't paint the fallback borders either.
1057 if (!styleImage->canRender(*this, style->effectiveZoom()))
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);
1066 IntSize imageSize = calculateImageIntrinsicDimensions(styleImage, borderImageRect.size(), DoNotScaleByEffectiveZoom);
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());
1071 int imageWidth = imageSize.width();
1072 int imageHeight = imageSize.height();
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;
1080 ENinePieceImageRule hRule = ninePieceImage.horizontalRule();
1081 ENinePieceImageRule vRule = ninePieceImage.verticalRule();
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());
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;
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;
1109 RefPtr<Image> image = styleImage->image(this, imageSize);
1111 float destinationWidth = borderImageRect.width() - leftWidth - rightWidth;
1112 float destinationHeight = borderImageRect.height() - topWidth - bottomWidth;
1114 float sourceWidth = imageWidth - leftSlice - rightSlice;
1115 float sourceHeight = imageHeight - topSlice - bottomSlice;
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;
1123 // Paint the top and bottom left corners.
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)
1128 graphicsContext->drawImage(image.get(), IntRect(borderImageRect.location(), IntSize(leftWidth, topWidth)),
1129 LayoutRect(0, 0, leftSlice, topSlice), op);
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)
1134 graphicsContext->drawImage(image.get(), IntRect(borderImageRect.x(), borderImageRect.maxY() - bottomWidth, leftWidth, bottomWidth),
1135 LayoutRect(0, imageHeight - bottomSlice, leftSlice, bottomSlice), op);
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);
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)
1150 graphicsContext->drawImage(image.get(), IntRect(borderImageRect.maxX() - rightWidth, borderImageRect.y(), rightWidth, topWidth),
1151 LayoutRect(imageWidth - rightSlice, 0, rightSlice, topSlice), op);
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)
1156 graphicsContext->drawImage(image.get(), IntRect(borderImageRect.maxX() - rightWidth, borderImageRect.maxY() - bottomWidth, rightWidth, bottomWidth),
1157 LayoutRect(imageWidth - rightSlice, imageHeight - bottomSlice, rightSlice, bottomSlice), op);
1159 // Paint the right edge.
1160 if (sourceHeight > 0)
1161 graphicsContext->drawTiledImage(image.get(), IntRect(borderImageRect.maxX() - rightWidth, borderImageRect.y() + topWidth, rightWidth,
1163 IntRect(imageWidth - rightSlice, topSlice, rightSlice, sourceHeight),
1164 FloatSize(rightSideScale, rightSideScale),
1165 Image::StretchTile, (Image::TileRule)vRule, op);
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);
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);
1182 // Paint the middle.
1184 FloatSize middleScaleFactor(1, 1);
1186 middleScaleFactor.setWidth(topSideScale);
1187 else if (drawBottom)
1188 middleScaleFactor.setWidth(bottomSideScale);
1190 middleScaleFactor.setHeight(leftSideScale);
1192 middleScaleFactor.setHeight(rightSideScale);
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);
1201 if (vRule == StretchImageRule)
1202 middleScaleFactor.setHeight(destinationHeight / sourceHeight);
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);
1215 BorderEdge(int edgeWidth, const Color& edgeColor, EBorderStyle edgeStyle, bool edgeIsTransparent, bool edgeIsPresent = true)
1219 , isTransparent(edgeIsTransparent)
1220 , isPresent(edgeIsPresent)
1222 if (style == DOUBLE && edgeWidth < 3)
1229 , isTransparent(false)
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
1239 if (!isPresent || isTransparent || (width * scale) < 2 || color.hasAlpha() || style == BHIDDEN)
1242 if (style == DOTTED || style == DASHED)
1245 if (style == DOUBLE)
1246 return width >= 5 * scale; // The outer band needs to be >= 2px wide at unit scale.
1250 bool obscuresBackground() const
1252 if (!isPresent || isTransparent || color.hasAlpha() || style == BHIDDEN)
1255 if (style == DOTTED || style == DASHED || style == DOUBLE)
1261 int usedWidth() const { return isPresent ? width : 0; }
1263 void getDoubleBorderStripeWidths(int& outerWidth, int& innerWidth) const
1265 int fullWidth = usedWidth();
1266 outerWidth = fullWidth / 3;
1267 innerWidth = fullWidth * 2 / 3;
1269 // We need certain integer rounding results
1270 if (fullWidth % 3 == 2)
1273 if (fullWidth % 3 == 1)
1284 static bool allCornersClippedOut(const RoundedRect& border, const LayoutRect& clipRect)
1286 LayoutRect boundingRect = border.rect();
1287 if (clipRect.contains(boundingRect))
1290 RoundedRect::Radii radii = border.radii();
1292 LayoutRect topLeftRect(boundingRect.location(), radii.topLeft());
1293 if (clipRect.intersects(topLeftRect))
1296 LayoutRect topRightRect(boundingRect.location(), radii.topRight());
1297 topRightRect.setX(boundingRect.maxX() - topRightRect.width());
1298 if (clipRect.intersects(topRightRect))
1301 LayoutRect bottomLeftRect(boundingRect.location(), radii.bottomLeft());
1302 bottomLeftRect.setY(boundingRect.maxY() - bottomLeftRect.height());
1303 if (clipRect.intersects(bottomLeftRect))
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))
1315 static bool borderWillArcInnerEdge(const LayoutSize& firstRadius, const FloatSize& secondRadius)
1317 return !firstRadius.isZero() || !secondRadius.isZero();
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
1328 static inline BorderEdgeFlag edgeFlagForSide(BoxSide side)
1330 return static_cast<BorderEdgeFlag>(1 << side);
1333 static inline bool includesEdge(BorderEdgeFlags flags, BoxSide side)
1335 return flags & edgeFlagForSide(side);
1338 static inline bool includesAdjacentEdges(BorderEdgeFlags flags)
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);
1346 inline bool edgesShareColor(const BorderEdge& firstEdge, const BorderEdge& secondEdge)
1348 return firstEdge.color == secondEdge.color;
1351 inline bool styleRequiresClipPolygon(EBorderStyle style)
1353 return style == DOTTED || style == DASHED; // These are drawn with a stroke, so we have to clip to get corner miters.
1356 static bool borderStyleFillsBorderArea(EBorderStyle style)
1358 return !(style == DOTTED || style == DASHED || style == DOUBLE);
1361 static bool borderStyleHasInnerDetail(EBorderStyle style)
1363 return style == GROOVE || style == RIDGE || style == DOUBLE;
1366 static bool borderStyleIsDottedOrDashed(EBorderStyle style)
1368 return style == DOTTED || style == DASHED;
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)
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);
1380 BorderEdgeFlags flags = edgeFlagForSide(side) | edgeFlagForSide(adjacentSide);
1381 return flags == topRightFlags || flags == bottomLeftFlags;
1386 static inline bool colorsMatchAtCorner(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1388 if (edges[side].shouldRender() != edges[adjacentSide].shouldRender())
1391 if (!edgesShareColor(edges[side], edges[adjacentSide]))
1394 return !borderStyleHasUnmatchedColorsAtCorner(edges[side].style, side, adjacentSide);
1398 static inline bool colorNeedsAntiAliasAtCorner(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1400 if (!edges[side].color.hasAlpha())
1403 if (edges[side].shouldRender() != edges[adjacentSide].shouldRender())
1406 if (!edgesShareColor(edges[side], edges[adjacentSide]))
1409 return borderStyleHasUnmatchedColorsAtCorner(edges[side].style, side, adjacentSide);
1412 // This assumes that we draw in order: top, bottom, left, right.
1413 static inline bool willBeOverdrawn(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1418 if (edges[adjacentSide].presentButInvisible())
1421 if (!edgesShareColor(edges[side], edges[adjacentSide]) && edges[adjacentSide].color.hasAlpha())
1424 if (!borderStyleFillsBorderArea(edges[adjacentSide].style))
1431 // These draw last, so are never overdrawn.
1437 static inline bool borderStylesRequireMitre(BoxSide side, BoxSide adjacentSide, EBorderStyle style, EBorderStyle adjacentStyle)
1439 if (style == DOUBLE || adjacentStyle == DOUBLE || adjacentStyle == GROOVE || adjacentStyle == RIDGE)
1442 if (borderStyleIsDottedOrDashed(style) != borderStyleIsDottedOrDashed(adjacentStyle))
1445 if (style != adjacentStyle)
1448 return borderStyleHasUnmatchedColorsAtCorner(style, side, adjacentSide);
1451 static bool joinRequiresMitre(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[], bool allowOverdraw)
1453 if ((edges[side].isTransparent && edges[adjacentSide].isTransparent) || !edges[adjacentSide].isPresent)
1456 if (allowOverdraw && willBeOverdrawn(side, adjacentSide, edges))
1459 if (!edgesShareColor(edges[side], edges[adjacentSide]))
1462 if (borderStylesRequireMitre(side, adjacentSide, edges[side].style, edges[adjacentSide].style))
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)
1472 const BorderEdge& edgeToRender = edges[side];
1473 ASSERT(edgeToRender.width);
1474 const BorderEdge& adjacentEdge1 = edges[adjacentSide1];
1475 const BorderEdge& adjacentEdge2 = edges[adjacentSide2];
1477 bool mitreAdjacentSide1 = joinRequiresMitre(side, adjacentSide1, edges, !antialias);
1478 bool mitreAdjacentSide2 = joinRequiresMitre(side, adjacentSide2, edges, !antialias);
1480 bool adjacentSide1StylesMatch = colorsMatchAtCorner(side, adjacentSide1, edges);
1481 bool adjacentSide2StylesMatch = colorsMatchAtCorner(side, adjacentSide2, edges);
1483 const Color& colorToPaint = overrideColor ? *overrideColor : edgeToRender.color;
1486 GraphicsContextStateSaver stateSaver(*graphicsContext);
1487 if (innerBorder.isRenderable())
1488 clipBorderSidePolygon(graphicsContext, outerBorder, innerBorder, side, adjacentSide1StylesMatch, adjacentSide2StylesMatch);
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);
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;
1500 GraphicsContextStateSaver clipStateSaver(*graphicsContext, 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;
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);
1515 static IntRect calculateSideRect(const RoundedRect& outerBorder, const BorderEdge edges[], int side)
1517 IntRect sideRect = outerBorder.rect();
1518 int width = edges[side].width;
1521 sideRect.setHeight(width);
1522 else if (side == BSBottom)
1523 sideRect.shiftYEdgeTo(sideRect.maxY() - width);
1524 else if (side == BSLeft)
1525 sideRect.setWidth(width);
1527 sideRect.shiftXEdgeTo(sideRect.maxX() - width);
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)
1536 bool renderRadii = outerBorder.isRounded();
1540 roundedPath.addRoundedRect(outerBorder);
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.
1547 if (edges[BSTop].shouldRender() && includesEdge(edgeSet, BSTop)) {
1548 IntRect sideRect = outerBorder.rect();
1549 sideRect.setHeight(edges[BSTop].width + innerBorderAdjustment.y());
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);
1555 if (edges[BSBottom].shouldRender() && includesEdge(edgeSet, BSBottom)) {
1556 IntRect sideRect = outerBorder.rect();
1557 sideRect.shiftYEdgeTo(sideRect.maxY() - edges[BSBottom].width - innerBorderAdjustment.y());
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);
1563 if (edges[BSLeft].shouldRender() && includesEdge(edgeSet, BSLeft)) {
1564 IntRect sideRect = outerBorder.rect();
1565 sideRect.setWidth(edges[BSLeft].width + innerBorderAdjustment.x());
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);
1571 if (edges[BSRight].shouldRender() && includesEdge(edgeSet, BSRight)) {
1572 IntRect sideRect = outerBorder.rect();
1573 sideRect.shiftXEdgeTo(sideRect.maxX() - edges[BSRight].width - innerBorderAdjustment.x());
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);
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)
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 };
1587 while (edgesToDraw) {
1588 // Find undrawn edges sharing a color.
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))
1598 if (!commonColorEdgeSet) {
1599 commonColor = edges[currSide].color;
1602 includeEdge = edges[currSide].color == commonColor;
1605 commonColorEdgeSet |= edgeFlagForSide(currSide);
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());
1614 paintBorderSides(graphicsContext, style, outerBorder, innerBorder, innerBorderAdjustment, edges, commonColorEdgeSet, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, &commonColor);
1616 if (useTransparencyLayer)
1617 graphicsContext->endLayer();
1619 edgesToDraw &= ~commonColorEdgeSet;
1623 void RenderBoxModelObject::paintBorder(const PaintInfo& info, const LayoutRect& rect, const RenderStyle* style,
1624 BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
1626 GraphicsContext* graphicsContext = info.context;
1627 // border-image is not affected by border-radius.
1628 if (paintNinePieceImage(graphicsContext, rect, style, style->borderImage()))
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);
1636 if (outerBorder.rect().isEmpty())
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;
1648 for (int i = BSTop; i <= BSLeft; ++i) {
1649 const BorderEdge& currEdge = edges[i];
1651 if (edges[i].shouldRender())
1652 edgesToDraw |= edgeFlagForSide(static_cast<BoxSide>(i));
1654 if (currEdge.presentButInvisible()) {
1656 allEdgesShareColor = false;
1657 allEdgesShareWidth = false;
1661 if (!currEdge.shouldRender()) {
1666 if (firstVisibleEdge == -1) {
1667 firstVisibleEdge = i;
1669 if (currEdge.color != edges[firstVisibleEdge].color)
1670 allEdgesShareColor = false;
1671 if (currEdge.width != edges[firstVisibleEdge].width)
1672 allEdgesShareWidth = false;
1675 if (currEdge.color.hasAlpha())
1676 haveAlphaColor = true;
1678 if (currEdge.style != SOLID)
1679 haveAllSolidEdges = false;
1681 if (currEdge.style != DOUBLE)
1682 haveAllDoubleEdges = false;
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());
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
1694 if (numEdgesVisible == 4 && (outerBorder.isRounded() || haveAlphaColor)
1695 && (haveAllSolidEdges || (!outerBorder.isRounded() && !innerBorder.isRounded()))) {
1698 if (outerBorder.isRounded() && allEdgesShareWidth) {
1700 // Very fast path for single stroked round rect with circular corners
1702 graphicsContext->fillBetweenRoundedRects(outerBorder, innerBorder, edges[firstVisibleEdge].color);
1705 if (outerBorder.isRounded() && bleedAvoidance != BackgroundBleedClipBackground)
1706 path.addRoundedRect(outerBorder);
1708 path.addRect(outerBorder.rect());
1710 if (haveAllDoubleEdges) {
1711 IntRect innerThirdRect = outerBorder.rect();
1712 IntRect outerThirdRect = outerBorder.rect();
1713 for (int side = BSTop; side <= BSLeft; ++side) {
1716 edges[side].getDoubleBorderStripeWidths(outerWidth, innerWidth);
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);
1728 innerThirdRect.setWidth(innerThirdRect.width() - innerWidth);
1729 outerThirdRect.setWidth(outerThirdRect.width() - outerWidth);
1733 RoundedRect outerThird = outerBorder;
1734 RoundedRect innerThird = innerBorder;
1735 innerThird.setRect(innerThirdRect);
1736 outerThird.setRect(outerThirdRect);
1738 if (outerThird.isRounded() && bleedAvoidance != BackgroundBleedClipBackground)
1739 path.addRoundedRect(outerThird);
1741 path.addRect(outerThird.rect());
1743 if (innerThird.isRounded() && bleedAvoidance != BackgroundBleedClipBackground)
1744 path.addRoundedRect(innerThird);
1746 path.addRect(innerThird.rect());
1749 if (innerBorder.isRounded())
1750 path.addRoundedRect(innerBorder);
1752 path.addRect(innerBorder.rect());
1754 graphicsContext->setFillRule(RULE_EVENODD);
1755 graphicsContext->setFillColor(edges[firstVisibleEdge].color);
1756 graphicsContext->fillPath(path);
1759 // Avoid creating transparent layers
1760 if (haveAllSolidEdges && numEdgesVisible != 4 && !outerBorder.isRounded() && haveAlphaColor) {
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);
1771 graphicsContext->setFillRule(RULE_NONZERO);
1772 graphicsContext->setFillColor(edges[firstVisibleEdge].color);
1773 graphicsContext->fillPath(path);
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);
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());
1795 paintTranslucentBorderSides(graphicsContext, style, outerBorder, unadjustedInnerBorder, innerBorderAdjustment, edges, edgesToDraw, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias);
1797 paintBorderSides(graphicsContext, style, outerBorder, unadjustedInnerBorder, innerBorderAdjustment, edges, edgesToDraw, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias);
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)
1807 if (borderStyle == DOUBLE && thickness < 3)
1808 borderStyle = SOLID;
1810 switch (borderStyle) {
1816 graphicsContext->setStrokeColor(color);
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);
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);
1844 lineDash.append(dashLength);
1845 lineDash.append(gapLength);
1846 graphicsContext->setLineDash(lineDash, dashLength);
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);
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);
1861 int outerBorderRightWidth;
1862 int innerBorderRightWidth;
1863 edges[BSRight].getDoubleBorderStripeWidths(outerBorderRightWidth, innerBorderRightWidth);
1865 int outerBorderBottomWidth;
1866 int innerBorderBottomWidth;
1867 edges[BSBottom].getDoubleBorderStripeWidths(outerBorderBottomWidth, innerBorderBottomWidth);
1869 int outerBorderLeftWidth;
1870 int innerBorderLeftWidth;
1871 edges[BSLeft].getDoubleBorderStripeWidths(outerBorderLeftWidth, innerBorderLeftWidth);
1873 // Draw inner border line
1875 GraphicsContextStateSaver stateSaver(*graphicsContext);
1876 RoundedRect innerClip = style->getRoundedInnerBorderFor(borderRect,
1877 innerBorderTopWidth, innerBorderBottomWidth, innerBorderLeftWidth, innerBorderRightWidth,
1878 includeLogicalLeftEdge, includeLogicalRightEdge);
1880 graphicsContext->clipRoundedRect(innerClip);
1881 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, SOLID, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
1884 // Draw outer border line
1886 GraphicsContextStateSaver stateSaver(*graphicsContext);
1887 LayoutRect outerRect = borderRect;
1888 if (bleedAvoidance == BackgroundBleedClipBackground) {
1889 outerRect.inflate(1);
1890 ++outerBorderTopWidth;
1891 ++outerBorderBottomWidth;
1892 ++outerBorderLeftWidth;
1893 ++outerBorderRightWidth;
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);
1909 if (borderStyle == GROOVE) {
1917 // Paint full border
1918 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, s1, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
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;
1927 RoundedRect clipRect = style->getRoundedInnerBorderFor(borderRect,
1928 topWidth, bottomWidth, leftWidth, rightWidth,
1929 includeLogicalLeftEdge, includeLogicalRightEdge);
1931 graphicsContext->clipRoundedRect(clipRect);
1932 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, s2, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
1936 if (side == BSTop || side == BSLeft)
1937 color = color.dark();
1940 if (side == BSBottom || side == BSRight)
1941 color = color.dark();
1947 graphicsContext->setStrokeStyle(NoStroke);
1948 graphicsContext->setFillColor(color);
1949 graphicsContext->drawRect(pixelSnappedIntRect(borderRect));
1952 void RenderBoxModelObject::clipBorderSidePolygon(GraphicsContext* graphicsContext, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
1953 BoxSide side, bool firstEdgeMatches, bool secondEdgeMatches)
1957 const LayoutRect& outerRect = outerBorder.rect();
1958 const LayoutRect& innerRect = innerBorder.rect();
1960 FloatPoint centerPoint(innerRect.location().x().toFloat() + innerRect.width().toFloat() / 2, innerRect.location().y().toFloat() + innerRect.height().toFloat() / 2);
1962 // For each side, create a quad that encompasses all parts of that side that may draw,
1963 // including areas inside the innerBorder.
1965 // 0----------------3
1967 // |\ 1----------- 2 /|
1972 // |/ 1------------2 \|
1974 // 0----------------3
1978 quad[0] = outerRect.minXMinYCorner();
1979 quad[1] = innerRect.minXMinYCorner();
1980 quad[2] = innerRect.maxXMinYCorner();
1981 quad[3] = outerRect.maxXMinYCorner();
1983 if (!innerBorder.radii().topLeft().isZero()) {
1984 findIntersection(quad[0], quad[1],
1986 quad[1].x() + innerBorder.radii().topLeft().width(),
1990 quad[1].y() + innerBorder.radii().topLeft().height()),
1994 if (!innerBorder.radii().topRight().isZero()) {
1995 findIntersection(quad[3], quad[2],
1997 quad[2].x() - innerBorder.radii().topRight().width(),
2001 quad[2].y() + innerBorder.radii().topRight().height()),
2007 quad[0] = outerRect.minXMinYCorner();
2008 quad[1] = innerRect.minXMinYCorner();
2009 quad[2] = innerRect.minXMaxYCorner();
2010 quad[3] = outerRect.minXMaxYCorner();
2012 if (!innerBorder.radii().topLeft().isZero()) {
2013 findIntersection(quad[0], quad[1],
2015 quad[1].x() + innerBorder.radii().topLeft().width(),
2019 quad[1].y() + innerBorder.radii().topLeft().height()),
2023 if (!innerBorder.radii().bottomLeft().isZero()) {
2024 findIntersection(quad[3], quad[2],
2026 quad[2].x() + innerBorder.radii().bottomLeft().width(),
2030 quad[2].y() - innerBorder.radii().bottomLeft().height()),
2036 quad[0] = outerRect.minXMaxYCorner();
2037 quad[1] = innerRect.minXMaxYCorner();
2038 quad[2] = innerRect.maxXMaxYCorner();
2039 quad[3] = outerRect.maxXMaxYCorner();
2041 if (!innerBorder.radii().bottomLeft().isZero()) {
2042 findIntersection(quad[0], quad[1],
2044 quad[1].x() + innerBorder.radii().bottomLeft().width(),
2048 quad[1].y() - innerBorder.radii().bottomLeft().height()),
2052 if (!innerBorder.radii().bottomRight().isZero()) {
2053 findIntersection(quad[3], quad[2],
2055 quad[2].x() - innerBorder.radii().bottomRight().width(),
2059 quad[2].y() - innerBorder.radii().bottomRight().height()),
2065 quad[0] = outerRect.maxXMinYCorner();
2066 quad[1] = innerRect.maxXMinYCorner();
2067 quad[2] = innerRect.maxXMaxYCorner();
2068 quad[3] = outerRect.maxXMaxYCorner();
2070 if (!innerBorder.radii().topRight().isZero()) {
2071 findIntersection(quad[0], quad[1],
2073 quad[1].x() - innerBorder.radii().topRight().width(),
2077 quad[1].y() + innerBorder.radii().topRight().height()),
2081 if (!innerBorder.radii().bottomRight().isZero()) {
2082 findIntersection(quad[3], quad[2],
2084 quad[2].x() - innerBorder.radii().bottomRight().width(),
2088 quad[2].y() - innerBorder.radii().bottomRight().height()),
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);
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();
2111 const static float kEpsilon = 1e-2f;
2113 if (fabsf(bx) < kEpsilon && fabsf(by) < kEpsilon) {
2114 // The quad was actually a triangle.
2117 // Extend parallelogram a bit to hide calculation error
2118 const static float kExtendFill = 1e-2f;
2120 r1 = (-ax * by + ay * bx) / (cx * by - cy * bx) + kExtendFill;
2121 r2 = (-cx * by + cy * bx) / (ax * by - ay * bx) + kExtendFill;
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);
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);
2139 static IntRect calculateSideRectIncludingInner(const RoundedRect& outerBorder, const BorderEdge edges[], BoxSide side)
2141 IntRect sideRect = outerBorder.rect();
2146 width = sideRect.height() - edges[BSBottom].width;
2147 sideRect.setHeight(width);
2150 width = sideRect.height() - edges[BSTop].width;
2151 sideRect.shiftYEdgeTo(sideRect.maxY() - width);
2154 width = sideRect.width() - edges[BSRight].width;
2155 sideRect.setWidth(width);
2158 width = sideRect.width() - edges[BSLeft].width;
2159 sideRect.shiftXEdgeTo(sideRect.maxX() - width);
2166 static RoundedRect calculateAdjustedInnerBorder(const RoundedRect&innerBorder, BoxSide side)
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();
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);
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);
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);
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);
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);
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);
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);
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);
2243 return RoundedRect(newRect, newRadii);
2246 void RenderBoxModelObject::clipBorderSideForComplexInnerPath(GraphicsContext* graphicsContext, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
2247 BoxSide side, const class BorderEdge edges[])
2249 graphicsContext->clip(calculateSideRectIncludingInner(outerBorder, edges, side));
2250 RoundedRect adjustedInnerRect = calculateAdjustedInnerBorder(innerBorder, side);
2251 if (!adjustedInnerRect.isEmpty())
2252 graphicsContext->clipOutRoundedRect(adjustedInnerRect);
2255 void RenderBoxModelObject::getBorderEdgeInfo(BorderEdge edges[], const RenderStyle* style, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
2257 bool horizontal = style->isHorizontalWritingMode();
2259 edges[BSTop] = BorderEdge(style->borderTopWidth(),
2260 resolveColor(style, CSSPropertyBorderTopColor),
2261 style->borderTopStyle(),
2262 style->borderTopIsTransparent(),
2263 horizontal || includeLogicalLeftEdge);
2265 edges[BSRight] = BorderEdge(style->borderRightWidth(),
2266 resolveColor(style, CSSPropertyBorderRightColor),
2267 style->borderRightStyle(),
2268 style->borderRightIsTransparent(),
2269 !horizontal || includeLogicalRightEdge);
2271 edges[BSBottom] = BorderEdge(style->borderBottomWidth(),
2272 resolveColor(style, CSSPropertyBorderBottomColor),
2273 style->borderBottomStyle(),
2274 style->borderBottomIsTransparent(),
2275 horizontal || includeLogicalRightEdge);
2277 edges[BSLeft] = BorderEdge(style->borderLeftWidth(),
2278 resolveColor(style, CSSPropertyBorderLeftColor),
2279 style->borderLeftStyle(),
2280 style->borderLeftIsTransparent(),
2281 !horizontal || includeLogicalLeftEdge);
2284 bool RenderBoxModelObject::borderObscuresBackgroundEdge(const FloatSize& contextScale) const
2286 BorderEdge edges[4];
2287 getBorderEdgeInfo(edges, style());
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))
2300 bool RenderBoxModelObject::borderObscuresBackground() const
2302 if (!style()->hasBorder())
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())
2309 BorderEdge edges[4];
2310 getBorderEdgeInfo(edges, style());
2312 for (int i = BSTop; i <= BSLeft; ++i) {
2313 const BorderEdge& currEdge = edges[i];
2314 if (!currEdge.obscuresBackground())
2321 bool RenderBoxModelObject::boxShadowShouldBeAppliedToBackground(BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* inlineFlowBox) const
2323 if (bleedAvoidance != BackgroundBleedNone)
2326 if (style()->hasAppearance())
2329 const ShadowList* shadowList = style()->boxShadow();
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)
2340 if (hasOneNormalBoxShadow)
2342 hasOneNormalBoxShadow = true;
2344 if (currentShadow.spread())
2348 if (!hasOneNormalBoxShadow)
2351 Color backgroundColor = resolveColor(CSSPropertyBackgroundColor);
2352 if (backgroundColor.hasAlpha())
2355 const FillLayer* lastBackgroundLayer = &style()->backgroundLayers();
2356 for (const FillLayer* next = lastBackgroundLayer->next(); next; next = lastBackgroundLayer->next())
2357 lastBackgroundLayer = next;
2359 if (lastBackgroundLayer->clip() != BorderFillBox)
2362 if (lastBackgroundLayer->image() && style()->hasBorderRadius())
2365 if (inlineFlowBox && !inlineFlowBox->boxShadowCanBeAppliedToBackground(*lastBackgroundLayer))
2368 if (hasOverflowClip() && lastBackgroundLayer->attachment() == LocalBackgroundAttachment)
2374 void RenderBoxModelObject::paintBoxShadow(const PaintInfo& info, const LayoutRect& paintRect, const RenderStyle* s, ShadowStyle shadowStyle, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
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())
2381 RoundedRect border = (shadowStyle == Inset) ? s->getRoundedInnerBorderFor(paintRect, includeLogicalLeftEdge, includeLogicalRightEdge)
2382 : s->getRoundedBorderFor(paintRect, includeLogicalLeftEdge, includeLogicalRightEdge);
2384 bool hasBorderRadius = s->hasBorderRadius();
2385 bool isHorizontal = s->isHorizontalWritingMode();
2386 bool hasOpaqueBackground = s->visitedDependentColor(CSSPropertyBackgroundColor).alpha() == 255;
2388 GraphicsContextStateSaver stateSaver(*context, false);
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)
2396 FloatSize shadowOffset(shadow.x(), shadow.y());
2397 float shadowBlur = shadow.blur();
2398 float shadowSpread = shadow.spread();
2400 if (shadowOffset.isZero() && !shadowBlur && !shadowSpread)
2403 const Color& shadowColor = shadow.color();
2405 if (shadow.style() == Normal) {
2406 FloatRect fillRect = border.rect();
2407 fillRect.inflate(shadowSpread);
2408 if (fillRect.isEmpty())
2411 FloatRect shadowRect(border.rect());
2412 shadowRect.inflate(shadowBlur + shadowSpread);
2413 shadowRect.move(shadowOffset);
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()) {
2419 if (hasBorderRadius) {
2420 RoundedRect rectToClipOut = border;
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);
2428 if (!rectToClipOut.isEmpty()) {
2429 context->clipOutRoundedRect(rectToClipOut);
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();
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
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);
2450 if (!rectToClipOut.isEmpty()) {
2451 context->clipOut(rectToClipOut);
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());
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);
2468 // TODO: support non-integer shadows - crbug.com/334829
2469 RoundedRect roundedFillRect = border;
2470 roundedFillRect.inflate(shadowSpread);
2472 roundedFillRect.expandRadii(shadowSpread);
2473 if (!roundedFillRect.isRenderable())
2474 roundedFillRect.adjustRadii();
2475 context->fillRoundedRect(roundedFillRect, Color::black);
2478 context->fillRect(fillRect, Color::black);
2481 // The inset shadow case.
2482 GraphicsContext::Edges clippedEdges = GraphicsContext::NoEdge;
2483 if (!includeLogicalLeftEdge) {
2485 clippedEdges |= GraphicsContext::LeftEdge;
2487 clippedEdges |= GraphicsContext::TopEdge;
2489 if (!includeLogicalRightEdge) {
2491 clippedEdges |= GraphicsContext::RightEdge;
2493 clippedEdges |= GraphicsContext::BottomEdge;
2495 // TODO: support non-integer shadows - crbug.com/334828
2496 context->drawInnerShadow(border, shadowColor, flooredIntSize(shadowOffset), shadowBlur, shadowSpread, clippedEdges);
2501 LayoutUnit RenderBoxModelObject::containingBlockLogicalWidthForContent() const
2503 return containingBlock()->availableLogicalWidth();
2506 RenderBoxModelObject* RenderBoxModelObject::continuation() const
2508 if (!continuationMap)
2510 return (*continuationMap)->get(this);
2513 void RenderBoxModelObject::setContinuation(RenderBoxModelObject* continuation)
2516 if (!continuationMap)
2517 continuationMap = new OwnPtrWillBePersistent<ContinuationMap>(adoptPtrWillBeNoop(new ContinuationMap));
2518 (*continuationMap)->set(this, continuation);
2520 if (continuationMap)
2521 (*continuationMap)->remove(this);
2525 void RenderBoxModelObject::computeLayerHitTestRects(LayerHitTestRects& rects) const
2527 RenderLayerModelObject::computeLayerHitTestRects(rects);
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.
2534 continuation()->computeLayerHitTestRects(rects);
2537 RenderTextFragment* RenderBoxModelObject::firstLetterRemainingText() const
2539 if (!firstLetterRemainingTextMap)
2541 return (*firstLetterRemainingTextMap)->get(this);
2544 void RenderBoxModelObject::setFirstLetterRemainingText(RenderTextFragment* remainingText)
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);
2555 LayoutRect RenderBoxModelObject::localCaretRectForEmptyElement(LayoutUnit width, LayoutUnit textIndentOffset)
2557 ASSERT(!slowFirstChild());
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();
2566 enum CaretAlignment { alignLeft, alignRight, alignCenter };
2568 CaretAlignment alignment = alignLeft;
2570 switch (currentStyle->textAlign()) {
2576 alignment = alignCenter;
2580 alignment = alignRight;
2584 if (!currentStyle->isLeftToRightDirection())
2585 alignment = alignRight;
2588 if (currentStyle->isLeftToRightDirection())
2589 alignment = alignRight;
2593 LayoutUnit x = borderLeft() + paddingLeft();
2594 LayoutUnit maxX = width - borderRight() - paddingRight();
2596 switch (alignment) {
2598 if (currentStyle->isLeftToRightDirection())
2599 x += textIndentOffset;
2603 if (currentStyle->isLeftToRightDirection())
2604 x += textIndentOffset / 2;
2606 x -= textIndentOffset / 2;
2609 x = maxX - caretWidth;
2610 if (!currentStyle->isLeftToRightDirection())
2611 x -= textIndentOffset;
2614 x = std::min(x, std::max<LayoutUnit>(maxX - caretWidth, 0));
2616 LayoutUnit y = paddingTop() + borderTop();
2618 return currentStyle->isHorizontalWritingMode() ? LayoutRect(x, y, caretWidth, height) : LayoutRect(y, x, height, caretWidth);
2621 bool RenderBoxModelObject::shouldAntialiasLines(GraphicsContext* context)
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
2627 return !context->getCTM().isIdentityOrTranslationOrFlipped();
2630 void RenderBoxModelObject::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
2632 RenderObject* o = container();
2636 if (o->isRenderFlowThread())
2637 transformState.move(o->columnOffset(LayoutPoint(transformState.mappedPoint())));
2639 o->mapAbsoluteToLocalPoint(mode, transformState);
2641 LayoutSize containerOffset = offsetFromContainer(o, LayoutPoint());
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);
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);
2656 transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
2659 const RenderObject* RenderBoxModelObject::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
2661 ASSERT(ancestorToStopAt != this);
2663 bool ancestorSkipped;
2664 RenderObject* container = this->container(ancestorToStopAt, &ancestorSkipped);
2668 bool isInline = isRenderInline();
2669 bool isFixedPos = !isInline && style()->position() == FixedPosition;
2670 bool hasTransform = !isInline && hasLayer() && layer()->transform();
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);
2679 bool offsetDependsOnPoint = false;
2680 LayoutSize containerOffset = offsetFromContainer(container, LayoutPoint(), &offsetDependsOnPoint);
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);
2689 containerOffset += adjustmentForSkippedAncestor;
2690 geometryMap.push(this, containerOffset, preserve3D, offsetDependsOnPoint, isFixedPos, hasTransform);
2693 return ancestorSkipped ? ancestorToStopAt : container;
2696 void RenderBoxModelObject::moveChildTo(RenderBoxModelObject* toBoxModelObject, RenderObject* child, RenderObject* beforeChild, bool fullRemoveInsert)
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());
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);
2709 toBoxModelObject->virtualChildren()->insertChildNode(toBoxModelObject, virtualChildren()->removeChildNode(this, child, fullRemoveInsert), beforeChild, fullRemoveInsert);
2712 void RenderBoxModelObject::moveChildrenTo(RenderBoxModelObject* toBoxModelObject, RenderObject* startChild, RenderObject* endChild, RenderObject* beforeChild, bool fullRemoveInsert)
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();
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;
2733 } // namespace blink