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 "RenderBoxModelObject.h"
29 #include "GraphicsContext.h"
30 #include "HTMLFrameOwnerElement.h"
31 #include "HTMLNames.h"
32 #include "ImageBuffer.h"
35 #include "RenderBlock.h"
36 #include "RenderInline.h"
37 #include "RenderLayer.h"
38 #include "RenderView.h"
39 #include <wtf/CurrentTime.h>
45 using namespace HTMLNames;
47 bool RenderBoxModelObject::s_wasFloating = false;
48 bool RenderBoxModelObject::s_hadLayer = false;
49 bool RenderBoxModelObject::s_layerWasSelfPainting = false;
51 static const double cInterpolationCutoff = 800. * 800.;
52 static const double cLowQualityTimeThreshold = 0.500; // 500 ms
54 typedef HashMap<const void*, LayoutSize> LayerSizeMap;
55 typedef HashMap<RenderBoxModelObject*, LayerSizeMap> ObjectLayerSizeMap;
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 HashMap<const RenderBoxModelObject*, RenderBoxModelObject*> ContinuationMap;
65 static ContinuationMap* continuationMap = 0;
67 class ImageQualityController {
68 WTF_MAKE_NONCOPYABLE(ImageQualityController); WTF_MAKE_FAST_ALLOCATED;
70 ImageQualityController();
71 bool shouldPaintAtLowQuality(GraphicsContext*, RenderBoxModelObject*, Image*, const void* layer, const LayoutSize&);
72 void removeLayer(RenderBoxModelObject*, LayerSizeMap* innerMap, const void* layer);
73 void set(RenderBoxModelObject*, LayerSizeMap* innerMap, const void* layer, const LayoutSize&);
74 void objectDestroyed(RenderBoxModelObject*);
75 bool isEmpty() { return m_objectLayerSizeMap.isEmpty(); }
78 void highQualityRepaintTimerFired(Timer<ImageQualityController>*);
81 ObjectLayerSizeMap m_objectLayerSizeMap;
82 Timer<ImageQualityController> m_timer;
83 bool m_animatedResizeIsActive;
86 ImageQualityController::ImageQualityController()
87 : m_timer(this, &ImageQualityController::highQualityRepaintTimerFired)
88 , m_animatedResizeIsActive(false)
92 void ImageQualityController::removeLayer(RenderBoxModelObject* object, LayerSizeMap* innerMap, const void* layer)
95 innerMap->remove(layer);
96 if (innerMap->isEmpty())
97 objectDestroyed(object);
101 void ImageQualityController::set(RenderBoxModelObject* object, LayerSizeMap* innerMap, const void* layer, const LayoutSize& size)
104 innerMap->set(layer, size);
106 LayerSizeMap newInnerMap;
107 newInnerMap.set(layer, size);
108 m_objectLayerSizeMap.set(object, newInnerMap);
112 void ImageQualityController::objectDestroyed(RenderBoxModelObject* object)
114 m_objectLayerSizeMap.remove(object);
115 if (m_objectLayerSizeMap.isEmpty()) {
116 m_animatedResizeIsActive = false;
121 void ImageQualityController::highQualityRepaintTimerFired(Timer<ImageQualityController>*)
123 if (m_animatedResizeIsActive) {
124 m_animatedResizeIsActive = false;
125 for (ObjectLayerSizeMap::iterator it = m_objectLayerSizeMap.begin(); it != m_objectLayerSizeMap.end(); ++it)
126 it->first->repaint();
130 void ImageQualityController::restartTimer()
132 m_timer.startOneShot(cLowQualityTimeThreshold);
135 bool ImageQualityController::shouldPaintAtLowQuality(GraphicsContext* context, RenderBoxModelObject* object, Image* image, const void *layer, const LayoutSize& size)
137 // If the image is not a bitmap image, then none of this is relevant and we just paint at high
139 if (!image || !image->isBitmapImage() || context->paintingDisabled())
142 if (object->style()->imageRendering() == ImageRenderingOptimizeContrast)
145 // Make sure to use the unzoomed image size, since if a full page zoom is in effect, the image
146 // is actually being scaled.
147 IntSize imageSize(image->width(), image->height());
149 // Look ourselves up in the hashtables.
150 ObjectLayerSizeMap::iterator i = m_objectLayerSizeMap.find(object);
151 LayerSizeMap* innerMap = i != m_objectLayerSizeMap.end() ? &i->second : 0;
153 bool isFirstResize = true;
155 LayerSizeMap::iterator j = innerMap->find(layer);
156 if (j != innerMap->end()) {
157 isFirstResize = false;
162 const AffineTransform& currentTransform = context->getCTM();
163 bool contextIsScaled = !currentTransform.isIdentityOrTranslationOrFlipped();
164 // FIXME: Change to use roughlyEquals when we move to float.
165 // See https://bugs.webkit.org/show_bug.cgi?id=66148
166 if (!contextIsScaled && size == imageSize) {
167 // There is no scale in effect. If we had a scale in effect before, we can just remove this object from the list.
168 removeLayer(object, innerMap, layer);
172 // There is no need to hash scaled images that always use low quality mode when the page demands it. This is the iChat case.
173 if (object->document()->page()->inLowQualityImageInterpolationMode()) {
174 double totalPixels = static_cast<double>(image->width()) * static_cast<double>(image->height());
175 if (totalPixels > cInterpolationCutoff)
179 // If an animated resize is active, paint in low quality and kick the timer ahead.
180 if (m_animatedResizeIsActive) {
181 set(object, innerMap, layer, size);
185 // If this is the first time resizing this image, or its size is the
186 // same as the last resize, draw at high res, but record the paint
187 // size and set the timer.
188 // FIXME: Change to use roughlyEquals when we move to float.
189 // See https://bugs.webkit.org/show_bug.cgi?id=66148
190 if (isFirstResize || oldSize == size) {
192 set(object, innerMap, layer, size);
195 // If the timer is no longer active, draw at high quality and don't
197 if (!m_timer.isActive()) {
198 removeLayer(object, innerMap, layer);
201 // This object has been resized to two different sizes while the timer
202 // is active, so draw at low quality, set the flag for animated resizes and
203 // the object to the list for high quality redraw.
204 set(object, innerMap, layer, size);
205 m_animatedResizeIsActive = true;
210 static ImageQualityController* gImageQualityController = 0;
212 static ImageQualityController* imageQualityController()
214 if (!gImageQualityController)
215 gImageQualityController = new ImageQualityController;
217 return gImageQualityController;
220 void RenderBoxModelObject::setSelectionState(SelectionState s)
222 if (selectionState() == s)
225 if (s == SelectionInside && selectionState() != SelectionNone)
228 if ((s == SelectionStart && selectionState() == SelectionEnd)
229 || (s == SelectionEnd && selectionState() == SelectionStart))
230 RenderObject::setSelectionState(SelectionBoth);
232 RenderObject::setSelectionState(s);
235 // We should consider whether it is OK propagating to ancestor RenderInlines.
236 // This is a workaround for http://webkit.org/b/32123
237 RenderBlock* cb = containingBlock();
238 if (cb && !cb->isRenderView())
239 cb->setSelectionState(s);
242 bool RenderBoxModelObject::shouldPaintAtLowQuality(GraphicsContext* context, Image* image, const void* layer, const LayoutSize& size)
244 return imageQualityController()->shouldPaintAtLowQuality(context, this, image, layer, size);
247 RenderBoxModelObject::RenderBoxModelObject(Node* node)
253 RenderBoxModelObject::~RenderBoxModelObject()
255 // Our layer should have been destroyed and cleared by now
258 if (gImageQualityController) {
259 gImageQualityController->objectDestroyed(this);
260 if (gImageQualityController->isEmpty()) {
261 delete gImageQualityController;
262 gImageQualityController = 0;
267 void RenderBoxModelObject::destroyLayer()
269 ASSERT(!hasLayer()); // Callers should have already called setHasLayer(false)
271 m_layer->destroy(renderArena());
275 void RenderBoxModelObject::willBeDestroyed()
277 // This must be done before we destroy the RenderObject.
279 m_layer->clearClipRects();
281 // A continuation of this RenderObject should be destroyed at subclasses.
282 ASSERT(!continuation());
284 // RenderObject::willBeDestroyed calls back to destroyLayer() for layer destruction
285 RenderObject::willBeDestroyed();
288 bool RenderBoxModelObject::hasSelfPaintingLayer() const
290 return m_layer && m_layer->isSelfPaintingLayer();
293 void RenderBoxModelObject::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
295 s_wasFloating = isFloating();
296 s_hadLayer = hasLayer();
298 s_layerWasSelfPainting = layer()->isSelfPaintingLayer();
300 // If our z-index changes value or our visibility changes,
301 // we need to dirty our stacking context's z-order list.
302 if (style() && newStyle) {
304 // Do a repaint with the old style first, e.g., for example if we go from
305 // having an outline to not having an outline.
306 if (diff == StyleDifferenceRepaintLayer) {
307 layer()->repaintIncludingDescendants();
308 if (!(style()->clip() == newStyle->clip()))
309 layer()->clearClipRectsIncludingDescendants();
310 } else if (diff == StyleDifferenceRepaint || newStyle->outlineSize() < style()->outlineSize())
314 if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
315 // When a layout hint happens, we go ahead and do a repaint of the layer, since the layer could
316 // end up being destroyed.
318 if (style()->position() != newStyle->position() ||
319 style()->zIndex() != newStyle->zIndex() ||
320 style()->hasAutoZIndex() != newStyle->hasAutoZIndex() ||
321 !(style()->clip() == newStyle->clip()) ||
322 style()->hasClip() != newStyle->hasClip() ||
323 style()->opacity() != newStyle->opacity() ||
324 style()->transform() != newStyle->transform())
325 layer()->repaintIncludingDescendants();
326 } else if (newStyle->hasTransform() || newStyle->opacity() < 1) {
327 // If we don't have a layer yet, but we are going to get one because of transform or opacity,
328 // then we need to repaint the old position of the object.
333 if (hasLayer() && (style()->hasAutoZIndex() != newStyle->hasAutoZIndex() ||
334 style()->zIndex() != newStyle->zIndex() ||
335 style()->visibility() != newStyle->visibility())) {
336 layer()->dirtyStackingContextZOrderLists();
337 if (style()->hasAutoZIndex() != newStyle->hasAutoZIndex() || style()->visibility() != newStyle->visibility())
338 layer()->dirtyZOrderLists();
342 RenderObject::styleWillChange(diff, newStyle);
345 void RenderBoxModelObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
347 RenderObject::styleDidChange(diff, oldStyle);
348 updateBoxModelInfoFromStyle();
350 if (requiresLayer()) {
352 if (s_wasFloating && isFloating())
353 setChildNeedsLayout(true);
354 m_layer = new (renderArena()) RenderLayer(this);
356 m_layer->insertOnlyThisLayer();
357 if (parent() && !needsLayout() && containingBlock()) {
358 m_layer->setNeedsFullRepaint();
359 // There is only one layer to update, it is not worth using |cachedOffset| since
360 // we are not sure the value will be used.
361 m_layer->updateLayerPositions(0);
364 } else if (layer() && layer()->parent()) {
365 setHasTransform(false); // Either a transform wasn't specified or the object doesn't support transforms, so just null out the bit.
366 setHasReflection(false);
367 m_layer->removeOnlyThisLayer(); // calls destroyLayer() which clears m_layer
368 if (s_wasFloating && isFloating())
369 setChildNeedsLayout(true);
373 layer()->styleChanged(diff, oldStyle);
374 if (s_hadLayer && layer()->isSelfPaintingLayer() != s_layerWasSelfPainting)
375 setChildNeedsLayout(true);
379 void RenderBoxModelObject::updateBoxModelInfoFromStyle()
381 // Set the appropriate bits for a box model object. Since all bits are cleared in styleWillChange,
382 // we only check for bits that could possibly be set to true.
383 setHasBoxDecorations(hasBackground() || style()->hasBorder() || style()->hasAppearance() || style()->boxShadow());
384 setInline(style()->isDisplayInlineType());
385 setRelPositioned(style()->position() == RelativePosition);
386 setHorizontalWritingMode(style()->isHorizontalWritingMode());
389 LayoutUnit RenderBoxModelObject::relativePositionOffsetX() const
391 // Objects that shrink to avoid floats normally use available line width when computing containing block width. However
392 // in the case of relative positioning using percentages, we can't do this. The offset should always be resolved using the
393 // available width of the containing block. Therefore we don't use containingBlockLogicalWidthForContent() here, but instead explicitly
394 // call availableWidth on our containing block.
395 if (!style()->left().isAuto()) {
396 RenderBlock* cb = containingBlock();
397 if (!style()->right().isAuto() && !cb->style()->isLeftToRightDirection())
398 return -style()->right().calcValue(cb->availableWidth());
399 return style()->left().calcValue(cb->availableWidth());
401 if (!style()->right().isAuto()) {
402 RenderBlock* cb = containingBlock();
403 return -style()->right().calcValue(cb->availableWidth());
408 LayoutUnit RenderBoxModelObject::relativePositionOffsetY() const
410 RenderBlock* containingBlock = this->containingBlock();
412 // If the containing block of a relatively positioned element does not
413 // specify a height, a percentage top or bottom offset should be resolved as
414 // auto. An exception to this is if the containing block has the WinIE quirk
415 // where <html> and <body> assume the size of the viewport. In this case,
416 // calculate the percent offset based on this height.
417 // See <https://bugs.webkit.org/show_bug.cgi?id=26396>.
418 if (!style()->top().isAuto()
419 && (!containingBlock->style()->height().isAuto()
420 || !style()->top().isPercent()
421 || containingBlock->stretchesToViewport()))
422 return style()->top().calcValue(containingBlock->availableHeight());
424 if (!style()->bottom().isAuto()
425 && (!containingBlock->style()->height().isAuto()
426 || !style()->bottom().isPercent()
427 || containingBlock->stretchesToViewport()))
428 return -style()->bottom().calcValue(containingBlock->availableHeight());
433 LayoutUnit RenderBoxModelObject::offsetLeft() const
435 // If the element is the HTML body element or does not have an associated box
436 // return 0 and stop this algorithm.
440 RenderBoxModelObject* offsetPar = offsetParent();
441 LayoutUnit xPos = (isBox() ? toRenderBox(this)->x() : 0);
443 // If the offsetParent of the element is null, or is the HTML body element,
444 // return the distance between the canvas origin and the left border edge
445 // of the element and stop this algorithm.
447 if (offsetPar->isBox() && !offsetPar->isBody())
448 xPos -= toRenderBox(offsetPar)->borderLeft();
449 if (!isPositioned()) {
450 if (isRelPositioned())
451 xPos += relativePositionOffsetX();
452 RenderObject* curr = parent();
453 while (curr && curr != offsetPar) {
454 // FIXME: What are we supposed to do inside SVG content?
455 if (curr->isBox() && !curr->isTableRow())
456 xPos += toRenderBox(curr)->x();
457 curr = curr->parent();
459 if (offsetPar->isBox() && offsetPar->isBody() && !offsetPar->isRelPositioned() && !offsetPar->isPositioned())
460 xPos += toRenderBox(offsetPar)->x();
467 LayoutUnit RenderBoxModelObject::offsetTop() const
469 // If the element is the HTML body element or does not have an associated box
470 // return 0 and stop this algorithm.
474 RenderBoxModelObject* offsetPar = offsetParent();
475 LayoutUnit yPos = (isBox() ? toRenderBox(this)->y() : 0);
477 // If the offsetParent of the element is null, or is the HTML body element,
478 // return the distance between the canvas origin and the top border edge
479 // of the element and stop this algorithm.
481 if (offsetPar->isBox() && !offsetPar->isBody())
482 yPos -= toRenderBox(offsetPar)->borderTop();
483 if (!isPositioned()) {
484 if (isRelPositioned())
485 yPos += relativePositionOffsetY();
486 RenderObject* curr = parent();
487 while (curr && curr != offsetPar) {
488 // FIXME: What are we supposed to do inside SVG content?
489 if (curr->isBox() && !curr->isTableRow())
490 yPos += toRenderBox(curr)->y();
491 curr = curr->parent();
493 if (offsetPar->isBox() && offsetPar->isBody() && !offsetPar->isRelPositioned() && !offsetPar->isPositioned())
494 yPos += toRenderBox(offsetPar)->y();
500 LayoutUnit RenderBoxModelObject::paddingTop(bool) const
503 Length padding = style()->paddingTop();
504 if (padding.isPercent())
505 w = containingBlock()->availableLogicalWidth();
506 return padding.calcMinValue(w);
509 LayoutUnit RenderBoxModelObject::paddingBottom(bool) const
512 Length padding = style()->paddingBottom();
513 if (padding.isPercent())
514 w = containingBlock()->availableLogicalWidth();
515 return padding.calcMinValue(w);
518 LayoutUnit RenderBoxModelObject::paddingLeft(bool) const
521 Length padding = style()->paddingLeft();
522 if (padding.isPercent())
523 w = containingBlock()->availableLogicalWidth();
524 return padding.calcMinValue(w);
527 LayoutUnit RenderBoxModelObject::paddingRight(bool) const
530 Length padding = style()->paddingRight();
531 if (padding.isPercent())
532 w = containingBlock()->availableLogicalWidth();
533 return padding.calcMinValue(w);
536 LayoutUnit RenderBoxModelObject::paddingBefore(bool) const
539 Length padding = style()->paddingBefore();
540 if (padding.isPercent())
541 w = containingBlock()->availableLogicalWidth();
542 return padding.calcMinValue(w);
545 LayoutUnit RenderBoxModelObject::paddingAfter(bool) const
548 Length padding = style()->paddingAfter();
549 if (padding.isPercent())
550 w = containingBlock()->availableLogicalWidth();
551 return padding.calcMinValue(w);
554 LayoutUnit RenderBoxModelObject::paddingStart(bool) const
557 Length padding = style()->paddingStart();
558 if (padding.isPercent())
559 w = containingBlock()->availableLogicalWidth();
560 return padding.calcMinValue(w);
563 LayoutUnit RenderBoxModelObject::paddingEnd(bool) const
566 Length padding = style()->paddingEnd();
567 if (padding.isPercent())
568 w = containingBlock()->availableLogicalWidth();
569 return padding.calcMinValue(w);
572 RoundedRect RenderBoxModelObject::getBackgroundRoundedRect(const LayoutRect& borderRect, InlineFlowBox* box, LayoutUnit inlineBoxWidth, LayoutUnit inlineBoxHeight,
573 bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
575 RoundedRect border = style()->getRoundedBorderFor(borderRect, includeLogicalLeftEdge, includeLogicalRightEdge);
576 if (box && (box->nextLineBox() || box->prevLineBox())) {
577 RoundedRect segmentBorder = style()->getRoundedBorderFor(LayoutRect(0, 0, inlineBoxWidth, inlineBoxHeight), includeLogicalLeftEdge, includeLogicalRightEdge);
578 border.setRadii(segmentBorder.radii());
584 static LayoutRect backgroundRectAdjustedForBleedAvoidance(GraphicsContext* context, const LayoutRect& borderRect, BackgroundBleedAvoidance bleedAvoidance)
586 if (bleedAvoidance != BackgroundBleedShrinkBackground)
589 LayoutRect adjustedRect = borderRect;
590 // We need to shrink the border by one device pixel on each side.
591 AffineTransform ctm = context->getCTM();
592 FloatSize contextScale(static_cast<float>(ctm.xScale()), static_cast<float>(ctm.yScale()));
593 adjustedRect.inflateX(-ceilf(1 / contextScale.width()));
594 adjustedRect.inflateY(-ceilf(1 / contextScale.height()));
598 void RenderBoxModelObject::paintFillLayerExtended(const PaintInfo& paintInfo, const Color& color, const FillLayer* bgLayer, const LayoutRect& rect,
599 BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* box, const LayoutSize& boxSize, CompositeOperator op, RenderObject* backgroundObject)
601 GraphicsContext* context = paintInfo.context;
602 if (context->paintingDisabled() || rect.isEmpty())
605 bool includeLeftEdge = box ? box->includeLogicalLeftEdge() : true;
606 bool includeRightEdge = box ? box->includeLogicalRightEdge() : true;
608 bool hasRoundedBorder = style()->hasBorderRadius() && (includeLeftEdge || includeRightEdge);
609 bool clippedWithLocalScrolling = hasOverflowClip() && bgLayer->attachment() == LocalBackgroundAttachment;
610 bool isBorderFill = bgLayer->clip() == BorderFillBox;
611 bool isRoot = this->isRoot();
613 Color bgColor = color;
614 StyleImage* bgImage = bgLayer->image();
615 bool shouldPaintBackgroundImage = bgImage && bgImage->canRender(style()->effectiveZoom());
617 // When this style flag is set, change existing background colors and images to a solid white background.
618 // If there's no bg color or image, leave it untouched to avoid affecting transparency.
619 // We don't try to avoid loading the background images, because this style flag is only set
620 // when printing, and at that point we've already loaded the background images anyway. (To avoid
621 // loading the background images we'd have to do this check when applying styles rather than
623 if (style()->forceBackgroundsToWhite()) {
624 // Note that we can't reuse this variable below because the bgColor might be changed
625 bool shouldPaintBackgroundColor = !bgLayer->next() && bgColor.isValid() && bgColor.alpha() > 0;
626 if (shouldPaintBackgroundImage || shouldPaintBackgroundColor) {
627 bgColor = Color::white;
628 shouldPaintBackgroundImage = false;
632 bool colorVisible = bgColor.isValid() && bgColor.alpha() > 0;
634 // Fast path for drawing simple color backgrounds.
635 if (!isRoot && !clippedWithLocalScrolling && !shouldPaintBackgroundImage && isBorderFill && !bgLayer->next()) {
639 if (hasRoundedBorder && bleedAvoidance != BackgroundBleedUseTransparencyLayer) {
640 RoundedRect border = getBackgroundRoundedRect(backgroundRectAdjustedForBleedAvoidance(context, rect, bleedAvoidance), box, boxSize.width(), boxSize.height(), includeLeftEdge, includeRightEdge);
641 context->fillRoundedRect(border, bgColor, style()->colorSpace());
643 context->fillRect(rect, bgColor, style()->colorSpace());
648 bool clipToBorderRadius = hasRoundedBorder && bleedAvoidance != BackgroundBleedUseTransparencyLayer;
649 GraphicsContextStateSaver clipToBorderStateSaver(*context, clipToBorderRadius);
650 if (clipToBorderRadius) {
651 RoundedRect border = getBackgroundRoundedRect(backgroundRectAdjustedForBleedAvoidance(context, rect, bleedAvoidance), box, boxSize.width(), boxSize.height(), includeLeftEdge, includeRightEdge);
652 context->addRoundedRectClip(border);
655 LayoutUnit bLeft = includeLeftEdge ? borderLeft() : 0;
656 LayoutUnit bRight = includeRightEdge ? borderRight() : 0;
657 LayoutUnit pLeft = includeLeftEdge ? paddingLeft() : 0;
658 LayoutUnit pRight = includeRightEdge ? paddingRight() : 0;
660 GraphicsContextStateSaver clipWithScrollingStateSaver(*context, clippedWithLocalScrolling);
661 LayoutRect scrolledPaintRect = rect;
662 if (clippedWithLocalScrolling) {
663 // Clip to the overflow area.
664 context->clip(toRenderBox(this)->overflowClipRect(rect.location()));
666 // Adjust the paint rect to reflect a scrolled content box with borders at the ends.
667 LayoutSize offset = layer()->scrolledContentOffset();
668 scrolledPaintRect.move(-offset);
669 scrolledPaintRect.setWidth(bLeft + layer()->scrollWidth() + bRight);
670 scrolledPaintRect.setHeight(borderTop() + layer()->scrollHeight() + borderBottom());
673 GraphicsContextStateSaver backgroundClipStateSaver(*context, false);
674 if (bgLayer->clip() == PaddingFillBox || bgLayer->clip() == ContentFillBox) {
675 // Clip to the padding or content boxes as necessary.
676 bool includePadding = bgLayer->clip() == ContentFillBox;
677 LayoutRect clipRect = LayoutRect(scrolledPaintRect.x() + bLeft + (includePadding ? pLeft : 0),
678 scrolledPaintRect.y() + borderTop() + (includePadding ? paddingTop() : 0),
679 scrolledPaintRect.width() - bLeft - bRight - (includePadding ? pLeft + pRight : 0),
680 scrolledPaintRect.height() - borderTop() - borderBottom() - (includePadding ? paddingTop() + paddingBottom() : 0));
681 backgroundClipStateSaver.save();
682 context->clip(clipRect);
683 } else if (bgLayer->clip() == TextFillBox) {
684 // We have to draw our text into a mask that can then be used to clip background drawing.
685 // First figure out how big the mask has to be. It should be no bigger than what we need
686 // to actually render, so we should intersect the dirty rect with the border box of the background.
687 LayoutRect maskRect = rect;
688 maskRect.intersect(paintInfo.rect);
690 // Now create the mask.
691 OwnPtr<ImageBuffer> maskImage = ImageBuffer::create(maskRect.size());
695 GraphicsContext* maskImageContext = maskImage->context();
696 maskImageContext->translate(-maskRect.x(), -maskRect.y());
698 // Now add the text to the clip. We do this by painting using a special paint phase that signals to
699 // InlineTextBoxes that they should just add their contents to the clip.
700 PaintInfo info(maskImageContext, maskRect, PaintPhaseTextClip, true, 0, 0);
702 RootInlineBox* root = box->root();
703 box->paint(info, LayoutPoint(scrolledPaintRect.x() - box->x(), scrolledPaintRect.y() - box->y()), root->lineTop(), root->lineBottom());
705 LayoutSize localOffset = isBox() ? toRenderBox(this)->locationOffset() : LayoutSize();
706 paint(info, scrolledPaintRect.location() - localOffset);
709 // The mask has been created. Now we just need to clip to it.
710 backgroundClipStateSaver.save();
711 context->clipToImageBuffer(maskImage.get(), maskRect);
714 // Only fill with a base color (e.g., white) if we're the root document, since iframes/frames with
715 // no background in the child document should show the parent's background.
716 bool isOpaqueRoot = false;
719 if (!bgLayer->next() && !(bgColor.isValid() && bgColor.alpha() == 255) && view()->frameView()) {
720 Element* ownerElement = document()->ownerElement();
722 if (!ownerElement->hasTagName(frameTag)) {
723 // Locate the <body> element using the DOM. This is easier than trying
724 // to crawl around a render tree with potential :before/:after content and
725 // anonymous blocks created by inline <body> tags etc. We can locate the <body>
726 // render object very easily via the DOM.
727 HTMLElement* body = document()->body();
729 // Can't scroll a frameset document anyway.
730 isOpaqueRoot = body->hasLocalName(framesetTag);
734 // SVG documents and XML documents with SVG root nodes are transparent.
735 isOpaqueRoot = !document()->hasSVGRootNode();
740 isOpaqueRoot = !view()->frameView()->isTransparent();
742 view()->frameView()->setContentIsOpaque(isOpaqueRoot);
745 // Paint the color first underneath all images.
746 if (!bgLayer->next()) {
747 LayoutRect backgroundRect(scrolledPaintRect);
748 backgroundRect.intersect(paintInfo.rect);
749 // If we have an alpha and we are painting the root element, go ahead and blend with the base background color.
751 bool shouldClearBackground = false;
753 baseColor = view()->frameView()->baseBackgroundColor();
754 if (!baseColor.alpha())
755 shouldClearBackground = true;
758 if (baseColor.alpha()) {
760 baseColor = baseColor.blend(bgColor);
762 context->fillRect(backgroundRect, baseColor, style()->colorSpace(), CompositeCopy);
763 } else if (bgColor.alpha()) {
764 CompositeOperator operation = shouldClearBackground ? CompositeCopy : context->compositeOperation();
765 context->fillRect(backgroundRect, bgColor, style()->colorSpace(), operation);
766 } else if (shouldClearBackground)
767 context->clearRect(backgroundRect);
770 // no progressive loading of the background image
771 if (shouldPaintBackgroundImage) {
772 BackgroundImageGeometry geometry;
773 calculateBackgroundImageGeometry(bgLayer, scrolledPaintRect, geometry);
774 geometry.clip(paintInfo.rect);
775 if (!geometry.destRect().isEmpty()) {
776 CompositeOperator compositeOp = op == CompositeSourceOver ? bgLayer->composite() : op;
777 RenderObject* clientForBackgroundImage = backgroundObject ? backgroundObject : this;
778 RefPtr<Image> image = bgImage->image(clientForBackgroundImage, geometry.tileSize());
779 bool useLowQualityScaling = shouldPaintAtLowQuality(context, image.get(), bgLayer, geometry.tileSize());
780 context->drawTiledImage(image.get(), style()->colorSpace(), geometry.destRect(), geometry.relativePhase(), geometry.tileSize(),
781 compositeOp, useLowQualityScaling);
786 LayoutSize RenderBoxModelObject::calculateFillTileSize(const FillLayer* fillLayer, LayoutSize positioningAreaSize) const
788 StyleImage* image = fillLayer->image();
789 image->setImageContainerSize(positioningAreaSize); // Use the box established by background-origin.
791 EFillSizeType type = fillLayer->size().type;
795 LayoutUnit w = positioningAreaSize.width();
796 LayoutUnit h = positioningAreaSize.height();
798 Length layerWidth = fillLayer->size().size.width();
799 Length layerHeight = fillLayer->size().size.height();
801 if (layerWidth.isFixed())
802 w = layerWidth.value();
803 else if (layerWidth.isPercent())
804 w = layerWidth.calcValue(positioningAreaSize.width());
806 if (layerHeight.isFixed())
807 h = layerHeight.value();
808 else if (layerHeight.isPercent())
809 h = layerHeight.calcValue(positioningAreaSize.height());
811 // If one of the values is auto we have to use the appropriate
812 // scale to maintain our aspect ratio.
813 if (layerWidth.isAuto() && !layerHeight.isAuto()) {
814 LayoutSize imageIntrinsicSize = image->imageSize(this, style()->effectiveZoom());
815 if (imageIntrinsicSize.height())
816 w = imageIntrinsicSize.width() * h / imageIntrinsicSize.height();
817 } else if (!layerWidth.isAuto() && layerHeight.isAuto()) {
818 LayoutSize imageIntrinsicSize = image->imageSize(this, style()->effectiveZoom());
819 if (imageIntrinsicSize.width())
820 h = imageIntrinsicSize.height() * w / imageIntrinsicSize.width();
821 } else if (layerWidth.isAuto() && layerHeight.isAuto()) {
822 // If both width and height are auto, use the image's intrinsic size.
823 LayoutSize imageIntrinsicSize = image->imageSize(this, style()->effectiveZoom());
824 w = imageIntrinsicSize.width();
825 h = imageIntrinsicSize.height();
828 return LayoutSize(max<LayoutUnit>(1, w), max<LayoutUnit>(1, h));
832 LayoutSize imageIntrinsicSize = image->imageSize(this, 1);
833 float horizontalScaleFactor = imageIntrinsicSize.width()
834 ? static_cast<float>(positioningAreaSize.width()) / imageIntrinsicSize.width() : 1;
835 float verticalScaleFactor = imageIntrinsicSize.height()
836 ? static_cast<float>(positioningAreaSize.height()) / imageIntrinsicSize.height() : 1;
837 float scaleFactor = type == Contain ? min(horizontalScaleFactor, verticalScaleFactor) : max(horizontalScaleFactor, verticalScaleFactor);
838 return LayoutSize(max<LayoutUnit>(1, imageIntrinsicSize.width() * scaleFactor), max<LayoutUnit>(1, imageIntrinsicSize.height() * scaleFactor));
844 return image->imageSize(this, style()->effectiveZoom());
847 void RenderBoxModelObject::BackgroundImageGeometry::setNoRepeatX(int xOffset)
849 m_destRect.move(max(xOffset, 0), 0);
850 m_phase.setX(-min(xOffset, 0));
851 m_destRect.setWidth(m_tileSize.width() + min(xOffset, 0));
853 void RenderBoxModelObject::BackgroundImageGeometry::setNoRepeatY(int yOffset)
855 m_destRect.move(0, max(yOffset, 0));
856 m_phase.setY(-min(yOffset, 0));
857 m_destRect.setHeight(m_tileSize.height() + min(yOffset, 0));
860 void RenderBoxModelObject::BackgroundImageGeometry::useFixedAttachment(const LayoutPoint& attachmentPoint)
862 m_phase.move(max<LayoutUnit>(attachmentPoint.x() - m_destRect.x(), 0), max<LayoutUnit>(attachmentPoint.y() - m_destRect.y(), 0));
865 void RenderBoxModelObject::BackgroundImageGeometry::clip(const LayoutRect& clipRect)
867 m_destRect.intersect(clipRect);
870 LayoutPoint RenderBoxModelObject::BackgroundImageGeometry::relativePhase() const
872 LayoutPoint phase = m_phase;
873 phase += m_destRect.location() - m_destOrigin;
877 void RenderBoxModelObject::calculateBackgroundImageGeometry(const FillLayer* fillLayer, const LayoutRect& paintRect,
878 BackgroundImageGeometry& geometry)
882 LayoutSize positioningAreaSize;
884 // Determine the background positioning area and set destRect to the background painting area.
885 // destRect will be adjusted later if the background is non-repeating.
886 bool fixedAttachment = fillLayer->attachment() == FixedBackgroundAttachment;
888 #if ENABLE(FAST_MOBILE_SCROLLING)
889 if (view()->frameView() && view()->frameView()->canBlitOnScroll()) {
890 // As a side effect of an optimization to blit on scroll, we do not honor the CSS
891 // property "background-attachment: fixed" because it may result in rendering
892 // artifacts. Note, these artifacts only appear if we are blitting on scroll of
893 // a page that has fixed background images.
894 fixedAttachment = false;
898 if (!fixedAttachment) {
899 geometry.setDestRect(paintRect);
901 LayoutUnit right = 0;
902 LayoutUnit bottom = 0;
904 if (fillLayer->origin() != BorderFillBox) {
906 right = borderRight();
908 bottom = borderBottom();
909 if (fillLayer->origin() == ContentFillBox) {
910 left += paddingLeft();
911 right += paddingRight();
913 bottom += paddingBottom();
917 // The background of the box generated by the root element covers the entire canvas including
918 // its margins. Since those were added in already, we have to factor them out when computing
919 // the background positioning area.
921 positioningAreaSize = LayoutSize(toRenderBox(this)->width() - left - right, toRenderBox(this)->height() - top - bottom);
922 left += marginLeft();
925 positioningAreaSize = LayoutSize(paintRect.width() - left - right, paintRect.height() - top - bottom);
927 geometry.setDestRect(viewRect());
928 positioningAreaSize = geometry.destRect().size();
931 geometry.setTileSize(calculateFillTileSize(fillLayer, positioningAreaSize));
933 EFillRepeat backgroundRepeatX = fillLayer->repeatX();
934 EFillRepeat backgroundRepeatY = fillLayer->repeatY();
936 LayoutUnit xPosition = fillLayer->xPosition().calcMinValue(positioningAreaSize.width() - geometry.tileSize().width(), true);
937 if (backgroundRepeatX == RepeatFill)
938 geometry.setPhaseX(geometry.tileSize().width() ? layoutMod(geometry.tileSize().width() - (xPosition + left), geometry.tileSize().width()) : 0);
940 geometry.setNoRepeatX(xPosition + left);
942 LayoutUnit yPosition = fillLayer->yPosition().calcMinValue(positioningAreaSize.height() - geometry.tileSize().height(), true);
943 if (backgroundRepeatY == RepeatFill)
944 geometry.setPhaseY(geometry.tileSize().height() ? layoutMod(geometry.tileSize().height() - (yPosition + top), geometry.tileSize().height()) : 0);
946 geometry.setNoRepeatY(yPosition + top);
949 geometry.useFixedAttachment(paintRect.location());
951 geometry.clip(paintRect);
952 geometry.setDestOrigin(geometry.destRect().location());
955 static LayoutUnit computeBorderImageSide(Length borderSlice, LayoutUnit borderSide, LayoutUnit imageSide, LayoutUnit boxExtent)
957 if (borderSlice.isRelative())
958 return borderSlice.value() * borderSide;
959 if (borderSlice.isAuto())
961 return borderSlice.calcValue(boxExtent);
964 bool RenderBoxModelObject::paintNinePieceImage(GraphicsContext* graphicsContext, const LayoutRect& rect, const RenderStyle* style,
965 const NinePieceImage& ninePieceImage, CompositeOperator op)
967 StyleImage* styleImage = ninePieceImage.image();
971 if (!styleImage->isLoaded())
972 return true; // Never paint a nine-piece image incrementally, but don't paint the fallback borders either.
974 if (!styleImage->canRender(style->effectiveZoom()))
977 // FIXME: border-image is broken with full page zooming when tiling has to happen, since the tiling function
978 // doesn't have any understanding of the zoom that is in effect on the tile.
979 LayoutUnit topOutset;
980 LayoutUnit rightOutset;
981 LayoutUnit bottomOutset;
982 LayoutUnit leftOutset;
983 style->getImageOutsets(ninePieceImage, topOutset, rightOutset, bottomOutset, leftOutset);
985 LayoutUnit topWithOutset = rect.y() - topOutset;
986 LayoutUnit bottomWithOutset = rect.maxY() + bottomOutset;
987 LayoutUnit leftWithOutset = rect.x() - leftOutset;
988 LayoutUnit rightWithOutset = rect.maxX() + rightOutset;
989 LayoutRect borderImageRect = LayoutRect(leftWithOutset, topWithOutset, rightWithOutset - leftWithOutset, bottomWithOutset - topWithOutset);
991 styleImage->setImageContainerSize(borderImageRect.size());
992 LayoutSize imageSize = styleImage->imageSize(this, 1.0f);
993 LayoutUnit imageWidth = imageSize.width();
994 LayoutUnit imageHeight = imageSize.height();
996 LayoutUnit topSlice = min<LayoutUnit>(imageHeight, ninePieceImage.imageSlices().top().calcValue(imageHeight));
997 LayoutUnit rightSlice = min<LayoutUnit>(imageWidth, ninePieceImage.imageSlices().right().calcValue(imageWidth));
998 LayoutUnit bottomSlice = min<LayoutUnit>(imageHeight, ninePieceImage.imageSlices().bottom().calcValue(imageHeight));
999 LayoutUnit leftSlice = min<LayoutUnit>(imageWidth, ninePieceImage.imageSlices().left().calcValue(imageWidth));
1001 ENinePieceImageRule hRule = ninePieceImage.horizontalRule();
1002 ENinePieceImageRule vRule = ninePieceImage.verticalRule();
1004 LayoutUnit topWidth = computeBorderImageSide(ninePieceImage.borderSlices().top(), style->borderTopWidth(), topSlice, borderImageRect.height());
1005 LayoutUnit rightWidth = computeBorderImageSide(ninePieceImage.borderSlices().right(), style->borderRightWidth(), rightSlice, borderImageRect.width());
1006 LayoutUnit bottomWidth = computeBorderImageSide(ninePieceImage.borderSlices().bottom(), style->borderBottomWidth(), bottomSlice, borderImageRect.height());
1007 LayoutUnit leftWidth = computeBorderImageSide(ninePieceImage.borderSlices().left(), style->borderLeftWidth(), leftSlice, borderImageRect.width());
1009 // Reduce the widths if they're too large.
1010 // The spec says: Given Lwidth as the width of the border image area, Lheight as its height, and Wside as the border image width
1011 // offset for the side, let f = min(Lwidth/(Wleft+Wright), Lheight/(Wtop+Wbottom)). If f < 1, then all W are reduced by
1012 // multiplying them by f.
1013 int borderSideWidth = max(1, leftWidth + rightWidth);
1014 int borderSideHeight = max(1, topWidth + bottomWidth);
1015 float borderSideScaleFactor = min((float)borderImageRect.width() / borderSideWidth, (float)borderImageRect.height() / borderSideHeight);
1016 if (borderSideScaleFactor < 1) {
1017 topWidth *= borderSideScaleFactor;
1018 rightWidth *= borderSideScaleFactor;
1019 bottomWidth *= borderSideScaleFactor;
1020 leftWidth *= borderSideScaleFactor;
1023 bool drawLeft = leftSlice > 0 && leftWidth > 0;
1024 bool drawTop = topSlice > 0 && topWidth > 0;
1025 bool drawRight = rightSlice > 0 && rightWidth > 0;
1026 bool drawBottom = bottomSlice > 0 && bottomWidth > 0;
1027 bool drawMiddle = ninePieceImage.fill() && (imageWidth - leftSlice - rightSlice) > 0 && (borderImageRect.width() - leftWidth - rightWidth) > 0
1028 && (imageHeight - topSlice - bottomSlice) > 0 && (borderImageRect.height() - topWidth - bottomWidth) > 0;
1030 RefPtr<Image> image = styleImage->image(this, imageSize);
1031 ColorSpace colorSpace = style->colorSpace();
1033 float destinationWidth = borderImageRect.width() - leftWidth - rightWidth;
1034 float destinationHeight = borderImageRect.height() - topWidth - bottomWidth;
1036 float sourceWidth = imageWidth - leftSlice - rightSlice;
1037 float sourceHeight = imageHeight - topSlice - bottomSlice;
1039 float leftSideScale = drawLeft ? (float)leftWidth / leftSlice : 1;
1040 float rightSideScale = drawRight ? (float)rightWidth / rightSlice : 1;
1041 float topSideScale = drawTop ? (float)topWidth / topSlice : 1;
1042 float bottomSideScale = drawBottom ? (float)bottomWidth / bottomSlice : 1;
1045 // Paint the top and bottom left corners.
1047 // The top left corner rect is (tx, ty, leftWidth, topWidth)
1048 // The rect to use from within the image is obtained from our slice, and is (0, 0, leftSlice, topSlice)
1050 graphicsContext->drawImage(image.get(), colorSpace, LayoutRect(borderImageRect.location(), LayoutSize(leftWidth, topWidth)),
1051 LayoutRect(0, 0, leftSlice, topSlice), op);
1053 // The bottom left corner rect is (tx, ty + h - bottomWidth, leftWidth, bottomWidth)
1054 // The rect to use from within the image is (0, imageHeight - bottomSlice, leftSlice, botomSlice)
1056 graphicsContext->drawImage(image.get(), colorSpace, LayoutRect(borderImageRect.x(), borderImageRect.maxY() - bottomWidth, leftWidth, bottomWidth),
1057 LayoutRect(0, imageHeight - bottomSlice, leftSlice, bottomSlice), op);
1059 // Paint the left edge.
1060 // Have to scale and tile into the border rect.
1061 graphicsContext->drawTiledImage(image.get(), colorSpace, LayoutRect(borderImageRect.x(), borderImageRect.y() + topWidth, leftWidth,
1063 LayoutRect(0, topSlice, leftSlice, sourceHeight),
1064 FloatSize(leftSideScale, leftSideScale), Image::StretchTile, (Image::TileRule)vRule, op);
1068 // Paint the top and bottom right corners
1069 // The top right corner rect is (tx + w - rightWidth, ty, rightWidth, topWidth)
1070 // The rect to use from within the image is obtained from our slice, and is (imageWidth - rightSlice, 0, rightSlice, topSlice)
1072 graphicsContext->drawImage(image.get(), colorSpace, LayoutRect(borderImageRect.maxX() - rightWidth, borderImageRect.y(), rightWidth, topWidth),
1073 LayoutRect(imageWidth - rightSlice, 0, rightSlice, topSlice), op);
1075 // The bottom right corner rect is (tx + w - rightWidth, ty + h - bottomWidth, rightWidth, bottomWidth)
1076 // The rect to use from within the image is (imageWidth - rightSlice, imageHeight - bottomSlice, rightSlice, bottomSlice)
1078 graphicsContext->drawImage(image.get(), colorSpace, LayoutRect(borderImageRect.maxX() - rightWidth, borderImageRect.maxY() - bottomWidth, rightWidth, bottomWidth),
1079 LayoutRect(imageWidth - rightSlice, imageHeight - bottomSlice, rightSlice, bottomSlice), op);
1081 // Paint the right edge.
1082 graphicsContext->drawTiledImage(image.get(), colorSpace, LayoutRect(borderImageRect.maxX() - rightWidth, borderImageRect.y() + topWidth, rightWidth,
1084 LayoutRect(imageWidth - rightSlice, topSlice, rightSlice, sourceHeight),
1085 FloatSize(rightSideScale, rightSideScale),
1086 Image::StretchTile, (Image::TileRule)vRule, op);
1089 // Paint the top edge.
1091 graphicsContext->drawTiledImage(image.get(), colorSpace, LayoutRect(borderImageRect.x() + leftWidth, borderImageRect.y(), destinationWidth, topWidth),
1092 LayoutRect(leftSlice, 0, sourceWidth, topSlice),
1093 FloatSize(topSideScale, topSideScale), (Image::TileRule)hRule, Image::StretchTile, op);
1095 // Paint the bottom edge.
1097 graphicsContext->drawTiledImage(image.get(), colorSpace, LayoutRect(borderImageRect.x() + leftWidth, borderImageRect.maxY() - bottomWidth,
1098 destinationWidth, bottomWidth),
1099 LayoutRect(leftSlice, imageHeight - bottomSlice, sourceWidth, bottomSlice),
1100 FloatSize(bottomSideScale, bottomSideScale),
1101 (Image::TileRule)hRule, Image::StretchTile, op);
1103 // Paint the middle.
1105 FloatSize middleScaleFactor(1, 1);
1107 middleScaleFactor.setWidth(topSideScale);
1108 else if (drawBottom)
1109 middleScaleFactor.setWidth(bottomSideScale);
1111 middleScaleFactor.setHeight(leftSideScale);
1113 middleScaleFactor.setHeight(rightSideScale);
1115 // For "stretch" rules, just override the scale factor and replace. We only had to do this for the
1116 // center tile, since sides don't even use the scale factor unless they have a rule other than "stretch".
1117 // The middle however can have "stretch" specified in one axis but not the other, so we have to
1118 // correct the scale here.
1119 if (hRule == StretchImageRule)
1120 middleScaleFactor.setWidth(destinationWidth / sourceWidth);
1122 if (vRule == StretchImageRule)
1123 middleScaleFactor.setHeight(destinationHeight / sourceHeight);
1125 graphicsContext->drawTiledImage(image.get(), colorSpace,
1126 LayoutRect(borderImageRect.x() + leftWidth, borderImageRect.y() + topWidth, destinationWidth, destinationHeight),
1127 LayoutRect(leftSlice, topSlice, sourceWidth, sourceHeight),
1128 middleScaleFactor, (Image::TileRule)hRule, (Image::TileRule)vRule, op);
1136 BorderEdge(int edgeWidth, const Color& edgeColor, EBorderStyle edgeStyle, bool edgeIsTransparent, bool edgeIsPresent = true)
1140 , isTransparent(edgeIsTransparent)
1141 , isPresent(edgeIsPresent)
1143 if (style == DOUBLE && edgeWidth < 3)
1150 , isTransparent(false)
1155 bool hasVisibleColorAndStyle() const { return style > BHIDDEN && !isTransparent; }
1156 bool shouldRender() const { return isPresent && hasVisibleColorAndStyle(); }
1157 bool presentButInvisible() const { return usedWidth() && !hasVisibleColorAndStyle(); }
1158 bool obscuresBackgroundEdge(float scale) const
1160 if (!isPresent || isTransparent || width < (2 * scale) || color.hasAlpha() || style == BHIDDEN)
1163 if (style == DOTTED || style == DASHED)
1166 if (style == DOUBLE)
1167 return width >= 5 * scale; // The outer band needs to be >= 2px wide at unit scale.
1171 bool obscuresBackground() const
1173 if (!isPresent || isTransparent || color.hasAlpha() || style == BHIDDEN)
1176 if (style == DOTTED || style == DASHED || style == DOUBLE)
1182 int usedWidth() const { return isPresent ? width : 0; }
1184 void getDoubleBorderStripeWidths(int& outerWidth, int& innerWidth) const
1186 int fullWidth = usedWidth();
1187 outerWidth = fullWidth / 3;
1188 innerWidth = fullWidth * 2 / 3;
1190 // We need certain integer rounding results
1191 if (fullWidth % 3 == 2)
1194 if (fullWidth % 3 == 1)
1205 static bool allCornersClippedOut(const RoundedRect& border, const LayoutRect& clipRect)
1207 LayoutRect boundingRect = border.rect();
1208 if (clipRect.contains(boundingRect))
1211 RoundedRect::Radii radii = border.radii();
1213 LayoutRect topLeftRect(boundingRect.location(), radii.topLeft());
1214 if (clipRect.intersects(topLeftRect))
1217 LayoutRect topRightRect(boundingRect.location(), radii.topRight());
1218 topRightRect.setX(boundingRect.maxX() - topRightRect.width());
1219 if (clipRect.intersects(topRightRect))
1222 LayoutRect bottomLeftRect(boundingRect.location(), radii.bottomLeft());
1223 bottomLeftRect.setY(boundingRect.maxY() - bottomLeftRect.height());
1224 if (clipRect.intersects(bottomLeftRect))
1227 LayoutRect bottomRightRect(boundingRect.location(), radii.bottomRight());
1228 bottomRightRect.setX(boundingRect.maxX() - bottomRightRect.width());
1229 bottomRightRect.setY(boundingRect.maxY() - bottomRightRect.height());
1230 if (clipRect.intersects(bottomRightRect))
1236 #if HAVE(PATH_BASED_BORDER_RADIUS_DRAWING)
1237 static bool borderWillArcInnerEdge(const LayoutSize& firstRadius, const FloatSize& secondRadius)
1239 return !firstRadius.isZero() || !secondRadius.isZero();
1242 enum BorderEdgeFlag {
1243 TopBorderEdge = 1 << BSTop,
1244 RightBorderEdge = 1 << BSRight,
1245 BottomBorderEdge = 1 << BSBottom,
1246 LeftBorderEdge = 1 << BSLeft,
1247 AllBorderEdges = TopBorderEdge | BottomBorderEdge | LeftBorderEdge | RightBorderEdge
1250 static inline BorderEdgeFlag edgeFlagForSide(BoxSide side)
1252 return static_cast<BorderEdgeFlag>(1 << side);
1255 static inline bool includesEdge(BorderEdgeFlags flags, BoxSide side)
1257 return flags & edgeFlagForSide(side);
1260 inline bool edgesShareColor(const BorderEdge& firstEdge, const BorderEdge& secondEdge)
1262 return firstEdge.color == secondEdge.color;
1265 inline bool styleRequiresClipPolygon(EBorderStyle style)
1267 return style == DOTTED || style == DASHED; // These are drawn with a stroke, so we have to clip to get corner miters.
1270 static bool borderStyleFillsBorderArea(EBorderStyle style)
1272 return !(style == DOTTED || style == DASHED || style == DOUBLE);
1275 static bool borderStyleHasInnerDetail(EBorderStyle style)
1277 return style == GROOVE || style == RIDGE || style == DOUBLE;
1280 static bool borderStyleIsDottedOrDashed(EBorderStyle style)
1282 return style == DOTTED || style == DASHED;
1285 // OUTSET darkens the bottom and right (and maybe lightens the top and left)
1286 // INSET darkens the top and left (and maybe lightens the bottom and right)
1287 static inline bool borderStyleHasUnmatchedColorsAtCorner(EBorderStyle style, BoxSide side, BoxSide adjacentSide)
1289 // These styles match at the top/left and bottom/right.
1290 if (style == INSET || style == GROOVE || style == RIDGE || style == OUTSET) {
1291 const BorderEdgeFlags topRightFlags = edgeFlagForSide(BSTop) | edgeFlagForSide(BSRight);
1292 const BorderEdgeFlags bottomLeftFlags = edgeFlagForSide(BSBottom) | edgeFlagForSide(BSLeft);
1294 BorderEdgeFlags flags = edgeFlagForSide(side) | edgeFlagForSide(adjacentSide);
1295 return flags == topRightFlags || flags == bottomLeftFlags;
1300 static inline bool colorsMatchAtCorner(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1302 if (edges[side].shouldRender() != edges[adjacentSide].shouldRender())
1305 if (!edgesShareColor(edges[side], edges[adjacentSide]))
1308 return !borderStyleHasUnmatchedColorsAtCorner(edges[side].style, side, adjacentSide);
1311 // This assumes that we draw in order: top, bottom, left, right.
1312 static inline bool willBeOverdrawn(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1317 if (edges[adjacentSide].presentButInvisible())
1320 if (!edgesShareColor(edges[side], edges[adjacentSide]) && edges[adjacentSide].color.hasAlpha())
1323 if (!borderStyleFillsBorderArea(edges[adjacentSide].style))
1330 // These draw last, so are never overdrawn.
1336 static inline bool borderStylesRequireMitre(BoxSide side, BoxSide adjacentSide, EBorderStyle style, EBorderStyle adjacentStyle)
1338 if (style == DOUBLE || adjacentStyle == DOUBLE || adjacentStyle == GROOVE || adjacentStyle == RIDGE)
1341 if (borderStyleIsDottedOrDashed(style) != borderStyleIsDottedOrDashed(adjacentStyle))
1344 if (style != adjacentStyle)
1347 return borderStyleHasUnmatchedColorsAtCorner(style, side, adjacentSide);
1350 static bool joinRequiresMitre(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[], bool allowOverdraw)
1352 if ((edges[side].isTransparent && edges[adjacentSide].isTransparent) || !edges[adjacentSide].isPresent)
1355 if (allowOverdraw && willBeOverdrawn(side, adjacentSide, edges))
1358 if (!edgesShareColor(edges[side], edges[adjacentSide]))
1361 if (borderStylesRequireMitre(side, adjacentSide, edges[side].style, edges[adjacentSide].style))
1367 void RenderBoxModelObject::paintOneBorderSide(GraphicsContext* graphicsContext, const RenderStyle* style, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
1368 const LayoutRect& sideRect, BoxSide side, BoxSide adjacentSide1, BoxSide adjacentSide2, const BorderEdge edges[], const Path* path,
1369 BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias, const Color* overrideColor)
1371 const BorderEdge& edgeToRender = edges[side];
1372 const BorderEdge& adjacentEdge1 = edges[adjacentSide1];
1373 const BorderEdge& adjacentEdge2 = edges[adjacentSide2];
1375 bool mitreAdjacentSide1 = joinRequiresMitre(side, adjacentSide1, edges, !antialias);
1376 bool mitreAdjacentSide2 = joinRequiresMitre(side, adjacentSide2, edges, !antialias);
1378 bool adjacentSide1StylesMatch = colorsMatchAtCorner(side, adjacentSide1, edges);
1379 bool adjacentSide2StylesMatch = colorsMatchAtCorner(side, adjacentSide2, edges);
1381 const Color& colorToPaint = overrideColor ? *overrideColor : edgeToRender.color;
1384 GraphicsContextStateSaver stateSaver(*graphicsContext);
1385 clipBorderSidePolygon(graphicsContext, outerBorder, innerBorder, side, adjacentSide1StylesMatch, adjacentSide2StylesMatch);
1386 float thickness = max(max(edgeToRender.width, adjacentEdge1.width), adjacentEdge2.width);
1387 drawBoxSideFromPath(graphicsContext, outerBorder.rect(), *path, edges, edgeToRender.width, thickness, side, style,
1388 colorToPaint, edgeToRender.style, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
1390 bool shouldClip = styleRequiresClipPolygon(edgeToRender.style) && (mitreAdjacentSide1 || mitreAdjacentSide2);
1392 GraphicsContextStateSaver clipStateSaver(*graphicsContext, shouldClip);
1394 clipBorderSidePolygon(graphicsContext, outerBorder, innerBorder, side, !mitreAdjacentSide1, !mitreAdjacentSide2);
1395 // Since we clipped, no need to draw with a mitre.
1396 mitreAdjacentSide1 = false;
1397 mitreAdjacentSide2 = false;
1400 drawLineForBoxSide(graphicsContext, sideRect.x(), sideRect.y(), sideRect.maxX(), sideRect.maxY(), side, colorToPaint, edgeToRender.style,
1401 mitreAdjacentSide1 ? adjacentEdge1.width : 0, mitreAdjacentSide2 ? adjacentEdge2.width : 0, antialias);
1405 static LayoutRect calculateSideRect(const RoundedRect& outerBorder, const BorderEdge edges[], int side)
1407 LayoutRect sideRect = outerBorder.rect();
1408 int width = edges[side].width;
1411 sideRect.setHeight(width);
1412 else if (side == BSBottom)
1413 sideRect.shiftYEdgeTo(sideRect.maxY() - width);
1414 else if (side == BSLeft)
1415 sideRect.setWidth(width);
1417 sideRect.shiftXEdgeTo(sideRect.maxX() - width);
1422 void RenderBoxModelObject::paintBorderSides(GraphicsContext* graphicsContext, const RenderStyle* style, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
1423 const BorderEdge edges[], BorderEdgeFlags edgeSet, BackgroundBleedAvoidance bleedAvoidance,
1424 bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias, const Color* overrideColor)
1426 bool renderRadii = outerBorder.isRounded();
1430 roundedPath.addRoundedRect(outerBorder);
1432 if (edges[BSTop].shouldRender() && includesEdge(edgeSet, BSTop)) {
1433 LayoutRect sideRect = outerBorder.rect();
1434 sideRect.setHeight(edges[BSTop].width);
1436 bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSTop].style) || borderWillArcInnerEdge(innerBorder.radii().topLeft(), innerBorder.radii().topRight()));
1437 paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSTop, BSLeft, BSRight, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1440 if (edges[BSBottom].shouldRender() && includesEdge(edgeSet, BSBottom)) {
1441 LayoutRect sideRect = outerBorder.rect();
1442 sideRect.shiftYEdgeTo(sideRect.maxY() - edges[BSBottom].width);
1444 bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSBottom].style) || borderWillArcInnerEdge(innerBorder.radii().bottomLeft(), innerBorder.radii().bottomRight()));
1445 paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSBottom, BSLeft, BSRight, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1448 if (edges[BSLeft].shouldRender() && includesEdge(edgeSet, BSLeft)) {
1449 LayoutRect sideRect = outerBorder.rect();
1450 sideRect.setWidth(edges[BSLeft].width);
1452 bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSLeft].style) || borderWillArcInnerEdge(innerBorder.radii().bottomLeft(), innerBorder.radii().topLeft()));
1453 paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSLeft, BSTop, BSBottom, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1456 if (edges[BSRight].shouldRender() && includesEdge(edgeSet, BSRight)) {
1457 LayoutRect sideRect = outerBorder.rect();
1458 sideRect.shiftXEdgeTo(sideRect.maxX() - edges[BSRight].width);
1460 bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSRight].style) || borderWillArcInnerEdge(innerBorder.radii().bottomRight(), innerBorder.radii().topRight()));
1461 paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSRight, BSTop, BSBottom, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1465 void RenderBoxModelObject::paintTranslucentBorderSides(GraphicsContext* graphicsContext, const RenderStyle* style, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
1466 const BorderEdge edges[], BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias)
1468 BorderEdgeFlags edgesToDraw = AllBorderEdges;
1469 while (edgesToDraw) {
1470 // Find undrawn edges sharing a color.
1473 BorderEdgeFlags commonColorEdgeSet = 0;
1474 for (int i = BSTop; i <= BSLeft; ++i) {
1475 BoxSide currSide = static_cast<BoxSide>(i);
1476 if (!includesEdge(edgesToDraw, currSide))
1480 if (!commonColorEdgeSet) {
1481 commonColor = edges[currSide].color;
1484 includeEdge = edges[currSide].color == commonColor;
1487 commonColorEdgeSet |= edgeFlagForSide(currSide);
1490 bool useTransparencyLayer = commonColor.hasAlpha();
1491 if (useTransparencyLayer) {
1492 graphicsContext->beginTransparencyLayer(static_cast<float>(commonColor.alpha()) / 255);
1493 commonColor = Color(commonColor.red(), commonColor.green(), commonColor.blue());
1496 paintBorderSides(graphicsContext, style, outerBorder, innerBorder, edges, commonColorEdgeSet, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, &commonColor);
1498 if (useTransparencyLayer)
1499 graphicsContext->endTransparencyLayer();
1501 edgesToDraw &= ~commonColorEdgeSet;
1505 void RenderBoxModelObject::paintBorder(const PaintInfo& info, const LayoutRect& rect, const RenderStyle* style,
1506 BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
1508 GraphicsContext* graphicsContext = info.context;
1509 // border-image is not affected by border-radius.
1510 if (paintNinePieceImage(graphicsContext, rect, style, style->borderImage()))
1513 if (graphicsContext->paintingDisabled())
1516 BorderEdge edges[4];
1517 getBorderEdgeInfo(edges, includeLogicalLeftEdge, includeLogicalRightEdge);
1519 RoundedRect outerBorder = style->getRoundedBorderFor(rect, includeLogicalLeftEdge, includeLogicalRightEdge);
1520 RoundedRect innerBorder = style->getRoundedInnerBorderFor(rect, includeLogicalLeftEdge, includeLogicalRightEdge);
1522 const AffineTransform& currentCTM = graphicsContext->getCTM();
1523 // FIXME: this isn't quite correct. We may want to antialias when scaled by a non-integral value, or when the translation is non-integral.
1524 bool antialias = !currentCTM.isIdentityOrTranslationOrFlipped();
1526 bool haveAlphaColor = false;
1527 bool haveAllSolidEdges = true;
1528 bool allEdgesVisible = true;
1529 bool allEdgesShareColor = true;
1530 int firstVisibleEdge = -1;
1532 for (int i = BSTop; i <= BSLeft; ++i) {
1533 const BorderEdge& currEdge = edges[i];
1534 if (currEdge.presentButInvisible()) {
1535 allEdgesVisible = false;
1536 allEdgesShareColor = false;
1540 if (!currEdge.width) {
1541 allEdgesVisible = false;
1545 if (firstVisibleEdge == -1)
1546 firstVisibleEdge = i;
1547 else if (currEdge.color != edges[firstVisibleEdge].color)
1548 allEdgesShareColor = false;
1550 if (currEdge.color.hasAlpha())
1551 haveAlphaColor = true;
1553 if (currEdge.style != SOLID)
1554 haveAllSolidEdges = false;
1557 // If no corner intersects the clip region, we can pretend outerBorder is
1558 // rectangular to improve performance.
1559 if (haveAllSolidEdges && outerBorder.isRounded() && allCornersClippedOut(outerBorder, info.rect))
1560 outerBorder.setRadii(RoundedRect::Radii());
1562 // isRenderable() check avoids issue described in https://bugs.webkit.org/show_bug.cgi?id=38787
1563 if (haveAllSolidEdges && allEdgesShareColor && innerBorder.isRenderable()) {
1564 // Fast path for drawing all solid edges.
1565 if (allEdgesVisible && (outerBorder.isRounded() || haveAlphaColor)) {
1568 if (outerBorder.isRounded() && bleedAvoidance != BackgroundBleedUseTransparencyLayer)
1569 path.addRoundedRect(outerBorder);
1571 path.addRect(outerBorder.rect());
1573 if (innerBorder.isRounded())
1574 path.addRoundedRect(innerBorder);
1576 path.addRect(innerBorder.rect());
1578 graphicsContext->setFillRule(RULE_EVENODD);
1579 graphicsContext->setFillColor(edges[firstVisibleEdge].color, style->colorSpace());
1580 graphicsContext->fillPath(path);
1583 // Avoid creating transparent layers
1584 if (!allEdgesVisible && !outerBorder.isRounded() && haveAlphaColor) {
1587 for (int i = BSTop; i <= BSLeft; ++i) {
1588 const BorderEdge& currEdge = edges[i];
1589 if (currEdge.shouldRender()) {
1590 LayoutRect sideRect = calculateSideRect(outerBorder, edges, i);
1591 path.addRect(sideRect);
1595 graphicsContext->setFillRule(RULE_NONZERO);
1596 graphicsContext->setFillColor(edges[firstVisibleEdge].color, style->colorSpace());
1597 graphicsContext->fillPath(path);
1602 bool clipToOuterBorder = outerBorder.isRounded();
1603 GraphicsContextStateSaver stateSaver(*graphicsContext, clipToOuterBorder);
1604 if (clipToOuterBorder) {
1605 // Clip to the inner and outer radii rects.
1606 if (bleedAvoidance != BackgroundBleedUseTransparencyLayer)
1607 graphicsContext->addRoundedRectClip(outerBorder);
1608 graphicsContext->clipOutRoundedRect(innerBorder);
1612 paintTranslucentBorderSides(graphicsContext, style, outerBorder, innerBorder, edges, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias);
1614 paintBorderSides(graphicsContext, style, outerBorder, innerBorder, edges, AllBorderEdges, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias);
1617 void RenderBoxModelObject::drawBoxSideFromPath(GraphicsContext* graphicsContext, const LayoutRect& borderRect, const Path& borderPath, const BorderEdge edges[],
1618 float thickness, float drawThickness, BoxSide side, const RenderStyle* style,
1619 Color color, EBorderStyle borderStyle, BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
1624 if (borderStyle == DOUBLE && thickness < 3)
1625 borderStyle = SOLID;
1627 switch (borderStyle) {
1633 graphicsContext->setStrokeColor(color, style->colorSpace());
1635 // The stroke is doubled here because the provided path is the
1636 // outside edge of the border so half the stroke is clipped off.
1637 // The extra multiplier is so that the clipping mask can antialias
1638 // the edges to prevent jaggies.
1639 graphicsContext->setStrokeThickness(drawThickness * 2 * 1.1f);
1640 graphicsContext->setStrokeStyle(borderStyle == DASHED ? DashedStroke : DottedStroke);
1642 // If the number of dashes that fit in the path is odd and non-integral then we
1643 // will have an awkwardly-sized dash at the end of the path. To try to avoid that
1644 // here, we simply make the whitespace dashes ever so slightly bigger.
1645 // FIXME: This could be even better if we tried to manipulate the dash offset
1646 // and possibly the gapLength to get the corners dash-symmetrical.
1647 float dashLength = thickness * ((borderStyle == DASHED) ? 3.0f : 1.0f);
1648 float gapLength = dashLength;
1649 float numberOfDashes = borderPath.length() / dashLength;
1650 // Don't try to show dashes if we have less than 2 dashes + 2 gaps.
1651 // FIXME: should do this test per side.
1652 if (numberOfDashes >= 4) {
1653 bool evenNumberOfFullDashes = !((int)numberOfDashes % 2);
1654 bool integralNumberOfDashes = !(numberOfDashes - (int)numberOfDashes);
1655 if (!evenNumberOfFullDashes && !integralNumberOfDashes) {
1656 float numberOfGaps = numberOfDashes / 2;
1657 gapLength += (dashLength / numberOfGaps);
1661 lineDash.append(dashLength);
1662 lineDash.append(gapLength);
1663 graphicsContext->setLineDash(lineDash, dashLength);
1666 // FIXME: stroking the border path causes issues with tight corners:
1667 // https://bugs.webkit.org/show_bug.cgi?id=58711
1668 // Also, to get the best appearance we should stroke a path between the two borders.
1669 graphicsContext->strokePath(borderPath);
1673 // Get the inner border rects for both the outer border line and the inner border line
1674 int outerBorderTopWidth;
1675 int innerBorderTopWidth;
1676 edges[BSTop].getDoubleBorderStripeWidths(outerBorderTopWidth, innerBorderTopWidth);
1678 int outerBorderRightWidth;
1679 int innerBorderRightWidth;
1680 edges[BSRight].getDoubleBorderStripeWidths(outerBorderRightWidth, innerBorderRightWidth);
1682 int outerBorderBottomWidth;
1683 int innerBorderBottomWidth;
1684 edges[BSBottom].getDoubleBorderStripeWidths(outerBorderBottomWidth, innerBorderBottomWidth);
1686 int outerBorderLeftWidth;
1687 int innerBorderLeftWidth;
1688 edges[BSLeft].getDoubleBorderStripeWidths(outerBorderLeftWidth, innerBorderLeftWidth);
1690 // Draw inner border line
1692 GraphicsContextStateSaver stateSaver(*graphicsContext);
1693 RoundedRect innerClip = style->getRoundedInnerBorderFor(borderRect,
1694 innerBorderTopWidth, innerBorderBottomWidth, innerBorderLeftWidth, innerBorderRightWidth,
1695 includeLogicalLeftEdge, includeLogicalRightEdge);
1697 graphicsContext->addRoundedRectClip(innerClip);
1698 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, SOLID, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
1701 // Draw outer border line
1703 GraphicsContextStateSaver stateSaver(*graphicsContext);
1704 LayoutRect outerRect = borderRect;
1705 if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
1706 outerRect.inflate(1);
1707 ++outerBorderTopWidth;
1708 ++outerBorderBottomWidth;
1709 ++outerBorderLeftWidth;
1710 ++outerBorderRightWidth;
1713 RoundedRect outerClip = style->getRoundedInnerBorderFor(outerRect,
1714 outerBorderTopWidth, outerBorderBottomWidth, outerBorderLeftWidth, outerBorderRightWidth,
1715 includeLogicalLeftEdge, includeLogicalRightEdge);
1716 graphicsContext->clipOutRoundedRect(outerClip);
1717 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, SOLID, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
1726 if (borderStyle == GROOVE) {
1734 // Paint full border
1735 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, s1, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
1738 GraphicsContextStateSaver stateSaver(*graphicsContext);
1739 LayoutUnit topWidth = edges[BSTop].usedWidth() / 2;
1740 LayoutUnit bottomWidth = edges[BSBottom].usedWidth() / 2;
1741 LayoutUnit leftWidth = edges[BSLeft].usedWidth() / 2;
1742 LayoutUnit rightWidth = edges[BSRight].usedWidth() / 2;
1744 RoundedRect clipRect = style->getRoundedInnerBorderFor(borderRect,
1745 topWidth, bottomWidth, leftWidth, rightWidth,
1746 includeLogicalLeftEdge, includeLogicalRightEdge);
1748 graphicsContext->addRoundedRectClip(clipRect);
1749 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, s2, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
1753 if (side == BSTop || side == BSLeft)
1754 color = color.dark();
1757 if (side == BSBottom || side == BSRight)
1758 color = color.dark();
1764 graphicsContext->setStrokeStyle(NoStroke);
1765 graphicsContext->setFillColor(color, style->colorSpace());
1766 graphicsContext->drawRect(borderRect);
1769 void RenderBoxModelObject::paintBorder(const PaintInfo& info, const IntRect& rect, const RenderStyle* style,
1770 BackgroundBleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
1772 GraphicsContext* graphicsContext = info.context;
1773 // FIXME: This old version of paintBorder should be removed when all ports implement
1774 // GraphicsContext::clipConvexPolygon()!! This should happen soon.
1775 if (paintNinePieceImage(graphicsContext, rect, style, style->borderImage()))
1778 const Color& topColor = style->visitedDependentColor(CSSPropertyBorderTopColor);
1779 const Color& bottomColor = style->visitedDependentColor(CSSPropertyBorderBottomColor);
1780 const Color& leftColor = style->visitedDependentColor(CSSPropertyBorderLeftColor);
1781 const Color& rightColor = style->visitedDependentColor(CSSPropertyBorderRightColor);
1783 bool topTransparent = style->borderTopIsTransparent();
1784 bool bottomTransparent = style->borderBottomIsTransparent();
1785 bool rightTransparent = style->borderRightIsTransparent();
1786 bool leftTransparent = style->borderLeftIsTransparent();
1788 EBorderStyle topStyle = style->borderTopStyle();
1789 EBorderStyle bottomStyle = style->borderBottomStyle();
1790 EBorderStyle leftStyle = style->borderLeftStyle();
1791 EBorderStyle rightStyle = style->borderRightStyle();
1793 bool horizontal = style->isHorizontalWritingMode();
1794 bool renderTop = topStyle > BHIDDEN && !topTransparent && (horizontal || includeLogicalLeftEdge);
1795 bool renderLeft = leftStyle > BHIDDEN && !leftTransparent && (!horizontal || includeLogicalLeftEdge);
1796 bool renderRight = rightStyle > BHIDDEN && !rightTransparent && (!horizontal || includeLogicalRightEdge);
1797 bool renderBottom = bottomStyle > BHIDDEN && !bottomTransparent && (horizontal || includeLogicalRightEdge);
1800 RoundedRect border(rect);
1802 GraphicsContextStateSaver stateSaver(*graphicsContext, false);
1803 if (style->hasBorderRadius()) {
1804 border.includeLogicalEdges(style->getRoundedBorderFor(border.rect()).radii(),
1805 horizontal, includeLogicalLeftEdge, includeLogicalRightEdge);
1806 if (border.isRounded()) {
1808 graphicsContext->addRoundedRectClip(border);
1812 int firstAngleStart, secondAngleStart, firstAngleSpan, secondAngleSpan;
1814 bool renderRadii = border.isRounded();
1815 bool upperLeftBorderStylesMatch = renderLeft && (topStyle == leftStyle) && (topColor == leftColor);
1816 bool upperRightBorderStylesMatch = renderRight && (topStyle == rightStyle) && (topColor == rightColor) && (topStyle != OUTSET) && (topStyle != RIDGE) && (topStyle != INSET) && (topStyle != GROOVE);
1817 bool lowerLeftBorderStylesMatch = renderLeft && (bottomStyle == leftStyle) && (bottomColor == leftColor) && (bottomStyle != OUTSET) && (bottomStyle != RIDGE) && (bottomStyle != INSET) && (bottomStyle != GROOVE);
1818 bool lowerRightBorderStylesMatch = renderRight && (bottomStyle == rightStyle) && (bottomColor == rightColor);
1821 bool ignoreLeft = (renderRadii && border.radii().topLeft().width() > 0)
1822 || (topColor == leftColor && topTransparent == leftTransparent && topStyle >= OUTSET
1823 && (leftStyle == DOTTED || leftStyle == DASHED || leftStyle == SOLID || leftStyle == OUTSET));
1825 bool ignoreRight = (renderRadii && border.radii().topRight().width() > 0)
1826 || (topColor == rightColor && topTransparent == rightTransparent && topStyle >= OUTSET
1827 && (rightStyle == DOTTED || rightStyle == DASHED || rightStyle == SOLID || rightStyle == INSET));
1830 int x2 = rect.maxX();
1832 x += border.radii().topLeft().width();
1833 x2 -= border.radii().topRight().width();
1836 drawLineForBoxSide(graphicsContext, x, rect.y(), x2, rect.y() + style->borderTopWidth(), BSTop, topColor, topStyle,
1837 ignoreLeft ? 0 : style->borderLeftWidth(), ignoreRight ? 0 : style->borderRightWidth());
1840 int leftY = rect.y();
1842 // We make the arc double thick and let the clip rect take care of clipping the extra off.
1843 // We're doing this because it doesn't seem possible to match the curve of the clip exactly
1844 // with the arc-drawing function.
1845 thickness = style->borderTopWidth() * 2;
1847 if (border.radii().topLeft().width()) {
1848 int leftX = rect.x();
1849 // The inner clip clips inside the arc. This is especially important for 1px borders.
1850 bool applyLeftInnerClip = (style->borderLeftWidth() < border.radii().topLeft().width())
1851 && (style->borderTopWidth() < border.radii().topLeft().height())
1852 && (topStyle != DOUBLE || style->borderTopWidth() > 6);
1854 GraphicsContextStateSaver stateSaver(*graphicsContext, applyLeftInnerClip);
1855 if (applyLeftInnerClip)
1856 graphicsContext->addInnerRoundedRectClip(IntRect(leftX, leftY, border.radii().topLeft().width() * 2, border.radii().topLeft().height() * 2),
1857 style->borderTopWidth());
1859 firstAngleStart = 90;
1860 firstAngleSpan = upperLeftBorderStylesMatch ? 90 : 45;
1862 // Draw upper left arc
1863 drawArcForBoxSide(graphicsContext, leftX, leftY, thickness, border.radii().topLeft(), firstAngleStart, firstAngleSpan,
1864 BSTop, topColor, topStyle, true);
1867 if (border.radii().topRight().width()) {
1868 int rightX = rect.maxX() - border.radii().topRight().width() * 2;
1869 bool applyRightInnerClip = (style->borderRightWidth() < border.radii().topRight().width())
1870 && (style->borderTopWidth() < border.radii().topRight().height())
1871 && (topStyle != DOUBLE || style->borderTopWidth() > 6);
1873 GraphicsContextStateSaver stateSaver(*graphicsContext, applyRightInnerClip);
1874 if (applyRightInnerClip)
1875 graphicsContext->addInnerRoundedRectClip(IntRect(rightX, leftY, border.radii().topRight().width() * 2, border.radii().topRight().height() * 2),
1876 style->borderTopWidth());
1878 if (upperRightBorderStylesMatch) {
1879 secondAngleStart = 0;
1880 secondAngleSpan = 90;
1882 secondAngleStart = 45;
1883 secondAngleSpan = 45;
1886 // Draw upper right arc
1887 drawArcForBoxSide(graphicsContext, rightX, leftY, thickness, border.radii().topRight(), secondAngleStart, secondAngleSpan,
1888 BSTop, topColor, topStyle, false);
1894 bool ignoreLeft = (renderRadii && border.radii().bottomLeft().width() > 0)
1895 || (bottomColor == leftColor && bottomTransparent == leftTransparent && bottomStyle >= OUTSET
1896 && (leftStyle == DOTTED || leftStyle == DASHED || leftStyle == SOLID || leftStyle == OUTSET));
1898 bool ignoreRight = (renderRadii && border.radii().bottomRight().width() > 0)
1899 || (bottomColor == rightColor && bottomTransparent == rightTransparent && bottomStyle >= OUTSET
1900 && (rightStyle == DOTTED || rightStyle == DASHED || rightStyle == SOLID || rightStyle == INSET));
1903 int x2 = rect.maxX();
1905 x += border.radii().bottomLeft().width();
1906 x2 -= border.radii().bottomRight().width();
1909 drawLineForBoxSide(graphicsContext, x, rect.maxY() - style->borderBottomWidth(), x2, rect.maxY(), BSBottom, bottomColor, bottomStyle,
1910 ignoreLeft ? 0 : style->borderLeftWidth(), ignoreRight ? 0 : style->borderRightWidth());
1913 thickness = style->borderBottomWidth() * 2;
1915 if (border.radii().bottomLeft().width()) {
1916 int leftX = rect.x();
1917 int leftY = rect.maxY() - border.radii().bottomLeft().height() * 2;
1918 bool applyLeftInnerClip = (style->borderLeftWidth() < border.radii().bottomLeft().width())
1919 && (style->borderBottomWidth() < border.radii().bottomLeft().height())
1920 && (bottomStyle != DOUBLE || style->borderBottomWidth() > 6);
1922 GraphicsContextStateSaver stateSaver(*graphicsContext, applyLeftInnerClip);
1923 if (applyLeftInnerClip)
1924 graphicsContext->addInnerRoundedRectClip(IntRect(leftX, leftY, border.radii().bottomLeft().width() * 2, border.radii().bottomLeft().height() * 2),
1925 style->borderBottomWidth());
1927 if (lowerLeftBorderStylesMatch) {
1928 firstAngleStart = 180;
1929 firstAngleSpan = 90;
1931 firstAngleStart = 225;
1932 firstAngleSpan = 45;
1935 // Draw lower left arc
1936 drawArcForBoxSide(graphicsContext, leftX, leftY, thickness, border.radii().bottomLeft(), firstAngleStart, firstAngleSpan,
1937 BSBottom, bottomColor, bottomStyle, true);
1940 if (border.radii().bottomRight().width()) {
1941 int rightY = rect.maxY() - border.radii().bottomRight().height() * 2;
1942 int rightX = rect.maxX() - border.radii().bottomRight().width() * 2;
1943 bool applyRightInnerClip = (style->borderRightWidth() < border.radii().bottomRight().width())
1944 && (style->borderBottomWidth() < border.radii().bottomRight().height())
1945 && (bottomStyle != DOUBLE || style->borderBottomWidth() > 6);
1947 GraphicsContextStateSaver stateSaver(*graphicsContext, applyRightInnerClip);
1948 if (applyRightInnerClip)
1949 graphicsContext->addInnerRoundedRectClip(IntRect(rightX, rightY, border.radii().bottomRight().width() * 2, border.radii().bottomRight().height() * 2),
1950 style->borderBottomWidth());
1952 secondAngleStart = 270;
1953 secondAngleSpan = lowerRightBorderStylesMatch ? 90 : 45;
1955 // Draw lower right arc
1956 drawArcForBoxSide(graphicsContext, rightX, rightY, thickness, border.radii().bottomRight(), secondAngleStart, secondAngleSpan,
1957 BSBottom, bottomColor, bottomStyle, false);
1963 bool ignoreTop = (renderRadii && border.radii().topLeft().height() > 0)
1964 || (topColor == leftColor && topTransparent == leftTransparent && leftStyle >= OUTSET
1965 && (topStyle == DOTTED || topStyle == DASHED || topStyle == SOLID || topStyle == OUTSET));
1967 bool ignoreBottom = (renderRadii && border.radii().bottomLeft().height() > 0)
1968 || (bottomColor == leftColor && bottomTransparent == leftTransparent && leftStyle >= OUTSET
1969 && (bottomStyle == DOTTED || bottomStyle == DASHED || bottomStyle == SOLID || bottomStyle == INSET));
1972 int y2 = rect.maxY();
1974 y += border.radii().topLeft().height();
1975 y2 -= border.radii().bottomLeft().height();
1978 drawLineForBoxSide(graphicsContext, rect.x(), y, rect.x() + style->borderLeftWidth(), y2, BSLeft, leftColor, leftStyle,
1979 ignoreTop ? 0 : style->borderTopWidth(), ignoreBottom ? 0 : style->borderBottomWidth());
1981 if (renderRadii && (!upperLeftBorderStylesMatch || !lowerLeftBorderStylesMatch)) {
1982 int topX = rect.x();
1983 thickness = style->borderLeftWidth() * 2;
1985 if (!upperLeftBorderStylesMatch && border.radii().topLeft().width()) {
1986 int topY = rect.y();
1987 bool applyTopInnerClip = (style->borderLeftWidth() < border.radii().topLeft().width())
1988 && (style->borderTopWidth() < border.radii().topLeft().height())
1989 && (leftStyle != DOUBLE || style->borderLeftWidth() > 6);
1991 GraphicsContextStateSaver stateSaver(*graphicsContext, applyTopInnerClip);
1992 if (applyTopInnerClip)
1993 graphicsContext->addInnerRoundedRectClip(IntRect(topX, topY, border.radii().topLeft().width() * 2, border.radii().topLeft().height() * 2),
1994 style->borderLeftWidth());
1996 firstAngleStart = 135;
1997 firstAngleSpan = 45;
1999 // Draw top left arc
2000 drawArcForBoxSide(graphicsContext, topX, topY, thickness, border.radii().topLeft(), firstAngleStart, firstAngleSpan,
2001 BSLeft, leftColor, leftStyle, true);
2004 if (!lowerLeftBorderStylesMatch && border.radii().bottomLeft().width()) {
2005 int bottomY = rect.maxY() - border.radii().bottomLeft().height() * 2;
2006 bool applyBottomInnerClip = (style->borderLeftWidth() < border.radii().bottomLeft().width())
2007 && (style->borderBottomWidth() < border.radii().bottomLeft().height())
2008 && (leftStyle != DOUBLE || style->borderLeftWidth() > 6);
2010 GraphicsContextStateSaver stateSaver(*graphicsContext, applyBottomInnerClip);
2011 if (applyBottomInnerClip)
2012 graphicsContext->addInnerRoundedRectClip(IntRect(topX, bottomY, border.radii().bottomLeft().width() * 2, border.radii().bottomLeft().height() * 2),
2013 style->borderLeftWidth());
2015 secondAngleStart = 180;
2016 secondAngleSpan = 45;
2018 // Draw bottom left arc
2019 drawArcForBoxSide(graphicsContext, topX, bottomY, thickness, border.radii().bottomLeft(), secondAngleStart, secondAngleSpan,
2020 BSLeft, leftColor, leftStyle, false);
2026 bool ignoreTop = (renderRadii && border.radii().topRight().height() > 0)
2027 || ((topColor == rightColor) && (topTransparent == rightTransparent)
2028 && (rightStyle >= DOTTED || rightStyle == INSET)
2029 && (topStyle == DOTTED || topStyle == DASHED || topStyle == SOLID || topStyle == OUTSET));
2031 bool ignoreBottom = (renderRadii && border.radii().bottomRight().height() > 0)
2032 || ((bottomColor == rightColor) && (bottomTransparent == rightTransparent)
2033 && (rightStyle >= DOTTED || rightStyle == INSET)
2034 && (bottomStyle == DOTTED || bottomStyle == DASHED || bottomStyle == SOLID || bottomStyle == INSET));
2037 int y2 = rect.maxY();
2039 y += border.radii().topRight().height();
2040 y2 -= border.radii().bottomRight().height();
2043 drawLineForBoxSide(graphicsContext, rect.maxX() - style->borderRightWidth(), y, rect.maxX(), y2, BSRight, rightColor, rightStyle,
2044 ignoreTop ? 0 : style->borderTopWidth(), ignoreBottom ? 0 : style->borderBottomWidth());
2046 if (renderRadii && (!upperRightBorderStylesMatch || !lowerRightBorderStylesMatch)) {
2047 thickness = style->borderRightWidth() * 2;
2049 if (!upperRightBorderStylesMatch && border.radii().topRight().width()) {
2050 int topX = rect.maxX() - border.radii().topRight().width() * 2;
2051 int topY = rect.y();
2052 bool applyTopInnerClip = (style->borderRightWidth() < border.radii().topRight().width())
2053 && (style->borderTopWidth() < border.radii().topRight().height())
2054 && (rightStyle != DOUBLE || style->borderRightWidth() > 6);
2056 GraphicsContextStateSaver stateSaver(*graphicsContext, applyTopInnerClip);
2057 if (applyTopInnerClip)
2058 graphicsContext->addInnerRoundedRectClip(IntRect(topX, topY, border.radii().topRight().width() * 2, border.radii().topRight().height() * 2),
2059 style->borderRightWidth());
2061 firstAngleStart = 0;
2062 firstAngleSpan = 45;
2064 // Draw top right arc
2065 drawArcForBoxSide(graphicsContext, topX, topY, thickness, border.radii().topRight(), firstAngleStart, firstAngleSpan,
2066 BSRight, rightColor, rightStyle, true);
2069 if (!lowerRightBorderStylesMatch && border.radii().bottomRight().width()) {
2070 int bottomX = rect.maxX() - border.radii().bottomRight().width() * 2;
2071 int bottomY = rect.maxY() - border.radii().bottomRight().height() * 2;
2072 bool applyBottomInnerClip = (style->borderRightWidth() < border.radii().bottomRight().width())
2073 && (style->borderBottomWidth() < border.radii().bottomRight().height())
2074 && (rightStyle != DOUBLE || style->borderRightWidth() > 6);
2076 GraphicsContextStateSaver stateSaver(*graphicsContext, applyBottomInnerClip);
2077 if (applyBottomInnerClip)
2078 graphicsContext->addInnerRoundedRectClip(IntRect(bottomX, bottomY, border.radii().bottomRight().width() * 2, border.radii().bottomRight().height() * 2),
2079 style->borderRightWidth());
2081 secondAngleStart = 315;
2082 secondAngleSpan = 45;
2084 // Draw bottom right arc
2085 drawArcForBoxSide(graphicsContext, bottomX, bottomY, thickness, border.radii().bottomRight(), secondAngleStart, secondAngleSpan,
2086 BSRight, rightColor, rightStyle, false);
2093 static void findInnerVertex(const FloatPoint& outerCorner, const FloatPoint& innerCorner, const FloatPoint& centerPoint, FloatPoint& result)
2095 // If the line between outer and inner corner is towards the horizontal, intersect with a vertical line through the center,
2096 // otherwise with a horizontal line through the center. The points that form this line are arbitrary (we use 0, 100).
2097 // Note that if findIntersection fails, it will leave result untouched.
2098 if (fabs(outerCorner.x() - innerCorner.x()) > fabs(outerCorner.y() - innerCorner.y()))
2099 findIntersection(outerCorner, innerCorner, FloatPoint(centerPoint.x(), 0), FloatPoint(centerPoint.x(), 100), result);
2101 findIntersection(outerCorner, innerCorner, FloatPoint(0, centerPoint.y()), FloatPoint(100, centerPoint.y()), result);
2104 void RenderBoxModelObject::clipBorderSidePolygon(GraphicsContext* graphicsContext, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
2105 BoxSide side, bool firstEdgeMatches, bool secondEdgeMatches)
2109 const LayoutRect& outerRect = outerBorder.rect();
2110 const LayoutRect& innerRect = innerBorder.rect();
2112 FloatPoint centerPoint(innerRect.location().x() + static_cast<float>(innerRect.width()) / 2, innerRect.location().y() + static_cast<float>(innerRect.height()) / 2);
2114 // For each side, create a quad that encompasses all parts of that side that may draw,
2115 // including areas inside the innerBorder.
2117 // 0----------------3
2119 // |\ 1----------- 2 /|
2124 // |/ 1------------2 \|
2126 // 0----------------3
2130 quad[0] = outerRect.minXMinYCorner();
2131 quad[1] = innerRect.minXMinYCorner();
2132 quad[2] = innerRect.maxXMinYCorner();
2133 quad[3] = outerRect.maxXMinYCorner();
2135 if (!innerBorder.radii().topLeft().isZero())
2136 findInnerVertex(outerRect.minXMinYCorner(), innerRect.minXMinYCorner(), centerPoint, quad[1]);
2138 if (!innerBorder.radii().topRight().isZero())
2139 findInnerVertex(outerRect.maxXMinYCorner(), innerRect.maxXMinYCorner(), centerPoint, quad[2]);
2143 quad[0] = outerRect.minXMinYCorner();
2144 quad[1] = innerRect.minXMinYCorner();
2145 quad[2] = innerRect.minXMaxYCorner();
2146 quad[3] = outerRect.minXMaxYCorner();
2148 if (!innerBorder.radii().topLeft().isZero())
2149 findInnerVertex(outerRect.minXMinYCorner(), innerRect.minXMinYCorner(), centerPoint, quad[1]);
2151 if (!innerBorder.radii().bottomLeft().isZero())
2152 findInnerVertex(outerRect.minXMaxYCorner(), innerRect.minXMaxYCorner(), centerPoint, quad[2]);
2156 quad[0] = outerRect.minXMaxYCorner();
2157 quad[1] = innerRect.minXMaxYCorner();
2158 quad[2] = innerRect.maxXMaxYCorner();
2159 quad[3] = outerRect.maxXMaxYCorner();
2161 if (!innerBorder.radii().bottomLeft().isZero())
2162 findInnerVertex(outerRect.minXMaxYCorner(), innerRect.minXMaxYCorner(), centerPoint, quad[1]);
2164 if (!innerBorder.radii().bottomRight().isZero())
2165 findInnerVertex(outerRect.maxXMaxYCorner(), innerRect.maxXMaxYCorner(), centerPoint, quad[2]);
2169 quad[0] = outerRect.maxXMinYCorner();
2170 quad[1] = innerRect.maxXMinYCorner();
2171 quad[2] = innerRect.maxXMaxYCorner();
2172 quad[3] = outerRect.maxXMaxYCorner();
2174 if (!innerBorder.radii().topRight().isZero())
2175 findInnerVertex(outerRect.maxXMinYCorner(), innerRect.maxXMinYCorner(), centerPoint, quad[1]);
2177 if (!innerBorder.radii().bottomRight().isZero())
2178 findInnerVertex(outerRect.maxXMaxYCorner(), innerRect.maxXMaxYCorner(), centerPoint, quad[2]);
2182 // If the border matches both of its adjacent sides, don't anti-alias the clip, and
2183 // if neither side matches, anti-alias the clip.
2184 if (firstEdgeMatches == secondEdgeMatches) {
2185 graphicsContext->clipConvexPolygon(4, quad, !firstEdgeMatches);
2189 // Square off the end which shouldn't be affected by antialiasing, and clip.
2190 FloatPoint firstQuad[4];
2191 firstQuad[0] = quad[0];
2192 firstQuad[1] = quad[1];
2193 firstQuad[2] = side == BSTop || side == BSBottom ? FloatPoint(quad[3].x(), quad[2].y())
2194 : FloatPoint(quad[2].x(), quad[3].y());
2195 firstQuad[3] = quad[3];
2196 graphicsContext->clipConvexPolygon(4, firstQuad, !firstEdgeMatches);
2198 FloatPoint secondQuad[4];
2199 secondQuad[0] = quad[0];
2200 secondQuad[1] = side == BSTop || side == BSBottom ? FloatPoint(quad[0].x(), quad[1].y())
2201 : FloatPoint(quad[1].x(), quad[0].y());
2202 secondQuad[2] = quad[2];
2203 secondQuad[3] = quad[3];
2204 // Antialiasing affects the second side.
2205 graphicsContext->clipConvexPolygon(4, secondQuad, !secondEdgeMatches);
2208 void RenderBoxModelObject::getBorderEdgeInfo(BorderEdge edges[], bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
2210 const RenderStyle* style = this->style();
2211 bool horizontal = style->isHorizontalWritingMode();
2213 edges[BSTop] = BorderEdge(style->borderTopWidth(),
2214 style->visitedDependentColor(CSSPropertyBorderTopColor),
2215 style->borderTopStyle(),
2216 style->borderTopIsTransparent(),
2217 horizontal || includeLogicalLeftEdge);
2219 edges[BSRight] = BorderEdge(style->borderRightWidth(),
2220 style->visitedDependentColor(CSSPropertyBorderRightColor),
2221 style->borderRightStyle(),
2222 style->borderRightIsTransparent(),
2223 !horizontal || includeLogicalRightEdge);
2225 edges[BSBottom] = BorderEdge(style->borderBottomWidth(),
2226 style->visitedDependentColor(CSSPropertyBorderBottomColor),
2227 style->borderBottomStyle(),
2228 style->borderBottomIsTransparent(),
2229 horizontal || includeLogicalRightEdge);
2231 edges[BSLeft] = BorderEdge(style->borderLeftWidth(),
2232 style->visitedDependentColor(CSSPropertyBorderLeftColor),
2233 style->borderLeftStyle(),
2234 style->borderLeftIsTransparent(),
2235 !horizontal || includeLogicalLeftEdge);
2238 bool RenderBoxModelObject::borderObscuresBackgroundEdge(const FloatSize& contextScale) const
2240 BorderEdge edges[4];
2241 getBorderEdgeInfo(edges);
2243 for (int i = BSTop; i <= BSLeft; ++i) {
2244 const BorderEdge& currEdge = edges[i];
2245 // FIXME: for vertical text
2246 float axisScale = (i == BSTop || i == BSBottom) ? contextScale.height() : contextScale.width();
2247 if (!currEdge.obscuresBackgroundEdge(axisScale))
2254 bool RenderBoxModelObject::borderObscuresBackground() const
2256 if (!style()->hasBorder())
2259 // Bail if we have any border-image for now. We could look at the image alpha to improve this.
2260 if (style()->borderImage().image())
2263 BorderEdge edges[4];
2264 getBorderEdgeInfo(edges);
2266 for (int i = BSTop; i <= BSLeft; ++i) {
2267 const BorderEdge& currEdge = edges[i];
2268 if (!currEdge.obscuresBackground())
2275 static inline LayoutRect areaCastingShadowInHole(const LayoutRect& holeRect, int shadowBlur, int shadowSpread, const LayoutSize& shadowOffset)
2277 LayoutRect bounds(holeRect);
2279 bounds.inflate(shadowBlur);
2281 if (shadowSpread < 0)
2282 bounds.inflate(-shadowSpread);
2284 LayoutRect offsetBounds = bounds;
2285 offsetBounds.move(-shadowOffset);
2286 return unionRect(bounds, offsetBounds);
2289 void RenderBoxModelObject::paintBoxShadow(const PaintInfo& info, const LayoutRect& paintRect, const RenderStyle* s, ShadowStyle shadowStyle, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
2291 // FIXME: Deal with border-image. Would be great to use border-image as a mask.
2292 GraphicsContext* context = info.context;
2293 if (context->paintingDisabled() || !s->boxShadow())
2296 RoundedRect border = (shadowStyle == Inset) ? s->getRoundedInnerBorderFor(paintRect, includeLogicalLeftEdge, includeLogicalRightEdge)
2297 : s->getRoundedBorderFor(paintRect, includeLogicalLeftEdge, includeLogicalRightEdge);
2299 bool hasBorderRadius = s->hasBorderRadius();
2300 bool isHorizontal = s->isHorizontalWritingMode();
2302 bool hasOpaqueBackground = s->visitedDependentColor(CSSPropertyBackgroundColor).isValid() && s->visitedDependentColor(CSSPropertyBackgroundColor).alpha() == 255;
2303 for (const ShadowData* shadow = s->boxShadow(); shadow; shadow = shadow->next()) {
2304 if (shadow->style() != shadowStyle)
2307 LayoutSize shadowOffset(shadow->x(), shadow->y());
2308 LayoutUnit shadowBlur = shadow->blur();
2309 LayoutUnit shadowSpread = shadow->spread();
2311 if (shadowOffset.isZero() && !shadowBlur && !shadowSpread)
2314 const Color& shadowColor = shadow->color();
2316 if (shadow->style() == Normal) {
2317 RoundedRect fillRect = border;
2318 fillRect.inflate(shadowSpread);
2319 if (fillRect.isEmpty())
2322 LayoutRect shadowRect(border.rect());
2323 shadowRect.inflate(shadowBlur + shadowSpread);
2324 shadowRect.move(shadowOffset);
2326 GraphicsContextStateSaver stateSaver(*context);
2327 context->clip(shadowRect);
2329 // Move the fill just outside the clip, adding 1 pixel separation so that the fill does not
2330 // bleed in (due to antialiasing) if the context is transformed.
2331 LayoutSize extraOffset(paintRect.width() + max<LayoutUnit>(0, shadowOffset.width()) + shadowBlur + 2 * shadowSpread + 1, 0);
2332 shadowOffset -= extraOffset;
2333 fillRect.move(extraOffset);
2335 if (shadow->isWebkitBoxShadow())
2336 context->setLegacyShadow(shadowOffset, shadowBlur, shadowColor, s->colorSpace());
2338 context->setShadow(shadowOffset, shadowBlur, shadowColor, s->colorSpace());
2340 if (hasBorderRadius) {
2341 RoundedRect rectToClipOut = border;
2343 // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
2344 // when painting the shadow. On the other hand, it introduces subpixel gaps along the
2345 // corners. Those are avoided by insetting the clipping path by one pixel.
2346 if (hasOpaqueBackground) {
2347 rectToClipOut.inflateWithRadii(-1);
2350 if (!rectToClipOut.isEmpty())
2351 context->clipOutRoundedRect(rectToClipOut);
2353 RoundedRect influenceRect(shadowRect, border.radii());
2354 influenceRect.expandRadii(2 * shadowBlur + shadowSpread);
2355 if (allCornersClippedOut(influenceRect, info.rect))
2356 context->fillRect(fillRect.rect(), Color::black, s->colorSpace());
2358 fillRect.expandRadii(shadowSpread);
2359 context->fillRoundedRect(fillRect, Color::black, s->colorSpace());
2362 LayoutRect rectToClipOut = border.rect();
2364 // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
2365 // when painting the shadow. On the other hand, it introduces subpixel gaps along the
2366 // edges if they are not pixel-aligned. Those are avoided by insetting the clipping path
2368 if (hasOpaqueBackground) {
2369 AffineTransform currentTransformation = context->getCTM();
2370 if (currentTransformation.a() != 1 || (currentTransformation.d() != 1 && currentTransformation.d() != -1)
2371 || currentTransformation.b() || currentTransformation.c())
2372 rectToClipOut.inflate(-1);
2375 if (!rectToClipOut.isEmpty())
2376 context->clipOut(rectToClipOut);
2377 context->fillRect(fillRect.rect(), Color::black, s->colorSpace());
2381 LayoutRect holeRect(border.rect());
2382 holeRect.inflate(-shadowSpread);
2384 if (holeRect.isEmpty()) {
2385 if (hasBorderRadius)
2386 context->fillRoundedRect(border, shadowColor, s->colorSpace());
2388 context->fillRect(border.rect(), shadowColor, s->colorSpace());
2392 if (!includeLogicalLeftEdge) {
2394 holeRect.move(-max<LayoutUnit>(shadowOffset.width(), 0) - shadowBlur, 0);
2395 holeRect.setWidth(holeRect.width() + max<LayoutUnit>(shadowOffset.width(), 0) + shadowBlur);
2397 holeRect.move(0, -max<LayoutUnit>(shadowOffset.height(), 0) - shadowBlur);
2398 holeRect.setHeight(holeRect.height() + max<LayoutUnit>(shadowOffset.height(), 0) + shadowBlur);
2401 if (!includeLogicalRightEdge) {
2403 holeRect.setWidth(holeRect.width() - min<LayoutUnit>(shadowOffset.width(), 0) + shadowBlur);
2405 holeRect.setHeight(holeRect.height() - min<LayoutUnit>(shadowOffset.height(), 0) + shadowBlur);
2408 Color fillColor(shadowColor.red(), shadowColor.green(), shadowColor.blue(), 255);
2410 LayoutRect outerRect = areaCastingShadowInHole(border.rect(), shadowBlur, shadowSpread, shadowOffset);
2411 RoundedRect roundedHole(holeRect, border.radii());
2413 GraphicsContextStateSaver stateSaver(*context);
2414 if (hasBorderRadius) {
2416 path.addRoundedRect(border);
2417 context->clip(path);
2418 roundedHole.shrinkRadii(shadowSpread);
2420 context->clip(border.rect());
2422 LayoutSize extraOffset(2 * paintRect.width() + max<LayoutUnit>(0, shadowOffset.width()) + shadowBlur - 2 * shadowSpread + 1, 0);
2423 context->translate(extraOffset.width(), extraOffset.height());
2424 shadowOffset -= extraOffset;
2426 if (shadow->isWebkitBoxShadow())
2427 context->setLegacyShadow(shadowOffset, shadowBlur, shadowColor, s->colorSpace());
2429 context->setShadow(shadowOffset, shadowBlur, shadowColor, s->colorSpace());
2431 context->fillRectWithRoundedHole(outerRect, roundedHole, fillColor, s->colorSpace());
2436 LayoutUnit RenderBoxModelObject::containingBlockLogicalWidthForContent() const
2438 return containingBlock()->availableLogicalWidth();
2441 RenderBoxModelObject* RenderBoxModelObject::continuation() const
2443 if (!continuationMap)
2445 return continuationMap->get(this);
2448 void RenderBoxModelObject::setContinuation(RenderBoxModelObject* continuation)
2451 if (!continuationMap)
2452 continuationMap = new ContinuationMap;
2453 continuationMap->set(this, continuation);
2455 if (continuationMap)
2456 continuationMap->remove(this);
2460 } // namespace WebCore