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 "FilterOperations.h"
30 #include "GraphicsContext.h"
31 #include "HTMLFrameOwnerElement.h"
32 #include "HTMLNames.h"
33 #include "ImageBuffer.h"
36 #include "RenderBlock.h"
37 #include "RenderInline.h"
38 #include "RenderLayer.h"
39 #include "RenderView.h"
41 #include "TransformState.h"
42 #include <wtf/CurrentTime.h>
44 #if USE(ACCELERATED_COMPOSITING)
45 #include "RenderLayerBacking.h"
46 #include "RenderLayerCompositor.h"
53 using namespace HTMLNames;
55 bool RenderBoxModelObject::s_wasFloating = false;
56 bool RenderBoxModelObject::s_hadLayer = false;
57 bool RenderBoxModelObject::s_hadTransform = false;
58 bool RenderBoxModelObject::s_layerWasSelfPainting = false;
60 static const double cInterpolationCutoff = 800. * 800.;
61 static const double cLowQualityTimeThreshold = 0.500; // 500 ms
63 typedef HashMap<const void*, LayoutSize> LayerSizeMap;
64 typedef HashMap<RenderBoxModelObject*, LayerSizeMap> ObjectLayerSizeMap;
66 // The HashMap for storing continuation pointers.
67 // An inline can be split with blocks occuring in between the inline content.
68 // When this occurs we need a pointer to the next object. We can basically be
69 // split into a sequence of inlines and blocks. The continuation will either be
70 // an anonymous block (that houses other blocks) or it will be an inline flow.
71 // <b><i><p>Hello</p></i></b>. In this example the <i> will have a block as
72 // its continuation but the <b> will just have an inline as its continuation.
73 typedef HashMap<const RenderBoxModelObject*, RenderBoxModelObject*> ContinuationMap;
74 static ContinuationMap* continuationMap = 0;
76 // This HashMap is similar to the continuation map, but connects first-letter
77 // renderers to their remaining text fragments.
78 typedef HashMap<const RenderBoxModelObject*, RenderObject*> FirstLetterRemainingTextMap;
79 static FirstLetterRemainingTextMap* firstLetterRemainingTextMap = 0;
81 class ImageQualityController {
82 WTF_MAKE_NONCOPYABLE(ImageQualityController); WTF_MAKE_FAST_ALLOCATED;
84 ImageQualityController();
85 bool shouldPaintAtLowQuality(GraphicsContext*, RenderBoxModelObject*, Image*, const void* layer, const LayoutSize&);
86 void removeLayer(RenderBoxModelObject*, LayerSizeMap* innerMap, const void* layer);
87 void set(RenderBoxModelObject*, LayerSizeMap* innerMap, const void* layer, const LayoutSize&);
88 void objectDestroyed(RenderBoxModelObject*);
89 bool isEmpty() { return m_objectLayerSizeMap.isEmpty(); }
92 void highQualityRepaintTimerFired(Timer<ImageQualityController>*);
95 ObjectLayerSizeMap m_objectLayerSizeMap;
96 Timer<ImageQualityController> m_timer;
97 bool m_animatedResizeIsActive;
100 ImageQualityController::ImageQualityController()
101 : m_timer(this, &ImageQualityController::highQualityRepaintTimerFired)
102 , m_animatedResizeIsActive(false)
106 void ImageQualityController::removeLayer(RenderBoxModelObject* object, LayerSizeMap* innerMap, const void* layer)
109 innerMap->remove(layer);
110 if (innerMap->isEmpty())
111 objectDestroyed(object);
115 void ImageQualityController::set(RenderBoxModelObject* object, LayerSizeMap* innerMap, const void* layer, const LayoutSize& size)
118 innerMap->set(layer, size);
120 LayerSizeMap newInnerMap;
121 newInnerMap.set(layer, size);
122 m_objectLayerSizeMap.set(object, newInnerMap);
126 void ImageQualityController::objectDestroyed(RenderBoxModelObject* object)
128 m_objectLayerSizeMap.remove(object);
129 if (m_objectLayerSizeMap.isEmpty()) {
130 m_animatedResizeIsActive = false;
135 void ImageQualityController::highQualityRepaintTimerFired(Timer<ImageQualityController>*)
137 if (m_animatedResizeIsActive) {
138 m_animatedResizeIsActive = false;
139 for (ObjectLayerSizeMap::iterator it = m_objectLayerSizeMap.begin(); it != m_objectLayerSizeMap.end(); ++it)
140 it->first->repaint();
144 void ImageQualityController::restartTimer()
146 m_timer.startOneShot(cLowQualityTimeThreshold);
149 bool ImageQualityController::shouldPaintAtLowQuality(GraphicsContext* context, RenderBoxModelObject* object, Image* image, const void *layer, const LayoutSize& size)
151 // If the image is not a bitmap image, then none of this is relevant and we just paint at high
153 if (!image || !image->isBitmapImage() || context->paintingDisabled())
156 if (object->style()->imageRendering() == ImageRenderingOptimizeContrast)
159 // Make sure to use the unzoomed image size, since if a full page zoom is in effect, the image
160 // is actually being scaled.
161 IntSize imageSize(image->width(), image->height());
163 // Look ourselves up in the hashtables.
164 ObjectLayerSizeMap::iterator i = m_objectLayerSizeMap.find(object);
165 LayerSizeMap* innerMap = i != m_objectLayerSizeMap.end() ? &i->second : 0;
167 bool isFirstResize = true;
169 LayerSizeMap::iterator j = innerMap->find(layer);
170 if (j != innerMap->end()) {
171 isFirstResize = false;
176 const AffineTransform& currentTransform = context->getCTM();
177 bool contextIsScaled = !currentTransform.isIdentityOrTranslationOrFlipped();
178 if (!contextIsScaled && size == imageSize) {
179 // There is no scale in effect. If we had a scale in effect before, we can just remove this object from the list.
180 removeLayer(object, innerMap, layer);
184 // There is no need to hash scaled images that always use low quality mode when the page demands it. This is the iChat case.
185 if (object->document()->page()->inLowQualityImageInterpolationMode()) {
186 double totalPixels = static_cast<double>(image->width()) * static_cast<double>(image->height());
187 if (totalPixels > cInterpolationCutoff)
191 // If an animated resize is active, paint in low quality and kick the timer ahead.
192 if (m_animatedResizeIsActive) {
193 set(object, innerMap, layer, size);
197 // If this is the first time resizing this image, or its size is the
198 // same as the last resize, draw at high res, but record the paint
199 // size and set the timer.
200 if (isFirstResize || oldSize == size) {
202 set(object, innerMap, layer, size);
205 // If the timer is no longer active, draw at high quality and don't
207 if (!m_timer.isActive()) {
208 removeLayer(object, innerMap, layer);
211 // This object has been resized to two different sizes while the timer
212 // is active, so draw at low quality, set the flag for animated resizes and
213 // the object to the list for high quality redraw.
214 set(object, innerMap, layer, size);
215 m_animatedResizeIsActive = true;
220 static ImageQualityController* gImageQualityController = 0;
222 static ImageQualityController* imageQualityController()
224 if (!gImageQualityController)
225 gImageQualityController = new ImageQualityController;
227 return gImageQualityController;
230 void RenderBoxModelObject::setSelectionState(SelectionState state)
232 if (state == SelectionInside && selectionState() != SelectionNone)
235 if ((state == SelectionStart && selectionState() == SelectionEnd)
236 || (state == SelectionEnd && selectionState() == SelectionStart))
237 RenderObject::setSelectionState(SelectionBoth);
239 RenderObject::setSelectionState(state);
241 // FIXME: We should consider whether it is OK propagating to ancestor RenderInlines.
242 // This is a workaround for http://webkit.org/b/32123
243 // The containing block can be null in case of an orphaned tree.
244 RenderBlock* containingBlock = this->containingBlock();
245 if (containingBlock && !containingBlock->isRenderView())
246 containingBlock->setSelectionState(state);
249 #if USE(ACCELERATED_COMPOSITING)
250 void RenderBoxModelObject::contentChanged(ContentChangeType changeType)
255 layer()->contentChanged(changeType);
258 bool RenderBoxModelObject::hasAcceleratedCompositing() const
260 return view()->compositor()->hasAcceleratedCompositing();
263 bool RenderBoxModelObject::startTransition(double timeOffset, CSSPropertyID propertyId, const RenderStyle* fromStyle, const RenderStyle* toStyle)
266 ASSERT(isComposited());
267 return layer()->backing()->startTransition(timeOffset, propertyId, fromStyle, toStyle);
270 void RenderBoxModelObject::transitionPaused(double timeOffset, CSSPropertyID propertyId)
273 ASSERT(isComposited());
274 layer()->backing()->transitionPaused(timeOffset, propertyId);
277 void RenderBoxModelObject::transitionFinished(CSSPropertyID propertyId)
280 ASSERT(isComposited());
281 layer()->backing()->transitionFinished(propertyId);
284 bool RenderBoxModelObject::startAnimation(double timeOffset, const Animation* animation, const KeyframeList& keyframes)
287 ASSERT(isComposited());
288 return layer()->backing()->startAnimation(timeOffset, animation, keyframes);
291 void RenderBoxModelObject::animationPaused(double timeOffset, const String& name)
294 ASSERT(isComposited());
295 layer()->backing()->animationPaused(timeOffset, name);
298 void RenderBoxModelObject::animationFinished(const String& name)
301 ASSERT(isComposited());
302 layer()->backing()->animationFinished(name);
305 void RenderBoxModelObject::suspendAnimations(double time)
308 ASSERT(isComposited());
309 layer()->backing()->suspendAnimations(time);
313 bool RenderBoxModelObject::shouldPaintAtLowQuality(GraphicsContext* context, Image* image, const void* layer, const LayoutSize& size)
315 return imageQualityController()->shouldPaintAtLowQuality(context, this, image, layer, size);
318 RenderBoxModelObject::RenderBoxModelObject(Node* node)
324 RenderBoxModelObject::~RenderBoxModelObject()
326 // Our layer should have been destroyed and cleared by now
329 if (gImageQualityController) {
330 gImageQualityController->objectDestroyed(this);
331 if (gImageQualityController->isEmpty()) {
332 delete gImageQualityController;
333 gImageQualityController = 0;
338 void RenderBoxModelObject::destroyLayer()
340 ASSERT(!hasLayer()); // Callers should have already called setHasLayer(false)
342 m_layer->destroy(renderArena());
346 void RenderBoxModelObject::willBeDestroyed()
348 // A continuation of this RenderObject should be destroyed at subclasses.
349 ASSERT(!continuation());
351 // If this is a first-letter object with a remaining text fragment then the
352 // entry needs to be cleared from the map.
353 if (firstLetterRemainingText())
354 setFirstLetterRemainingText(0);
356 // RenderObject::willBeDestroyed calls back to destroyLayer() for layer destruction
357 RenderObject::willBeDestroyed();
360 bool RenderBoxModelObject::hasSelfPaintingLayer() const
362 return m_layer && m_layer->isSelfPaintingLayer();
365 void RenderBoxModelObject::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
367 s_wasFloating = isFloating();
368 s_hadLayer = hasLayer();
369 s_hadTransform = hasTransform();
371 s_layerWasSelfPainting = layer()->isSelfPaintingLayer();
373 // If our z-index changes value or our visibility changes,
374 // we need to dirty our stacking context's z-order list.
375 RenderStyle* oldStyle = style();
376 if (oldStyle && newStyle) {
378 // Do a repaint with the old style first, e.g., for example if we go from
379 // having an outline to not having an outline.
380 if (diff == StyleDifferenceRepaintLayer) {
381 layer()->repaintIncludingDescendants();
382 if (!(oldStyle->clip() == newStyle->clip()))
383 layer()->clearClipRectsIncludingDescendants();
384 } else if (diff == StyleDifferenceRepaint || newStyle->outlineSize() < oldStyle->outlineSize())
388 if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
389 // When a layout hint happens, we go ahead and do a repaint of the layer, since the layer could
390 // end up being destroyed.
392 if (oldStyle->position() != newStyle->position()
393 || oldStyle->zIndex() != newStyle->zIndex()
394 || oldStyle->hasAutoZIndex() != newStyle->hasAutoZIndex()
395 || !(oldStyle->clip() == newStyle->clip())
396 || oldStyle->hasClip() != newStyle->hasClip()
397 || oldStyle->opacity() != newStyle->opacity()
398 || oldStyle->transform() != newStyle->transform()
399 #if ENABLE(CSS_FILTERS)
400 || oldStyle->filter() != newStyle->filter()
403 layer()->repaintIncludingDescendants();
404 } else if (newStyle->hasTransform() || newStyle->opacity() < 1 || newStyle->hasFilter()) {
405 // If we don't have a layer yet, but we are going to get one because of transform or opacity,
406 // then we need to repaint the old position of the object.
412 RenderObject::styleWillChange(diff, newStyle);
415 void RenderBoxModelObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
417 RenderObject::styleDidChange(diff, oldStyle);
418 updateBoxModelInfoFromStyle();
420 if (requiresLayer()) {
421 if (!layer() && layerCreationAllowedForSubtree()) {
422 if (s_wasFloating && isFloating())
423 setChildNeedsLayout(true);
424 m_layer = new (renderArena()) RenderLayer(this);
426 m_layer->insertOnlyThisLayer();
427 if (parent() && !needsLayout() && containingBlock()) {
428 m_layer->setRepaintStatus(NeedsFullRepaint);
429 // There is only one layer to update, it is not worth using |cachedOffset| since
430 // we are not sure the value will be used.
431 m_layer->updateLayerPositions(0);
434 } else if (layer() && layer()->parent()) {
435 setHasTransform(false); // Either a transform wasn't specified or the object doesn't support transforms, so just null out the bit.
436 setHasReflection(false);
437 m_layer->removeOnlyThisLayer(); // calls destroyLayer() which clears m_layer
438 if (s_wasFloating && isFloating())
439 setChildNeedsLayout(true);
441 setNeedsLayoutAndPrefWidthsRecalc();
445 layer()->styleChanged(diff, oldStyle);
446 if (s_hadLayer && layer()->isSelfPaintingLayer() != s_layerWasSelfPainting)
447 setChildNeedsLayout(true);
451 void RenderBoxModelObject::updateBoxModelInfoFromStyle()
453 // Set the appropriate bits for a box model object. Since all bits are cleared in styleWillChange,
454 // we only check for bits that could possibly be set to true.
455 RenderStyle* styleToUse = style();
456 setHasBoxDecorations(hasBackground() || styleToUse->hasBorder() || styleToUse->hasAppearance() || styleToUse->boxShadow());
457 setInline(styleToUse->isDisplayInlineType());
458 setRelPositioned(styleToUse->position() == RelativePosition);
459 setHorizontalWritingMode(styleToUse->isHorizontalWritingMode());
462 static LayoutSize accumulateRelativePositionOffsets(const RenderObject* child)
464 if (!child->isAnonymousBlock() || !child->isRelPositioned())
467 RenderObject* p = toRenderBlock(child)->inlineElementContinuation();
468 while (p && p->isRenderInline()) {
469 if (p->isRelPositioned()) {
470 RenderInline* renderInline = toRenderInline(p);
471 offset += renderInline->relativePositionOffset();
478 LayoutSize RenderBoxModelObject::relativePositionOffset() const
480 LayoutSize offset = accumulateRelativePositionOffsets(this);
482 RenderBlock* containingBlock = this->containingBlock();
484 // Objects that shrink to avoid floats normally use available line width when computing containing block width. However
485 // in the case of relative positioning using percentages, we can't do this. The offset should always be resolved using the
486 // available width of the containing block. Therefore we don't use containingBlockLogicalWidthForContent() here, but instead explicitly
487 // call availableWidth on our containing block.
488 if (!style()->left().isAuto()) {
489 if (!style()->right().isAuto() && !containingBlock->style()->isLeftToRightDirection())
490 offset.setWidth(-valueForLength(style()->right(), containingBlock->availableWidth(), view()));
492 offset.expand(valueForLength(style()->left(), containingBlock->availableWidth(), view()), 0);
493 } else if (!style()->right().isAuto()) {
494 offset.expand(-valueForLength(style()->right(), containingBlock->availableWidth(), view()), 0);
497 // If the containing block of a relatively positioned element does not
498 // specify a height, a percentage top or bottom offset should be resolved as
499 // auto. An exception to this is if the containing block has the WinIE quirk
500 // where <html> and <body> assume the size of the viewport. In this case,
501 // calculate the percent offset based on this height.
502 // See <https://bugs.webkit.org/show_bug.cgi?id=26396>.
503 if (!style()->top().isAuto()
504 && (!containingBlock->style()->height().isAuto()
505 || !style()->top().isPercent()
506 || containingBlock->stretchesToViewport()))
507 offset.expand(0, valueForLength(style()->top(), containingBlock->availableHeight(), view()));
509 else if (!style()->bottom().isAuto()
510 && (!containingBlock->style()->height().isAuto()
511 || !style()->bottom().isPercent()
512 || containingBlock->stretchesToViewport()))
513 offset.expand(0, -valueForLength(style()->bottom(), containingBlock->availableHeight(), view()));
518 LayoutPoint RenderBoxModelObject::adjustedPositionRelativeToOffsetParent(const LayoutPoint& startPoint) const
520 // If the element is the HTML body element or doesn't have a parent
521 // return 0 and stop this algorithm.
522 if (isBody() || !parent())
523 return LayoutPoint();
525 LayoutPoint referencePoint = startPoint;
526 referencePoint.move(parent()->offsetForColumns(referencePoint));
528 // If the offsetParent of the element is null, or is the HTML body element,
529 // return the distance between the canvas origin and the left border edge
530 // of the element and stop this algorithm.
531 if (const RenderBoxModelObject* offsetParent = this->offsetParent()) {
532 if (offsetParent->isBox() && !offsetParent->isBody())
533 referencePoint.move(-toRenderBox(offsetParent)->borderLeft(), -toRenderBox(offsetParent)->borderTop());
534 if (!isOutOfFlowPositioned()) {
535 if (isRelPositioned())
536 referencePoint.move(relativePositionOffset());
537 const RenderObject* curr = parent();
538 while (curr != offsetParent) {
539 // FIXME: What are we supposed to do inside SVG content?
540 if (curr->isBox() && !curr->isTableRow())
541 referencePoint.moveBy(toRenderBox(curr)->topLeftLocation());
542 referencePoint.move(curr->parent()->offsetForColumns(referencePoint));
543 curr = curr->parent();
545 if (offsetParent->isBox() && offsetParent->isBody() && !offsetParent->isRelPositioned() && !offsetParent->isOutOfFlowPositioned())
546 referencePoint.moveBy(toRenderBox(offsetParent)->topLeftLocation());
550 return referencePoint;
553 LayoutUnit RenderBoxModelObject::offsetLeft() const
555 // Note that RenderInline and RenderBox override this to pass a different
556 // startPoint to adjustedPositionRelativeToOffsetParent.
557 return adjustedPositionRelativeToOffsetParent(LayoutPoint()).x();
560 LayoutUnit RenderBoxModelObject::offsetTop() const
562 // Note that RenderInline and RenderBox override this to pass a different
563 // startPoint to adjustedPositionRelativeToOffsetParent.
564 return adjustedPositionRelativeToOffsetParent(LayoutPoint()).y();
567 int RenderBoxModelObject::pixelSnappedOffsetWidth() const
569 return snapSizeToPixel(offsetWidth(), offsetLeft());
572 int RenderBoxModelObject::pixelSnappedOffsetHeight() const
574 return snapSizeToPixel(offsetHeight(), offsetTop());
577 LayoutUnit RenderBoxModelObject::computedCSSPaddingTop() const
579 LayoutUnit w = ZERO_LAYOUT_UNIT;
580 RenderView* renderView = 0;
581 Length padding = style()->paddingTop();
582 if (padding.isPercent())
583 w = containingBlock()->availableLogicalWidth();
584 else if (padding.isViewportPercentage())
586 return minimumValueForLength(padding, w, renderView);
589 LayoutUnit RenderBoxModelObject::computedCSSPaddingBottom() const
591 LayoutUnit w = ZERO_LAYOUT_UNIT;
592 RenderView* renderView = 0;
593 Length padding = style()->paddingBottom();
594 if (padding.isPercent())
595 w = containingBlock()->availableLogicalWidth();
596 else if (padding.isViewportPercentage())
598 return minimumValueForLength(padding, w, renderView);
601 LayoutUnit RenderBoxModelObject::computedCSSPaddingLeft() const
603 LayoutUnit w = ZERO_LAYOUT_UNIT;
604 RenderView* renderView = 0;
605 Length padding = style()->paddingLeft();
606 if (padding.isPercent())
607 w = containingBlock()->availableLogicalWidth();
608 else if (padding.isViewportPercentage())
610 return minimumValueForLength(padding, w, renderView);
613 LayoutUnit RenderBoxModelObject::computedCSSPaddingRight() const
615 LayoutUnit w = ZERO_LAYOUT_UNIT;
616 RenderView* renderView = 0;
617 Length padding = style()->paddingRight();
618 if (padding.isPercent())
619 w = containingBlock()->availableLogicalWidth();
620 else if (padding.isViewportPercentage())
622 return minimumValueForLength(padding, w, renderView);
625 LayoutUnit RenderBoxModelObject::computedCSSPaddingBefore() const
627 LayoutUnit w = ZERO_LAYOUT_UNIT;
628 RenderView* renderView = 0;
629 Length padding = style()->paddingBefore();
630 if (padding.isPercent())
631 w = containingBlock()->availableLogicalWidth();
632 else if (padding.isViewportPercentage())
634 return minimumValueForLength(padding, w, renderView);
637 LayoutUnit RenderBoxModelObject::computedCSSPaddingAfter() const
639 LayoutUnit w = ZERO_LAYOUT_UNIT;
640 RenderView* renderView = 0;
641 Length padding = style()->paddingAfter();
642 if (padding.isPercent())
643 w = containingBlock()->availableLogicalWidth();
644 else if (padding.isViewportPercentage())
646 return minimumValueForLength(padding, w, renderView);
649 LayoutUnit RenderBoxModelObject::computedCSSPaddingStart() const
651 LayoutUnit w = ZERO_LAYOUT_UNIT;
652 RenderView* renderView = 0;
653 Length padding = style()->paddingStart();
654 if (padding.isPercent())
655 w = containingBlock()->availableLogicalWidth();
656 else if (padding.isViewportPercentage())
658 return minimumValueForLength(padding, w, renderView);
661 LayoutUnit RenderBoxModelObject::computedCSSPaddingEnd() const
663 LayoutUnit w = ZERO_LAYOUT_UNIT;
664 RenderView* renderView = 0;
665 Length padding = style()->paddingEnd();
666 if (padding.isPercent())
667 w = containingBlock()->availableLogicalWidth();
668 else if (padding.isViewportPercentage())
670 return minimumValueForLength(padding, w, renderView);
673 RoundedRect RenderBoxModelObject::getBackgroundRoundedRect(const LayoutRect& borderRect, InlineFlowBox* box, LayoutUnit inlineBoxWidth, LayoutUnit inlineBoxHeight,
674 bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
676 RenderView* renderView = view();
677 RoundedRect border = style()->getRoundedBorderFor(borderRect, renderView, includeLogicalLeftEdge, includeLogicalRightEdge);
678 if (box && (box->nextLineBox() || box->prevLineBox())) {
679 RoundedRect segmentBorder = style()->getRoundedBorderFor(LayoutRect(0, 0, inlineBoxWidth, inlineBoxHeight), renderView, includeLogicalLeftEdge, includeLogicalRightEdge);
680 border.setRadii(segmentBorder.radii());
686 static LayoutRect backgroundRectAdjustedForBleedAvoidance(GraphicsContext* context, const LayoutRect& borderRect, BackgroundBleedAvoidance bleedAvoidance)
688 if (bleedAvoidance != BackgroundBleedShrinkBackground)
691 // We shrink the rectangle by one pixel on each side because the bleed is one pixel maximum.
692 AffineTransform transform = context->getCTM();
693 LayoutRect adjustedRect = borderRect;
694 adjustedRect.inflateX(-static_cast<LayoutUnit>(ceil(1 / transform.xScale())));
695 adjustedRect.inflateY(-static_cast<LayoutUnit>(ceil(1 / transform.yScale())));
699 static void applyBoxShadowForBackground(GraphicsContext* context, RenderStyle* style)
701 const ShadowData* boxShadow = style->boxShadow();
702 while (boxShadow->style() != Normal)
703 boxShadow = boxShadow->next();
705 FloatSize shadowOffset(boxShadow->x(), boxShadow->y());
706 if (!boxShadow->isWebkitBoxShadow())
707 context->setShadow(shadowOffset, boxShadow->blur(), boxShadow->color(), style->colorSpace());
709 context->setLegacyShadow(shadowOffset, boxShadow->blur(), boxShadow->color(), style->colorSpace());
712 void RenderBoxModelObject::paintFillLayerExtended(const PaintInfo& paintInfo, const Color& color, const FillLayer* bgLayer, const LayoutRect& rect,
713 BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* box, const LayoutSize& boxSize, CompositeOperator op, RenderObject* backgroundObject)
715 GraphicsContext* context = paintInfo.context;
716 if (context->paintingDisabled() || rect.isEmpty())
719 bool includeLeftEdge = box ? box->includeLogicalLeftEdge() : true;
720 bool includeRightEdge = box ? box->includeLogicalRightEdge() : true;
722 bool hasRoundedBorder = style()->hasBorderRadius() && (includeLeftEdge || includeRightEdge);
723 bool clippedWithLocalScrolling = hasOverflowClip() && bgLayer->attachment() == LocalBackgroundAttachment;
724 bool isBorderFill = bgLayer->clip() == BorderFillBox;
725 bool isRoot = this->isRoot();
727 Color bgColor = color;
728 StyleImage* bgImage = bgLayer->image();
729 bool shouldPaintBackgroundImage = bgImage && bgImage->canRender(this, style()->effectiveZoom());
731 bool forceBackgroundToWhite = false;
732 if (document()->printing()) {
733 if (style()->printColorAdjust() == PrintColorAdjustEconomy)
734 forceBackgroundToWhite = true;
735 if (document()->settings() && document()->settings()->shouldPrintBackgrounds())
736 forceBackgroundToWhite = false;
739 // When printing backgrounds is disabled or using economy mode,
740 // change existing background colors and images to a solid white background.
741 // If there's no bg color or image, leave it untouched to avoid affecting transparency.
742 // We don't try to avoid loading the background images, because this style flag is only set
743 // when printing, and at that point we've already loaded the background images anyway. (To avoid
744 // loading the background images we'd have to do this check when applying styles rather than
746 if (forceBackgroundToWhite) {
747 // Note that we can't reuse this variable below because the bgColor might be changed
748 bool shouldPaintBackgroundColor = !bgLayer->next() && bgColor.isValid() && bgColor.alpha() > 0;
749 if (shouldPaintBackgroundImage || shouldPaintBackgroundColor) {
750 bgColor = Color::white;
751 shouldPaintBackgroundImage = false;
755 bool colorVisible = bgColor.isValid() && bgColor.alpha() > 0;
757 // Fast path for drawing simple color backgrounds.
758 if (!isRoot && !clippedWithLocalScrolling && !shouldPaintBackgroundImage && isBorderFill && !bgLayer->next()) {
762 bool boxShadowShouldBeAppliedToBackground = this->boxShadowShouldBeAppliedToBackground(bleedAvoidance, box);
763 GraphicsContextStateSaver shadowStateSaver(*context, boxShadowShouldBeAppliedToBackground);
764 if (boxShadowShouldBeAppliedToBackground)
765 applyBoxShadowForBackground(context, style());
767 if (hasRoundedBorder && bleedAvoidance != BackgroundBleedUseTransparencyLayer) {
768 RoundedRect border = getBackgroundRoundedRect(backgroundRectAdjustedForBleedAvoidance(context, rect, bleedAvoidance), box, boxSize.width(), boxSize.height(), includeLeftEdge, includeRightEdge);
769 context->fillRoundedRect(border, bgColor, style()->colorSpace());
771 context->fillRect(pixelSnappedIntRect(rect), bgColor, style()->colorSpace());
776 bool clipToBorderRadius = hasRoundedBorder && bleedAvoidance != BackgroundBleedUseTransparencyLayer;
777 GraphicsContextStateSaver clipToBorderStateSaver(*context, clipToBorderRadius);
778 if (clipToBorderRadius) {
779 RoundedRect border = getBackgroundRoundedRect(backgroundRectAdjustedForBleedAvoidance(context, rect, bleedAvoidance), box, boxSize.width(), boxSize.height(), includeLeftEdge, includeRightEdge);
780 context->addRoundedRectClip(border);
783 int bLeft = includeLeftEdge ? borderLeft() : 0;
784 int bRight = includeRightEdge ? borderRight() : 0;
785 LayoutUnit pLeft = includeLeftEdge ? paddingLeft() : ZERO_LAYOUT_UNIT;
786 LayoutUnit pRight = includeRightEdge ? paddingRight() : ZERO_LAYOUT_UNIT;
788 GraphicsContextStateSaver clipWithScrollingStateSaver(*context, clippedWithLocalScrolling);
789 LayoutRect scrolledPaintRect = rect;
790 if (clippedWithLocalScrolling) {
791 // Clip to the overflow area.
792 RenderBox* thisBox = toRenderBox(this);
793 context->clip(thisBox->overflowClipRect(rect.location(), paintInfo.renderRegion));
795 // Adjust the paint rect to reflect a scrolled content box with borders at the ends.
796 IntSize offset = thisBox->scrolledContentOffset();
797 scrolledPaintRect.move(-offset);
798 scrolledPaintRect.setWidth(bLeft + layer()->scrollWidth() + bRight);
799 scrolledPaintRect.setHeight(borderTop() + layer()->scrollHeight() + borderBottom());
802 GraphicsContextStateSaver backgroundClipStateSaver(*context, false);
803 OwnPtr<ImageBuffer> maskImage;
806 if (bgLayer->clip() == PaddingFillBox || bgLayer->clip() == ContentFillBox) {
807 // Clip to the padding or content boxes as necessary.
808 bool includePadding = bgLayer->clip() == ContentFillBox;
809 LayoutRect clipRect = LayoutRect(scrolledPaintRect.x() + bLeft + (includePadding ? pLeft : ZERO_LAYOUT_UNIT),
810 scrolledPaintRect.y() + borderTop() + (includePadding ? paddingTop() : ZERO_LAYOUT_UNIT),
811 scrolledPaintRect.width() - bLeft - bRight - (includePadding ? pLeft + pRight : ZERO_LAYOUT_UNIT),
812 scrolledPaintRect.height() - borderTop() - borderBottom() - (includePadding ? paddingTop() + paddingBottom() : ZERO_LAYOUT_UNIT));
813 backgroundClipStateSaver.save();
814 if (clipToBorderRadius && includePadding) {
815 RoundedRect rounded = getBackgroundRoundedRect(clipRect, box, boxSize.width(), boxSize.height(), includeLeftEdge, includeRightEdge);
816 context->addRoundedRectClip(rounded);
818 context->clip(clipRect);
819 } else if (bgLayer->clip() == TextFillBox) {
820 // We have to draw our text into a mask that can then be used to clip background drawing.
821 // First figure out how big the mask has to be. It should be no bigger than what we need
822 // to actually render, so we should intersect the dirty rect with the border box of the background.
823 maskRect = pixelSnappedIntRect(rect);
824 maskRect.intersect(paintInfo.rect);
826 // Now create the mask.
827 maskImage = context->createCompatibleBuffer(maskRect.size());
831 GraphicsContext* maskImageContext = maskImage->context();
832 maskImageContext->translate(-maskRect.x(), -maskRect.y());
834 // Now add the text to the clip. We do this by painting using a special paint phase that signals to
835 // InlineTextBoxes that they should just add their contents to the clip.
836 PaintInfo info(maskImageContext, maskRect, PaintPhaseTextClip, true, 0, paintInfo.renderRegion, 0);
838 RootInlineBox* root = box->root();
839 box->paint(info, LayoutPoint(scrolledPaintRect.x() - box->x(), scrolledPaintRect.y() - box->y()), root->lineTop(), root->lineBottom());
841 LayoutSize localOffset = isBox() ? toRenderBox(this)->locationOffset() : LayoutSize();
842 paint(info, scrolledPaintRect.location() - localOffset);
845 // The mask has been created. Now we just need to clip to it.
846 backgroundClipStateSaver.save();
847 context->clip(maskRect);
848 context->beginTransparencyLayer(1);
851 // Only fill with a base color (e.g., white) if we're the root document, since iframes/frames with
852 // no background in the child document should show the parent's background.
853 bool isOpaqueRoot = false;
856 if (!bgLayer->next() && !(bgColor.isValid() && bgColor.alpha() == 255) && view()->frameView()) {
857 Element* ownerElement = document()->ownerElement();
859 if (!ownerElement->hasTagName(frameTag)) {
860 // Locate the <body> element using the DOM. This is easier than trying
861 // to crawl around a render tree with potential :before/:after content and
862 // anonymous blocks created by inline <body> tags etc. We can locate the <body>
863 // render object very easily via the DOM.
864 HTMLElement* body = document()->body();
866 // Can't scroll a frameset document anyway.
867 isOpaqueRoot = body->hasLocalName(framesetTag);
871 // SVG documents and XML documents with SVG root nodes are transparent.
872 isOpaqueRoot = !document()->hasSVGRootNode();
877 isOpaqueRoot = !view()->frameView()->isTransparent();
879 view()->frameView()->setContentIsOpaque(isOpaqueRoot);
882 // Paint the color first underneath all images.
883 if (!bgLayer->next()) {
884 IntRect backgroundRect(pixelSnappedIntRect(scrolledPaintRect));
885 bool boxShadowShouldBeAppliedToBackground = this->boxShadowShouldBeAppliedToBackground(bleedAvoidance, box);
886 if (!boxShadowShouldBeAppliedToBackground)
887 backgroundRect.intersect(paintInfo.rect);
889 // If we have an alpha and we are painting the root element, go ahead and blend with the base background color.
891 bool shouldClearBackground = false;
893 baseColor = view()->frameView()->baseBackgroundColor();
894 if (!baseColor.alpha())
895 shouldClearBackground = true;
898 GraphicsContextStateSaver shadowStateSaver(*context, boxShadowShouldBeAppliedToBackground);
899 if (boxShadowShouldBeAppliedToBackground)
900 applyBoxShadowForBackground(context, style());
902 if (baseColor.alpha()) {
904 baseColor = baseColor.blend(bgColor);
906 context->fillRect(backgroundRect, baseColor, style()->colorSpace(), CompositeCopy);
907 } else if (bgColor.alpha()) {
908 CompositeOperator operation = shouldClearBackground ? CompositeCopy : context->compositeOperation();
909 context->fillRect(backgroundRect, bgColor, style()->colorSpace(), operation);
910 } else if (shouldClearBackground)
911 context->clearRect(backgroundRect);
914 // no progressive loading of the background image
915 if (shouldPaintBackgroundImage) {
916 BackgroundImageGeometry geometry;
917 calculateBackgroundImageGeometry(bgLayer, scrolledPaintRect, geometry);
918 geometry.clip(paintInfo.rect);
919 if (!geometry.destRect().isEmpty()) {
920 CompositeOperator compositeOp = op == CompositeSourceOver ? bgLayer->composite() : op;
921 RenderObject* clientForBackgroundImage = backgroundObject ? backgroundObject : this;
922 RefPtr<Image> image = bgImage->image(clientForBackgroundImage, geometry.tileSize());
923 bool useLowQualityScaling = shouldPaintAtLowQuality(context, image.get(), bgLayer, geometry.tileSize());
924 context->drawTiledImage(image.get(), style()->colorSpace(), geometry.destRect(), geometry.relativePhase(), geometry.tileSize(),
925 compositeOp, useLowQualityScaling);
929 if (bgLayer->clip() == TextFillBox) {
930 context->drawImageBuffer(maskImage.get(), ColorSpaceDeviceRGB, maskRect, CompositeDestinationIn);
931 context->endTransparencyLayer();
935 static inline int resolveWidthForRatio(int height, const FloatSize& intrinsicRatio)
937 return ceilf(height * intrinsicRatio.width() / intrinsicRatio.height());
940 static inline int resolveHeightForRatio(int width, const FloatSize& intrinsicRatio)
942 return ceilf(width * intrinsicRatio.height() / intrinsicRatio.width());
945 static inline IntSize resolveAgainstIntrinsicWidthOrHeightAndRatio(const IntSize& size, const FloatSize& intrinsicRatio, int useWidth, int useHeight)
947 if (intrinsicRatio.isEmpty()) {
949 return IntSize(useWidth, size.height());
950 return IntSize(size.width(), useHeight);
954 return IntSize(useWidth, resolveHeightForRatio(useWidth, intrinsicRatio));
955 return IntSize(resolveWidthForRatio(useHeight, intrinsicRatio), useHeight);
958 static inline IntSize resolveAgainstIntrinsicRatio(const IntSize& size, const FloatSize& intrinsicRatio)
960 // Two possible solutions: (size.width(), solutionHeight) or (solutionWidth, size.height())
961 // "... must be assumed to be the largest dimensions..." = easiest answer: the rect with the largest surface area.
963 int solutionWidth = resolveWidthForRatio(size.height(), intrinsicRatio);
964 int solutionHeight = resolveHeightForRatio(size.width(), intrinsicRatio);
965 if (solutionWidth <= size.width()) {
966 if (solutionHeight <= size.height()) {
967 // If both solutions fit, choose the one covering the larger area.
968 int areaOne = solutionWidth * size.height();
969 int areaTwo = size.width() * solutionHeight;
970 if (areaOne < areaTwo)
971 return IntSize(size.width(), solutionHeight);
972 return IntSize(solutionWidth, size.height());
975 // Only the first solution fits.
976 return IntSize(solutionWidth, size.height());
979 // Only the second solution fits, assert that.
980 ASSERT(solutionHeight <= size.height());
981 return IntSize(size.width(), solutionHeight);
984 IntSize RenderBoxModelObject::calculateImageIntrinsicDimensions(StyleImage* image, const IntSize& positioningAreaSize, ScaleByEffectiveZoomOrNot shouldScaleOrNot) const
986 // A generated image without a fixed size, will always return the container size as intrinsic size.
987 if (image->isGeneratedImage() && image->usesImageContainerSize())
988 return IntSize(positioningAreaSize.width(), positioningAreaSize.height());
990 Length intrinsicWidth;
991 Length intrinsicHeight;
992 FloatSize intrinsicRatio;
993 image->computeIntrinsicDimensions(this, intrinsicWidth, intrinsicHeight, intrinsicRatio);
995 // Intrinsic dimensions expressed as percentages must be resolved relative to the dimensions of the rectangle
996 // that establishes the coordinate system for the 'background-position' property.
998 // FIXME: Remove unnecessary rounding when layout is off ints: webkit.org/b/63656
999 if (intrinsicWidth.isPercent() && intrinsicHeight.isPercent() && intrinsicRatio.isEmpty()) {
1000 // Resolve width/height percentages against positioningAreaSize, only if no intrinsic ratio is provided.
1001 int resolvedWidth = static_cast<int>(round(positioningAreaSize.width() * intrinsicWidth.percent() / 100));
1002 int resolvedHeight = static_cast<int>(round(positioningAreaSize.height() * intrinsicHeight.percent() / 100));
1003 return IntSize(resolvedWidth, resolvedHeight);
1006 IntSize resolvedSize(intrinsicWidth.isFixed() ? intrinsicWidth.value() : 0, intrinsicHeight.isFixed() ? intrinsicHeight.value() : 0);
1007 IntSize minimumSize(resolvedSize.width() > 0 ? 1 : 0, resolvedSize.height() > 0 ? 1 : 0);
1008 if (shouldScaleOrNot == ScaleByEffectiveZoom)
1009 resolvedSize.scale(style()->effectiveZoom());
1010 resolvedSize.clampToMinimumSize(minimumSize);
1012 if (!resolvedSize.isEmpty())
1013 return resolvedSize;
1015 // If the image has one of either an intrinsic width or an intrinsic height:
1016 // * and an intrinsic aspect ratio, then the missing dimension is calculated from the given dimension and the ratio.
1017 // * and no intrinsic aspect ratio, then the missing dimension is assumed to be the size of the rectangle that
1018 // establishes the coordinate system for the 'background-position' property.
1019 if (resolvedSize.width() > 0 || resolvedSize.height() > 0)
1020 return resolveAgainstIntrinsicWidthOrHeightAndRatio(positioningAreaSize, intrinsicRatio, resolvedSize.width(), resolvedSize.height());
1022 // If the image has no intrinsic dimensions and has an intrinsic ratio the dimensions must be assumed to be the
1023 // largest dimensions at that ratio such that neither dimension exceeds the dimensions of the rectangle that
1024 // establishes the coordinate system for the 'background-position' property.
1025 if (!intrinsicRatio.isEmpty())
1026 return resolveAgainstIntrinsicRatio(positioningAreaSize, intrinsicRatio);
1028 // If the image has no intrinsic ratio either, then the dimensions must be assumed to be the rectangle that
1029 // establishes the coordinate system for the 'background-position' property.
1030 return positioningAreaSize;
1033 IntSize RenderBoxModelObject::calculateFillTileSize(const FillLayer* fillLayer, const IntSize& positioningAreaSize) const
1035 StyleImage* image = fillLayer->image();
1036 EFillSizeType type = fillLayer->size().type;
1038 IntSize imageIntrinsicSize = calculateImageIntrinsicDimensions(image, positioningAreaSize, ScaleByEffectiveZoom);
1039 imageIntrinsicSize.scale(1 / image->imageScaleFactor(), 1 / image->imageScaleFactor());
1040 RenderView* renderView = view();
1043 int w = positioningAreaSize.width();
1044 int h = positioningAreaSize.height();
1046 Length layerWidth = fillLayer->size().size.width();
1047 Length layerHeight = fillLayer->size().size.height();
1049 if (layerWidth.isFixed())
1050 w = layerWidth.value();
1051 else if (layerWidth.isPercent() || layerHeight.isViewportPercentage())
1052 w = valueForLength(layerWidth, positioningAreaSize.width(), renderView);
1054 if (layerHeight.isFixed())
1055 h = layerHeight.value();
1056 else if (layerHeight.isPercent() || layerHeight.isViewportPercentage())
1057 h = valueForLength(layerHeight, positioningAreaSize.height(), renderView);
1059 // If one of the values is auto we have to use the appropriate
1060 // scale to maintain our aspect ratio.
1061 if (layerWidth.isAuto() && !layerHeight.isAuto()) {
1062 if (imageIntrinsicSize.height())
1063 w = imageIntrinsicSize.width() * h / imageIntrinsicSize.height();
1064 } else if (!layerWidth.isAuto() && layerHeight.isAuto()) {
1065 if (imageIntrinsicSize.width())
1066 h = imageIntrinsicSize.height() * w / imageIntrinsicSize.width();
1067 } else if (layerWidth.isAuto() && layerHeight.isAuto()) {
1068 // If both width and height are auto, use the image's intrinsic size.
1069 w = imageIntrinsicSize.width();
1070 h = imageIntrinsicSize.height();
1073 return IntSize(max(0, w), max(0, h));
1076 // If both values are ‘auto’ then the intrinsic width and/or height of the image should be used, if any.
1077 if (!imageIntrinsicSize.isEmpty())
1078 return imageIntrinsicSize;
1080 // If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for ‘contain’.
1085 float horizontalScaleFactor = imageIntrinsicSize.width()
1086 ? static_cast<float>(positioningAreaSize.width()) / imageIntrinsicSize.width() : 1;
1087 float verticalScaleFactor = imageIntrinsicSize.height()
1088 ? static_cast<float>(positioningAreaSize.height()) / imageIntrinsicSize.height() : 1;
1089 float scaleFactor = type == Contain ? min(horizontalScaleFactor, verticalScaleFactor) : max(horizontalScaleFactor, verticalScaleFactor);
1090 return IntSize(max(1, static_cast<int>(imageIntrinsicSize.width() * scaleFactor)), max(1, static_cast<int>(imageIntrinsicSize.height() * scaleFactor)));
1094 ASSERT_NOT_REACHED();
1098 void RenderBoxModelObject::BackgroundImageGeometry::setNoRepeatX(int xOffset)
1100 m_destRect.move(max(xOffset, 0), 0);
1101 m_phase.setX(-min(xOffset, 0));
1102 m_destRect.setWidth(m_tileSize.width() + min(xOffset, 0));
1104 void RenderBoxModelObject::BackgroundImageGeometry::setNoRepeatY(int yOffset)
1106 m_destRect.move(0, max(yOffset, 0));
1107 m_phase.setY(-min(yOffset, 0));
1108 m_destRect.setHeight(m_tileSize.height() + min(yOffset, 0));
1111 void RenderBoxModelObject::BackgroundImageGeometry::useFixedAttachment(const IntPoint& attachmentPoint)
1113 IntPoint alignedPoint = attachmentPoint;
1114 m_phase.move(max(alignedPoint.x() - m_destRect.x(), 0), max(alignedPoint.y() - m_destRect.y(), 0));
1117 void RenderBoxModelObject::BackgroundImageGeometry::clip(const IntRect& clipRect)
1119 m_destRect.intersect(clipRect);
1122 IntPoint RenderBoxModelObject::BackgroundImageGeometry::relativePhase() const
1124 IntPoint phase = m_phase;
1125 phase += m_destRect.location() - m_destOrigin;
1129 void RenderBoxModelObject::calculateBackgroundImageGeometry(const FillLayer* fillLayer, const LayoutRect& paintRect,
1130 BackgroundImageGeometry& geometry)
1132 LayoutUnit left = 0;
1134 IntSize positioningAreaSize;
1135 IntRect snappedPaintRect = pixelSnappedIntRect(paintRect);
1137 // Determine the background positioning area and set destRect to the background painting area.
1138 // destRect will be adjusted later if the background is non-repeating.
1139 bool fixedAttachment = fillLayer->attachment() == FixedBackgroundAttachment;
1141 #if ENABLE(FAST_MOBILE_SCROLLING)
1142 if (view()->frameView() && view()->frameView()->canBlitOnScroll()) {
1143 // As a side effect of an optimization to blit on scroll, we do not honor the CSS
1144 // property "background-attachment: fixed" because it may result in rendering
1145 // artifacts. Note, these artifacts only appear if we are blitting on scroll of
1146 // a page that has fixed background images.
1147 fixedAttachment = false;
1151 if (!fixedAttachment) {
1152 geometry.setDestRect(snappedPaintRect);
1154 LayoutUnit right = 0;
1155 LayoutUnit bottom = 0;
1156 // Scroll and Local.
1157 if (fillLayer->origin() != BorderFillBox) {
1158 left = borderLeft();
1159 right = borderRight();
1161 bottom = borderBottom();
1162 if (fillLayer->origin() == ContentFillBox) {
1163 left += paddingLeft();
1164 right += paddingRight();
1165 top += paddingTop();
1166 bottom += paddingBottom();
1170 // The background of the box generated by the root element covers the entire canvas including
1171 // its margins. Since those were added in already, we have to factor them out when computing
1172 // the background positioning area.
1174 positioningAreaSize = pixelSnappedIntSize(toRenderBox(this)->size() - LayoutSize(left + right, top + bottom), toRenderBox(this)->location());
1175 left += marginLeft();
1178 positioningAreaSize = pixelSnappedIntSize(paintRect.size() - LayoutSize(left + right, top + bottom), paintRect.location());
1180 geometry.setDestRect(pixelSnappedIntRect(viewRect()));
1181 positioningAreaSize = geometry.destRect().size();
1184 IntSize fillTileSize = calculateFillTileSize(fillLayer, positioningAreaSize);
1185 fillLayer->image()->setContainerSizeForRenderer(this, fillTileSize, style()->effectiveZoom());
1186 geometry.setTileSize(fillTileSize);
1188 EFillRepeat backgroundRepeatX = fillLayer->repeatX();
1189 EFillRepeat backgroundRepeatY = fillLayer->repeatY();
1190 RenderView* renderView = view();
1192 LayoutUnit xPosition = minimumValueForLength(fillLayer->xPosition(), positioningAreaSize.width() - geometry.tileSize().width(), renderView, true);
1193 if (backgroundRepeatX == RepeatFill)
1194 geometry.setPhaseX(geometry.tileSize().width() ? geometry.tileSize().width() - roundToInt(xPosition + left) % geometry.tileSize().width() : 0);
1196 geometry.setNoRepeatX(xPosition + left);
1198 LayoutUnit yPosition = minimumValueForLength(fillLayer->yPosition(), positioningAreaSize.height() - geometry.tileSize().height(), renderView, true);
1199 if (backgroundRepeatY == RepeatFill)
1200 geometry.setPhaseY(geometry.tileSize().height() ? geometry.tileSize().height() - roundToInt(yPosition + top) % geometry.tileSize().height() : 0);
1202 geometry.setNoRepeatY(yPosition + top);
1204 if (fixedAttachment)
1205 geometry.useFixedAttachment(snappedPaintRect.location());
1207 geometry.clip(snappedPaintRect);
1208 geometry.setDestOrigin(geometry.destRect().location());
1211 static LayoutUnit computeBorderImageSide(Length borderSlice, LayoutUnit borderSide, LayoutUnit imageSide, LayoutUnit boxExtent, RenderView* renderView)
1213 if (borderSlice.isRelative())
1214 return borderSlice.value() * borderSide;
1215 if (borderSlice.isAuto())
1217 return valueForLength(borderSlice, boxExtent, renderView);
1220 bool RenderBoxModelObject::paintNinePieceImage(GraphicsContext* graphicsContext, const LayoutRect& rect, const RenderStyle* style,
1221 const NinePieceImage& ninePieceImage, CompositeOperator op)
1223 StyleImage* styleImage = ninePieceImage.image();
1227 if (!styleImage->isLoaded())
1228 return true; // Never paint a nine-piece image incrementally, but don't paint the fallback borders either.
1230 if (!styleImage->canRender(this, style->effectiveZoom()))
1233 // FIXME: border-image is broken with full page zooming when tiling has to happen, since the tiling function
1234 // doesn't have any understanding of the zoom that is in effect on the tile.
1235 LayoutRect rectWithOutsets = rect;
1236 rectWithOutsets.expand(style->imageOutsets(ninePieceImage));
1237 IntRect borderImageRect = pixelSnappedIntRect(rectWithOutsets);
1239 IntSize imageSize = calculateImageIntrinsicDimensions(styleImage, borderImageRect.size(), DoNotScaleByEffectiveZoom);
1241 // If both values are ‘auto’ then the intrinsic width and/or height of the image should be used, if any.
1242 styleImage->setContainerSizeForRenderer(this, imageSize, style->effectiveZoom());
1244 int imageWidth = imageSize.width();
1245 int imageHeight = imageSize.height();
1246 RenderView* renderView = view();
1248 float imageScaleFactor = styleImage->imageScaleFactor();
1249 int topSlice = min<int>(imageHeight, valueForLength(ninePieceImage.imageSlices().top(), imageHeight, renderView)) * imageScaleFactor;
1250 int rightSlice = min<int>(imageWidth, valueForLength(ninePieceImage.imageSlices().right(), imageWidth, renderView)) * imageScaleFactor;
1251 int bottomSlice = min<int>(imageHeight, valueForLength(ninePieceImage.imageSlices().bottom(), imageHeight, renderView)) * imageScaleFactor;
1252 int leftSlice = min<int>(imageWidth, valueForLength(ninePieceImage.imageSlices().left(), imageWidth, renderView)) * imageScaleFactor;
1254 ENinePieceImageRule hRule = ninePieceImage.horizontalRule();
1255 ENinePieceImageRule vRule = ninePieceImage.verticalRule();
1257 int topWidth = computeBorderImageSide(ninePieceImage.borderSlices().top(), style->borderTopWidth(), topSlice, borderImageRect.height(), renderView);
1258 int rightWidth = computeBorderImageSide(ninePieceImage.borderSlices().right(), style->borderRightWidth(), rightSlice, borderImageRect.width(), renderView);
1259 int bottomWidth = computeBorderImageSide(ninePieceImage.borderSlices().bottom(), style->borderBottomWidth(), bottomSlice, borderImageRect.height(), renderView);
1260 int leftWidth = computeBorderImageSide(ninePieceImage.borderSlices().left(), style->borderLeftWidth(), leftSlice, borderImageRect.width(), renderView);
1262 // Reduce the widths if they're too large.
1263 // The spec says: Given Lwidth as the width of the border image area, Lheight as its height, and Wside as the border image width
1264 // offset for the side, let f = min(Lwidth/(Wleft+Wright), Lheight/(Wtop+Wbottom)). If f < 1, then all W are reduced by
1265 // multiplying them by f.
1266 int borderSideWidth = max(1, leftWidth + rightWidth);
1267 int borderSideHeight = max(1, topWidth + bottomWidth);
1268 float borderSideScaleFactor = min((float)borderImageRect.width() / borderSideWidth, (float)borderImageRect.height() / borderSideHeight);
1269 if (borderSideScaleFactor < 1) {
1270 topWidth *= borderSideScaleFactor;
1271 rightWidth *= borderSideScaleFactor;
1272 bottomWidth *= borderSideScaleFactor;
1273 leftWidth *= borderSideScaleFactor;
1276 bool drawLeft = leftSlice > 0 && leftWidth > 0;
1277 bool drawTop = topSlice > 0 && topWidth > 0;
1278 bool drawRight = rightSlice > 0 && rightWidth > 0;
1279 bool drawBottom = bottomSlice > 0 && bottomWidth > 0;
1280 bool drawMiddle = ninePieceImage.fill() && (imageWidth - leftSlice - rightSlice) > 0 && (borderImageRect.width() - leftWidth - rightWidth) > 0
1281 && (imageHeight - topSlice - bottomSlice) > 0 && (borderImageRect.height() - topWidth - bottomWidth) > 0;
1283 RefPtr<Image> image = styleImage->image(this, imageSize);
1284 ColorSpace colorSpace = style->colorSpace();
1286 float destinationWidth = borderImageRect.width() - leftWidth - rightWidth;
1287 float destinationHeight = borderImageRect.height() - topWidth - bottomWidth;
1289 float sourceWidth = imageWidth - leftSlice - rightSlice;
1290 float sourceHeight = imageHeight - topSlice - bottomSlice;
1292 float leftSideScale = drawLeft ? (float)leftWidth / leftSlice : 1;
1293 float rightSideScale = drawRight ? (float)rightWidth / rightSlice : 1;
1294 float topSideScale = drawTop ? (float)topWidth / topSlice : 1;
1295 float bottomSideScale = drawBottom ? (float)bottomWidth / bottomSlice : 1;
1298 // Paint the top and bottom left corners.
1300 // The top left corner rect is (tx, ty, leftWidth, topWidth)
1301 // The rect to use from within the image is obtained from our slice, and is (0, 0, leftSlice, topSlice)
1303 graphicsContext->drawImage(image.get(), colorSpace, IntRect(borderImageRect.location(), IntSize(leftWidth, topWidth)),
1304 LayoutRect(0, 0, leftSlice, topSlice), op);
1306 // The bottom left corner rect is (tx, ty + h - bottomWidth, leftWidth, bottomWidth)
1307 // The rect to use from within the image is (0, imageHeight - bottomSlice, leftSlice, botomSlice)
1309 graphicsContext->drawImage(image.get(), colorSpace, IntRect(borderImageRect.x(), borderImageRect.maxY() - bottomWidth, leftWidth, bottomWidth),
1310 LayoutRect(0, imageHeight - bottomSlice, leftSlice, bottomSlice), op);
1312 // Paint the left edge.
1313 // Have to scale and tile into the border rect.
1314 if (sourceHeight > 0)
1315 graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(borderImageRect.x(), borderImageRect.y() + topWidth, leftWidth,
1317 IntRect(0, topSlice, leftSlice, sourceHeight),
1318 FloatSize(leftSideScale, leftSideScale), Image::StretchTile, (Image::TileRule)vRule, op);
1322 // Paint the top and bottom right corners
1323 // The top right corner rect is (tx + w - rightWidth, ty, rightWidth, topWidth)
1324 // The rect to use from within the image is obtained from our slice, and is (imageWidth - rightSlice, 0, rightSlice, topSlice)
1326 graphicsContext->drawImage(image.get(), colorSpace, IntRect(borderImageRect.maxX() - rightWidth, borderImageRect.y(), rightWidth, topWidth),
1327 LayoutRect(imageWidth - rightSlice, 0, rightSlice, topSlice), op);
1329 // The bottom right corner rect is (tx + w - rightWidth, ty + h - bottomWidth, rightWidth, bottomWidth)
1330 // The rect to use from within the image is (imageWidth - rightSlice, imageHeight - bottomSlice, rightSlice, bottomSlice)
1332 graphicsContext->drawImage(image.get(), colorSpace, IntRect(borderImageRect.maxX() - rightWidth, borderImageRect.maxY() - bottomWidth, rightWidth, bottomWidth),
1333 LayoutRect(imageWidth - rightSlice, imageHeight - bottomSlice, rightSlice, bottomSlice), op);
1335 // Paint the right edge.
1336 if (sourceHeight > 0)
1337 graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(borderImageRect.maxX() - rightWidth, borderImageRect.y() + topWidth, rightWidth,
1339 IntRect(imageWidth - rightSlice, topSlice, rightSlice, sourceHeight),
1340 FloatSize(rightSideScale, rightSideScale),
1341 Image::StretchTile, (Image::TileRule)vRule, op);
1344 // Paint the top edge.
1345 if (drawTop && sourceWidth > 0)
1346 graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(borderImageRect.x() + leftWidth, borderImageRect.y(), destinationWidth, topWidth),
1347 IntRect(leftSlice, 0, sourceWidth, topSlice),
1348 FloatSize(topSideScale, topSideScale), (Image::TileRule)hRule, Image::StretchTile, op);
1350 // Paint the bottom edge.
1351 if (drawBottom && sourceWidth > 0)
1352 graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(borderImageRect.x() + leftWidth, borderImageRect.maxY() - bottomWidth,
1353 destinationWidth, bottomWidth),
1354 IntRect(leftSlice, imageHeight - bottomSlice, sourceWidth, bottomSlice),
1355 FloatSize(bottomSideScale, bottomSideScale),
1356 (Image::TileRule)hRule, Image::StretchTile, op);
1358 // Paint the middle.
1360 FloatSize middleScaleFactor(1, 1);
1362 middleScaleFactor.setWidth(topSideScale);
1363 else if (drawBottom)
1364 middleScaleFactor.setWidth(bottomSideScale);
1366 middleScaleFactor.setHeight(leftSideScale);
1368 middleScaleFactor.setHeight(rightSideScale);
1370 // For "stretch" rules, just override the scale factor and replace. We only had to do this for the
1371 // center tile, since sides don't even use the scale factor unless they have a rule other than "stretch".
1372 // The middle however can have "stretch" specified in one axis but not the other, so we have to
1373 // correct the scale here.
1374 if (hRule == StretchImageRule)
1375 middleScaleFactor.setWidth(destinationWidth / sourceWidth);
1377 if (vRule == StretchImageRule)
1378 middleScaleFactor.setHeight(destinationHeight / sourceHeight);
1380 graphicsContext->drawTiledImage(image.get(), colorSpace,
1381 IntRect(borderImageRect.x() + leftWidth, borderImageRect.y() + topWidth, destinationWidth, destinationHeight),
1382 IntRect(leftSlice, topSlice, sourceWidth, sourceHeight),
1383 middleScaleFactor, (Image::TileRule)hRule, (Image::TileRule)vRule, op);
1391 BorderEdge(int edgeWidth, const Color& edgeColor, EBorderStyle edgeStyle, bool edgeIsTransparent, bool edgeIsPresent = true)
1395 , isTransparent(edgeIsTransparent)
1396 , isPresent(edgeIsPresent)
1398 if (style == DOUBLE && edgeWidth < 3)
1405 , isTransparent(false)
1410 bool hasVisibleColorAndStyle() const { return style > BHIDDEN && !isTransparent; }
1411 bool shouldRender() const { return isPresent && width && hasVisibleColorAndStyle(); }
1412 bool presentButInvisible() const { return usedWidth() && !hasVisibleColorAndStyle(); }
1413 bool obscuresBackgroundEdge(float scale) const
1415 if (!isPresent || isTransparent || width < (2 * scale) || color.hasAlpha() || style == BHIDDEN)
1418 if (style == DOTTED || style == DASHED)
1421 if (style == DOUBLE)
1422 return width >= 5 * scale; // The outer band needs to be >= 2px wide at unit scale.
1426 bool obscuresBackground() const
1428 if (!isPresent || isTransparent || color.hasAlpha() || style == BHIDDEN)
1431 if (style == DOTTED || style == DASHED || style == DOUBLE)
1437 int usedWidth() const { return isPresent ? width : 0; }
1439 void getDoubleBorderStripeWidths(int& outerWidth, int& innerWidth) const
1441 int fullWidth = usedWidth();
1442 outerWidth = fullWidth / 3;
1443 innerWidth = fullWidth * 2 / 3;
1445 // We need certain integer rounding results
1446 if (fullWidth % 3 == 2)
1449 if (fullWidth % 3 == 1)
1460 static bool allCornersClippedOut(const RoundedRect& border, const LayoutRect& clipRect)
1462 LayoutRect boundingRect = border.rect();
1463 if (clipRect.contains(boundingRect))
1466 RoundedRect::Radii radii = border.radii();
1468 LayoutRect topLeftRect(boundingRect.location(), radii.topLeft());
1469 if (clipRect.intersects(topLeftRect))
1472 LayoutRect topRightRect(boundingRect.location(), radii.topRight());
1473 topRightRect.setX(boundingRect.maxX() - topRightRect.width());
1474 if (clipRect.intersects(topRightRect))
1477 LayoutRect bottomLeftRect(boundingRect.location(), radii.bottomLeft());
1478 bottomLeftRect.setY(boundingRect.maxY() - bottomLeftRect.height());
1479 if (clipRect.intersects(bottomLeftRect))
1482 LayoutRect bottomRightRect(boundingRect.location(), radii.bottomRight());
1483 bottomRightRect.setX(boundingRect.maxX() - bottomRightRect.width());
1484 bottomRightRect.setY(boundingRect.maxY() - bottomRightRect.height());
1485 if (clipRect.intersects(bottomRightRect))
1491 static bool borderWillArcInnerEdge(const LayoutSize& firstRadius, const FloatSize& secondRadius)
1493 return !firstRadius.isZero() || !secondRadius.isZero();
1496 enum BorderEdgeFlag {
1497 TopBorderEdge = 1 << BSTop,
1498 RightBorderEdge = 1 << BSRight,
1499 BottomBorderEdge = 1 << BSBottom,
1500 LeftBorderEdge = 1 << BSLeft,
1501 AllBorderEdges = TopBorderEdge | BottomBorderEdge | LeftBorderEdge | RightBorderEdge
1504 static inline BorderEdgeFlag edgeFlagForSide(BoxSide side)
1506 return static_cast<BorderEdgeFlag>(1 << side);
1509 static inline bool includesEdge(BorderEdgeFlags flags, BoxSide side)
1511 return flags & edgeFlagForSide(side);
1514 static inline bool includesAdjacentEdges(BorderEdgeFlags flags)
1516 return (flags & (TopBorderEdge | RightBorderEdge)) == (TopBorderEdge | RightBorderEdge)
1517 || (flags & (RightBorderEdge | BottomBorderEdge)) == (RightBorderEdge | BottomBorderEdge)
1518 || (flags & (BottomBorderEdge | LeftBorderEdge)) == (BottomBorderEdge | LeftBorderEdge)
1519 || (flags & (LeftBorderEdge | TopBorderEdge)) == (LeftBorderEdge | TopBorderEdge);
1522 inline bool edgesShareColor(const BorderEdge& firstEdge, const BorderEdge& secondEdge)
1524 return firstEdge.color == secondEdge.color;
1527 inline bool styleRequiresClipPolygon(EBorderStyle style)
1529 return style == DOTTED || style == DASHED; // These are drawn with a stroke, so we have to clip to get corner miters.
1532 static bool borderStyleFillsBorderArea(EBorderStyle style)
1534 return !(style == DOTTED || style == DASHED || style == DOUBLE);
1537 static bool borderStyleHasInnerDetail(EBorderStyle style)
1539 return style == GROOVE || style == RIDGE || style == DOUBLE;
1542 static bool borderStyleIsDottedOrDashed(EBorderStyle style)
1544 return style == DOTTED || style == DASHED;
1547 // OUTSET darkens the bottom and right (and maybe lightens the top and left)
1548 // INSET darkens the top and left (and maybe lightens the bottom and right)
1549 static inline bool borderStyleHasUnmatchedColorsAtCorner(EBorderStyle style, BoxSide side, BoxSide adjacentSide)
1551 // These styles match at the top/left and bottom/right.
1552 if (style == INSET || style == GROOVE || style == RIDGE || style == OUTSET) {
1553 const BorderEdgeFlags topRightFlags = edgeFlagForSide(BSTop) | edgeFlagForSide(BSRight);
1554 const BorderEdgeFlags bottomLeftFlags = edgeFlagForSide(BSBottom) | edgeFlagForSide(BSLeft);
1556 BorderEdgeFlags flags = edgeFlagForSide(side) | edgeFlagForSide(adjacentSide);
1557 return flags == topRightFlags || flags == bottomLeftFlags;
1562 static inline bool colorsMatchAtCorner(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1564 if (edges[side].shouldRender() != edges[adjacentSide].shouldRender())
1567 if (!edgesShareColor(edges[side], edges[adjacentSide]))
1570 return !borderStyleHasUnmatchedColorsAtCorner(edges[side].style, side, adjacentSide);
1574 static inline bool colorNeedsAntiAliasAtCorner(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1576 if (!edges[side].color.hasAlpha())
1579 if (edges[side].shouldRender() != edges[adjacentSide].shouldRender())
1582 if (!edgesShareColor(edges[side], edges[adjacentSide]))
1585 return borderStyleHasUnmatchedColorsAtCorner(edges[side].style, side, adjacentSide);
1588 // This assumes that we draw in order: top, bottom, left, right.
1589 static inline bool willBeOverdrawn(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1594 if (edges[adjacentSide].presentButInvisible())
1597 if (!edgesShareColor(edges[side], edges[adjacentSide]) && edges[adjacentSide].color.hasAlpha())
1600 if (!borderStyleFillsBorderArea(edges[adjacentSide].style))
1607 // These draw last, so are never overdrawn.
1613 static inline bool borderStylesRequireMitre(BoxSide side, BoxSide adjacentSide, EBorderStyle style, EBorderStyle adjacentStyle)
1615 if (style == DOUBLE || adjacentStyle == DOUBLE || adjacentStyle == GROOVE || adjacentStyle == RIDGE)
1618 if (borderStyleIsDottedOrDashed(style) != borderStyleIsDottedOrDashed(adjacentStyle))
1621 if (style != adjacentStyle)
1624 return borderStyleHasUnmatchedColorsAtCorner(style, side, adjacentSide);
1627 static bool joinRequiresMitre(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[], bool allowOverdraw)
1629 if ((edges[side].isTransparent && edges[adjacentSide].isTransparent) || !edges[adjacentSide].isPresent)
1632 if (allowOverdraw && willBeOverdrawn(side, adjacentSide, edges))
1635 if (!edgesShareColor(edges[side], edges[adjacentSide]))
1638 if (borderStylesRequireMitre(side, adjacentSide, edges[side].style, edges[adjacentSide].style))
1644 void RenderBoxModelObject::paintOneBorderSide(GraphicsContext* graphicsContext, const RenderStyle* style, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
1645 const IntRect& sideRect, BoxSide side, BoxSide adjacentSide1, BoxSide adjacentSide2, const BorderEdge edges[], const Path* path,
1646 BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias, const Color* overrideColor)
1648 const BorderEdge& edgeToRender = edges[side];
1649 ASSERT(edgeToRender.width);
1650 const BorderEdge& adjacentEdge1 = edges[adjacentSide1];
1651 const BorderEdge& adjacentEdge2 = edges[adjacentSide2];
1653 bool mitreAdjacentSide1 = joinRequiresMitre(side, adjacentSide1, edges, !antialias);
1654 bool mitreAdjacentSide2 = joinRequiresMitre(side, adjacentSide2, edges, !antialias);
1656 bool adjacentSide1StylesMatch = colorsMatchAtCorner(side, adjacentSide1, edges);
1657 bool adjacentSide2StylesMatch = colorsMatchAtCorner(side, adjacentSide2, edges);
1659 const Color& colorToPaint = overrideColor ? *overrideColor : edgeToRender.color;
1662 GraphicsContextStateSaver stateSaver(*graphicsContext);
1663 if (innerBorder.isRenderable())
1664 clipBorderSidePolygon(graphicsContext, outerBorder, innerBorder, side, adjacentSide1StylesMatch, adjacentSide2StylesMatch);
1666 clipBorderSideForComplexInnerPath(graphicsContext, outerBorder, innerBorder, side, edges);
1667 float thickness = max(max(edgeToRender.width, adjacentEdge1.width), adjacentEdge2.width);
1668 drawBoxSideFromPath(graphicsContext, outerBorder.rect(), *path, edges, edgeToRender.width, thickness, side, style,
1669 colorToPaint, edgeToRender.style, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
1671 bool clipForStyle = styleRequiresClipPolygon(edgeToRender.style) && (mitreAdjacentSide1 || mitreAdjacentSide2);
1672 bool clipAdjacentSide1 = colorNeedsAntiAliasAtCorner(side, adjacentSide1, edges) && mitreAdjacentSide1;
1673 bool clipAdjacentSide2 = colorNeedsAntiAliasAtCorner(side, adjacentSide2, edges) && mitreAdjacentSide2;
1674 bool shouldClip = clipForStyle || clipAdjacentSide1 || clipAdjacentSide2;
1676 GraphicsContextStateSaver clipStateSaver(*graphicsContext, shouldClip);
1678 bool aliasAdjacentSide1 = clipAdjacentSide1 || (clipForStyle && mitreAdjacentSide1);
1679 bool aliasAdjacentSide2 = clipAdjacentSide2 || (clipForStyle && mitreAdjacentSide2);
1680 clipBorderSidePolygon(graphicsContext, outerBorder, innerBorder, side, !aliasAdjacentSide1, !aliasAdjacentSide2);
1681 // Since we clipped, no need to draw with a mitre.
1682 mitreAdjacentSide1 = false;
1683 mitreAdjacentSide2 = false;
1686 drawLineForBoxSide(graphicsContext, sideRect.x(), sideRect.y(), sideRect.maxX(), sideRect.maxY(), side, colorToPaint, edgeToRender.style,
1687 mitreAdjacentSide1 ? adjacentEdge1.width : 0, mitreAdjacentSide2 ? adjacentEdge2.width : 0, antialias);
1691 static IntRect calculateSideRect(const RoundedRect& outerBorder, const BorderEdge edges[], int side)
1693 IntRect sideRect = outerBorder.rect();
1694 int width = edges[side].width;
1697 sideRect.setHeight(width);
1698 else if (side == BSBottom)
1699 sideRect.shiftYEdgeTo(sideRect.maxY() - width);
1700 else if (side == BSLeft)
1701 sideRect.setWidth(width);
1703 sideRect.shiftXEdgeTo(sideRect.maxX() - width);
1708 void RenderBoxModelObject::paintBorderSides(GraphicsContext* graphicsContext, const RenderStyle* style, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
1709 const BorderEdge edges[], BorderEdgeFlags edgeSet, BackgroundBleedAvoidance bleedAvoidance,
1710 bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias, const Color* overrideColor)
1712 bool renderRadii = outerBorder.isRounded();
1716 roundedPath.addRoundedRect(outerBorder);
1718 if (edges[BSTop].shouldRender() && includesEdge(edgeSet, BSTop)) {
1719 IntRect sideRect = outerBorder.rect();
1720 sideRect.setHeight(edges[BSTop].width);
1722 bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSTop].style) || borderWillArcInnerEdge(innerBorder.radii().topLeft(), innerBorder.radii().topRight()));
1723 paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSTop, BSLeft, BSRight, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1726 if (edges[BSBottom].shouldRender() && includesEdge(edgeSet, BSBottom)) {
1727 IntRect sideRect = outerBorder.rect();
1728 sideRect.shiftYEdgeTo(sideRect.maxY() - edges[BSBottom].width);
1730 bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSBottom].style) || borderWillArcInnerEdge(innerBorder.radii().bottomLeft(), innerBorder.radii().bottomRight()));
1731 paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSBottom, BSLeft, BSRight, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1734 if (edges[BSLeft].shouldRender() && includesEdge(edgeSet, BSLeft)) {
1735 IntRect sideRect = outerBorder.rect();
1736 sideRect.setWidth(edges[BSLeft].width);
1738 bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSLeft].style) || borderWillArcInnerEdge(innerBorder.radii().bottomLeft(), innerBorder.radii().topLeft()));
1739 paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSLeft, BSTop, BSBottom, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1742 if (edges[BSRight].shouldRender() && includesEdge(edgeSet, BSRight)) {
1743 IntRect sideRect = outerBorder.rect();
1744 sideRect.shiftXEdgeTo(sideRect.maxX() - edges[BSRight].width);
1746 bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSRight].style) || borderWillArcInnerEdge(innerBorder.radii().bottomRight(), innerBorder.radii().topRight()));
1747 paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSRight, BSTop, BSBottom, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1751 void RenderBoxModelObject::paintTranslucentBorderSides(GraphicsContext* graphicsContext, const RenderStyle* style, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
1752 const BorderEdge edges[], BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias)
1754 BorderEdgeFlags edgesToDraw = AllBorderEdges;
1755 while (edgesToDraw) {
1756 // Find undrawn edges sharing a color.
1759 BorderEdgeFlags commonColorEdgeSet = 0;
1760 for (int i = BSTop; i <= BSLeft; ++i) {
1761 BoxSide currSide = static_cast<BoxSide>(i);
1762 if (!includesEdge(edgesToDraw, currSide))
1766 if (!commonColorEdgeSet) {
1767 commonColor = edges[currSide].color;
1770 includeEdge = edges[currSide].color == commonColor;
1773 commonColorEdgeSet |= edgeFlagForSide(currSide);
1776 bool useTransparencyLayer = includesAdjacentEdges(commonColorEdgeSet) && commonColor.hasAlpha();
1777 if (useTransparencyLayer) {
1778 graphicsContext->beginTransparencyLayer(static_cast<float>(commonColor.alpha()) / 255);
1779 commonColor = Color(commonColor.red(), commonColor.green(), commonColor.blue());
1782 paintBorderSides(graphicsContext, style, outerBorder, innerBorder, edges, commonColorEdgeSet, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, &commonColor);
1784 if (useTransparencyLayer)
1785 graphicsContext->endTransparencyLayer();
1787 edgesToDraw &= ~commonColorEdgeSet;
1791 void RenderBoxModelObject::paintBorder(const PaintInfo& info, const LayoutRect& rect, const RenderStyle* style,
1792 BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
1794 GraphicsContext* graphicsContext = info.context;
1795 // border-image is not affected by border-radius.
1796 if (paintNinePieceImage(graphicsContext, rect, style, style->borderImage()))
1799 if (graphicsContext->paintingDisabled())
1802 BorderEdge edges[4];
1803 getBorderEdgeInfo(edges, style, includeLogicalLeftEdge, includeLogicalRightEdge);
1804 RoundedRect outerBorder = style->getRoundedBorderFor(rect, view(), includeLogicalLeftEdge, includeLogicalRightEdge);
1805 RoundedRect innerBorder = style->getRoundedInnerBorderFor(rect, includeLogicalLeftEdge, includeLogicalRightEdge);
1807 bool haveAlphaColor = false;
1808 bool haveAllSolidEdges = true;
1809 bool haveAllDoubleEdges = true;
1810 int numEdgesVisible = 4;
1811 bool allEdgesShareColor = true;
1812 int firstVisibleEdge = -1;
1814 for (int i = BSTop; i <= BSLeft; ++i) {
1815 const BorderEdge& currEdge = edges[i];
1816 if (currEdge.presentButInvisible()) {
1818 allEdgesShareColor = false;
1822 if (!currEdge.width) {
1827 if (firstVisibleEdge == -1)
1828 firstVisibleEdge = i;
1829 else if (currEdge.color != edges[firstVisibleEdge].color)
1830 allEdgesShareColor = false;
1832 if (currEdge.color.hasAlpha())
1833 haveAlphaColor = true;
1835 if (currEdge.style != SOLID)
1836 haveAllSolidEdges = false;
1838 if (currEdge.style != DOUBLE)
1839 haveAllDoubleEdges = false;
1842 //In Cairo port, this check must be removed because a rounded rect border can look different with a rect border because a complex clip handles different with a simple clip
1843 #if !ENABLE(TIZEN_NOT_CHECK_ROUNDED_BORDER_ALL_CLIPPED_OUT)
1844 // If no corner intersects the clip region, we can pretend outerBorder is
1845 // rectangular to improve performance.
1846 if (haveAllSolidEdges && outerBorder.isRounded() && allCornersClippedOut(outerBorder, info.rect))
1847 outerBorder.setRadii(RoundedRect::Radii());
1850 // isRenderable() check avoids issue described in https://bugs.webkit.org/show_bug.cgi?id=38787
1851 if ((haveAllSolidEdges || haveAllDoubleEdges) && allEdgesShareColor && innerBorder.isRenderable()) {
1852 // Fast path for drawing all solid edges and all unrounded double edges
1853 if (numEdgesVisible == 4 && (outerBorder.isRounded() || haveAlphaColor)
1854 && (haveAllSolidEdges || (!outerBorder.isRounded() && !innerBorder.isRounded()))) {
1857 if (outerBorder.isRounded() && bleedAvoidance != BackgroundBleedUseTransparencyLayer)
1858 path.addRoundedRect(outerBorder);
1860 path.addRect(outerBorder.rect());
1862 if (haveAllDoubleEdges) {
1863 IntRect innerThirdRect = outerBorder.rect();
1864 IntRect outerThirdRect = outerBorder.rect();
1865 for (int side = BSTop; side <= BSLeft; ++side) {
1868 edges[side].getDoubleBorderStripeWidths(outerWidth, innerWidth);
1870 if (side == BSTop) {
1871 innerThirdRect.shiftYEdgeTo(innerThirdRect.y() + innerWidth);
1872 outerThirdRect.shiftYEdgeTo(outerThirdRect.y() + outerWidth);
1873 } else if (side == BSBottom) {
1874 innerThirdRect.setHeight(innerThirdRect.height() - innerWidth);
1875 outerThirdRect.setHeight(outerThirdRect.height() - outerWidth);
1876 } else if (side == BSLeft) {
1877 innerThirdRect.shiftXEdgeTo(innerThirdRect.x() + innerWidth);
1878 outerThirdRect.shiftXEdgeTo(outerThirdRect.x() + outerWidth);
1880 innerThirdRect.setWidth(innerThirdRect.width() - innerWidth);
1881 outerThirdRect.setWidth(outerThirdRect.width() - outerWidth);
1885 RoundedRect outerThird = outerBorder;
1886 RoundedRect innerThird = innerBorder;
1887 innerThird.setRect(innerThirdRect);
1888 outerThird.setRect(outerThirdRect);
1890 if (outerThird.isRounded() && bleedAvoidance != BackgroundBleedUseTransparencyLayer)
1891 path.addRoundedRect(outerThird);
1893 path.addRect(outerThird.rect());
1895 if (innerThird.isRounded() && bleedAvoidance != BackgroundBleedUseTransparencyLayer)
1896 path.addRoundedRect(innerThird);
1898 path.addRect(innerThird.rect());
1901 if (innerBorder.isRounded())
1902 path.addRoundedRect(innerBorder);
1904 path.addRect(innerBorder.rect());
1906 graphicsContext->setFillRule(RULE_EVENODD);
1907 graphicsContext->setFillColor(edges[firstVisibleEdge].color, style->colorSpace());
1908 graphicsContext->fillPath(path);
1911 // Avoid creating transparent layers
1912 if (haveAllSolidEdges && numEdgesVisible != 4 && !outerBorder.isRounded() && haveAlphaColor) {
1915 for (int i = BSTop; i <= BSLeft; ++i) {
1916 const BorderEdge& currEdge = edges[i];
1917 if (currEdge.shouldRender()) {
1918 IntRect sideRect = calculateSideRect(outerBorder, edges, i);
1919 path.addRect(sideRect);
1923 graphicsContext->setFillRule(RULE_NONZERO);
1924 graphicsContext->setFillColor(edges[firstVisibleEdge].color, style->colorSpace());
1925 graphicsContext->fillPath(path);
1930 bool clipToOuterBorder = outerBorder.isRounded();
1931 GraphicsContextStateSaver stateSaver(*graphicsContext, clipToOuterBorder);
1932 if (clipToOuterBorder) {
1933 // Clip to the inner and outer radii rects.
1934 if (bleedAvoidance != BackgroundBleedUseTransparencyLayer)
1935 graphicsContext->addRoundedRectClip(outerBorder);
1936 // isRenderable() check avoids issue described in https://bugs.webkit.org/show_bug.cgi?id=38787
1937 // The inside will be clipped out later (in clipBorderSideForComplexInnerPath)
1938 if (innerBorder.isRenderable())
1939 graphicsContext->clipOutRoundedRect(innerBorder);
1942 // If only one edge visible antialiasing doesn't create seams
1943 bool antialias = shouldAntialiasLines(graphicsContext) || numEdgesVisible == 1;
1945 paintTranslucentBorderSides(graphicsContext, style, outerBorder, innerBorder, edges, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias);
1947 paintBorderSides(graphicsContext, style, outerBorder, innerBorder, edges, AllBorderEdges, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias);
1950 void RenderBoxModelObject::drawBoxSideFromPath(GraphicsContext* graphicsContext, const LayoutRect& borderRect, const Path& borderPath, const BorderEdge edges[],
1951 float thickness, float drawThickness, BoxSide side, const RenderStyle* style,
1952 Color color, EBorderStyle borderStyle, BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
1957 if (borderStyle == DOUBLE && thickness < 3)
1958 borderStyle = SOLID;
1960 switch (borderStyle) {
1966 graphicsContext->setStrokeColor(color, style->colorSpace());
1968 // The stroke is doubled here because the provided path is the
1969 // outside edge of the border so half the stroke is clipped off.
1970 // The extra multiplier is so that the clipping mask can antialias
1971 // the edges to prevent jaggies.
1972 graphicsContext->setStrokeThickness(drawThickness * 2 * 1.1f);
1973 graphicsContext->setStrokeStyle(borderStyle == DASHED ? DashedStroke : DottedStroke);
1975 // If the number of dashes that fit in the path is odd and non-integral then we
1976 // will have an awkwardly-sized dash at the end of the path. To try to avoid that
1977 // here, we simply make the whitespace dashes ever so slightly bigger.
1978 // FIXME: This could be even better if we tried to manipulate the dash offset
1979 // and possibly the gapLength to get the corners dash-symmetrical.
1980 float dashLength = thickness * ((borderStyle == DASHED) ? 3.0f : 1.0f);
1981 float gapLength = dashLength;
1982 float numberOfDashes = borderPath.length() / dashLength;
1983 // Don't try to show dashes if we have less than 2 dashes + 2 gaps.
1984 // FIXME: should do this test per side.
1985 if (numberOfDashes >= 4) {
1986 bool evenNumberOfFullDashes = !((int)numberOfDashes % 2);
1987 bool integralNumberOfDashes = !(numberOfDashes - (int)numberOfDashes);
1988 if (!evenNumberOfFullDashes && !integralNumberOfDashes) {
1989 float numberOfGaps = numberOfDashes / 2;
1990 gapLength += (dashLength / numberOfGaps);
1994 lineDash.append(dashLength);
1995 lineDash.append(gapLength);
1996 graphicsContext->setLineDash(lineDash, dashLength);
1999 // FIXME: stroking the border path causes issues with tight corners:
2000 // https://bugs.webkit.org/show_bug.cgi?id=58711
2001 // Also, to get the best appearance we should stroke a path between the two borders.
2002 graphicsContext->strokePath(borderPath);
2006 // Get the inner border rects for both the outer border line and the inner border line
2007 int outerBorderTopWidth;
2008 int innerBorderTopWidth;
2009 edges[BSTop].getDoubleBorderStripeWidths(outerBorderTopWidth, innerBorderTopWidth);
2011 int outerBorderRightWidth;
2012 int innerBorderRightWidth;
2013 edges[BSRight].getDoubleBorderStripeWidths(outerBorderRightWidth, innerBorderRightWidth);
2015 int outerBorderBottomWidth;
2016 int innerBorderBottomWidth;
2017 edges[BSBottom].getDoubleBorderStripeWidths(outerBorderBottomWidth, innerBorderBottomWidth);
2019 int outerBorderLeftWidth;
2020 int innerBorderLeftWidth;
2021 edges[BSLeft].getDoubleBorderStripeWidths(outerBorderLeftWidth, innerBorderLeftWidth);
2023 // Draw inner border line
2025 GraphicsContextStateSaver stateSaver(*graphicsContext);
2026 RoundedRect innerClip = style->getRoundedInnerBorderFor(borderRect,
2027 innerBorderTopWidth, innerBorderBottomWidth, innerBorderLeftWidth, innerBorderRightWidth,
2028 includeLogicalLeftEdge, includeLogicalRightEdge);
2030 graphicsContext->addRoundedRectClip(innerClip);
2031 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, SOLID, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
2034 // Draw outer border line
2036 GraphicsContextStateSaver stateSaver(*graphicsContext);
2037 LayoutRect outerRect = borderRect;
2038 if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
2039 outerRect.inflate(1);
2040 ++outerBorderTopWidth;
2041 ++outerBorderBottomWidth;
2042 ++outerBorderLeftWidth;
2043 ++outerBorderRightWidth;
2046 RoundedRect outerClip = style->getRoundedInnerBorderFor(outerRect,
2047 outerBorderTopWidth, outerBorderBottomWidth, outerBorderLeftWidth, outerBorderRightWidth,
2048 includeLogicalLeftEdge, includeLogicalRightEdge);
2049 graphicsContext->clipOutRoundedRect(outerClip);
2050 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, SOLID, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
2059 if (borderStyle == GROOVE) {
2067 // Paint full border
2068 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, s1, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
2071 GraphicsContextStateSaver stateSaver(*graphicsContext);
2072 LayoutUnit topWidth = edges[BSTop].usedWidth() / 2;
2073 LayoutUnit bottomWidth = edges[BSBottom].usedWidth() / 2;
2074 LayoutUnit leftWidth = edges[BSLeft].usedWidth() / 2;
2075 LayoutUnit rightWidth = edges[BSRight].usedWidth() / 2;
2077 RoundedRect clipRect = style->getRoundedInnerBorderFor(borderRect,
2078 topWidth, bottomWidth, leftWidth, rightWidth,
2079 includeLogicalLeftEdge, includeLogicalRightEdge);
2081 graphicsContext->addRoundedRectClip(clipRect);
2082 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, s2, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
2086 if (side == BSTop || side == BSLeft)
2087 color = color.dark();
2090 if (side == BSBottom || side == BSRight)
2091 color = color.dark();
2097 graphicsContext->setStrokeStyle(NoStroke);
2098 graphicsContext->setFillColor(color, style->colorSpace());
2099 graphicsContext->drawRect(pixelSnappedIntRect(borderRect));
2102 static void findInnerVertex(const FloatPoint& outerCorner, const FloatPoint& innerCorner, const FloatPoint& centerPoint, FloatPoint& result)
2104 // If the line between outer and inner corner is towards the horizontal, intersect with a vertical line through the center,
2105 // otherwise with a horizontal line through the center. The points that form this line are arbitrary (we use 0, 100).
2106 // Note that if findIntersection fails, it will leave result untouched.
2107 float diffInnerOuterX = fabs(innerCorner.x() - outerCorner.x());
2108 float diffInnerOuterY = fabs(innerCorner.y() - outerCorner.y());
2109 float diffCenterOuterX = fabs(centerPoint.x() - outerCorner.x());
2110 float diffCenterOuterY = fabs(centerPoint.y() - outerCorner.y());
2111 if (diffInnerOuterY * diffCenterOuterX < diffCenterOuterY * diffInnerOuterX)
2112 findIntersection(outerCorner, innerCorner, FloatPoint(centerPoint.x(), 0), FloatPoint(centerPoint.x(), 100), result);
2114 findIntersection(outerCorner, innerCorner, FloatPoint(0, centerPoint.y()), FloatPoint(100, centerPoint.y()), result);
2117 void RenderBoxModelObject::clipBorderSidePolygon(GraphicsContext* graphicsContext, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
2118 BoxSide side, bool firstEdgeMatches, bool secondEdgeMatches)
2122 const LayoutRect& outerRect = outerBorder.rect();
2123 const LayoutRect& innerRect = innerBorder.rect();
2125 FloatPoint centerPoint(innerRect.location().x() + static_cast<float>(innerRect.width()) / 2, innerRect.location().y() + static_cast<float>(innerRect.height()) / 2);
2127 // For each side, create a quad that encompasses all parts of that side that may draw,
2128 // including areas inside the innerBorder.
2130 // 0----------------3
2132 // |\ 1----------- 2 /|
2137 // |/ 1------------2 \|
2139 // 0----------------3
2143 quad[0] = outerRect.minXMinYCorner();
2144 quad[1] = innerRect.minXMinYCorner();
2145 quad[2] = innerRect.maxXMinYCorner();
2146 quad[3] = outerRect.maxXMinYCorner();
2148 if (!innerBorder.radii().topLeft().isZero())
2149 findInnerVertex(outerRect.minXMinYCorner(), innerRect.minXMinYCorner(), centerPoint, quad[1]);
2151 if (!innerBorder.radii().topRight().isZero())
2152 findInnerVertex(outerRect.maxXMinYCorner(), innerRect.maxXMinYCorner(), centerPoint, quad[2]);
2156 quad[0] = outerRect.minXMinYCorner();
2157 quad[1] = innerRect.minXMinYCorner();
2158 quad[2] = innerRect.minXMaxYCorner();
2159 quad[3] = outerRect.minXMaxYCorner();
2161 if (!innerBorder.radii().topLeft().isZero())
2162 findInnerVertex(outerRect.minXMinYCorner(), innerRect.minXMinYCorner(), centerPoint, quad[1]);
2164 if (!innerBorder.radii().bottomLeft().isZero())
2165 findInnerVertex(outerRect.minXMaxYCorner(), innerRect.minXMaxYCorner(), centerPoint, quad[2]);
2169 quad[0] = outerRect.minXMaxYCorner();
2170 quad[1] = innerRect.minXMaxYCorner();
2171 quad[2] = innerRect.maxXMaxYCorner();
2172 quad[3] = outerRect.maxXMaxYCorner();
2174 if (!innerBorder.radii().bottomLeft().isZero())
2175 findInnerVertex(outerRect.minXMaxYCorner(), innerRect.minXMaxYCorner(), centerPoint, quad[1]);
2177 if (!innerBorder.radii().bottomRight().isZero())
2178 findInnerVertex(outerRect.maxXMaxYCorner(), innerRect.maxXMaxYCorner(), centerPoint, quad[2]);
2182 quad[0] = outerRect.maxXMinYCorner();
2183 quad[1] = innerRect.maxXMinYCorner();
2184 quad[2] = innerRect.maxXMaxYCorner();
2185 quad[3] = outerRect.maxXMaxYCorner();
2187 if (!innerBorder.radii().topRight().isZero())
2188 findInnerVertex(outerRect.maxXMinYCorner(), innerRect.maxXMinYCorner(), centerPoint, quad[1]);
2190 if (!innerBorder.radii().bottomRight().isZero())
2191 findInnerVertex(outerRect.maxXMaxYCorner(), innerRect.maxXMaxYCorner(), centerPoint, quad[2]);
2195 // The antialias setting for rounded rects border must be ON because rounded rects painted with antialias on
2196 #if ENABLE(TIZEN_ROUNDED_BORDER_CLIP_ANTIALIAS_ON)
2197 if (outerBorder.isRounded()) {
2198 graphicsContext->clipConvexPolygon(4, quad, true);
2203 // If the border matches both of its adjacent sides, don't anti-alias the clip, and
2204 // if neither side matches, anti-alias the clip.
2205 if (firstEdgeMatches == secondEdgeMatches) {
2206 graphicsContext->clipConvexPolygon(4, quad, !firstEdgeMatches);
2210 // Square off the end which shouldn't be affected by antialiasing, and clip.
2211 FloatPoint firstQuad[4];
2212 firstQuad[0] = quad[0];
2213 firstQuad[1] = quad[1];
2214 firstQuad[2] = side == BSTop || side == BSBottom ? FloatPoint(quad[3].x(), quad[2].y())
2215 : FloatPoint(quad[2].x(), quad[3].y());
2216 firstQuad[3] = quad[3];
2217 graphicsContext->clipConvexPolygon(4, firstQuad, !firstEdgeMatches);
2219 FloatPoint secondQuad[4];
2220 secondQuad[0] = quad[0];
2221 secondQuad[1] = side == BSTop || side == BSBottom ? FloatPoint(quad[0].x(), quad[1].y())
2222 : FloatPoint(quad[1].x(), quad[0].y());
2223 secondQuad[2] = quad[2];
2224 secondQuad[3] = quad[3];
2225 // Antialiasing affects the second side.
2226 graphicsContext->clipConvexPolygon(4, secondQuad, !secondEdgeMatches);
2229 static IntRect calculateSideRectIncludingInner(const RoundedRect& outerBorder, const BorderEdge edges[], BoxSide side)
2231 IntRect sideRect = outerBorder.rect();
2236 width = sideRect.height() - edges[BSBottom].width;
2237 sideRect.setHeight(width);
2240 width = sideRect.height() - edges[BSTop].width;
2241 sideRect.shiftYEdgeTo(sideRect.maxY() - width);
2244 width = sideRect.width() - edges[BSRight].width;
2245 sideRect.setWidth(width);
2248 width = sideRect.width() - edges[BSLeft].width;
2249 sideRect.shiftXEdgeTo(sideRect.maxX() - width);
2256 static RoundedRect calculateAdjustedInnerBorder(const RoundedRect&innerBorder, BoxSide side)
2258 // Expand the inner border as necessary to make it a rounded rect (i.e. radii contained within each edge).
2259 // This function relies on the fact we only get radii not contained within each edge if one of the radii
2260 // for an edge is zero, so we can shift the arc towards the zero radius corner.
2261 RoundedRect::Radii newRadii = innerBorder.radii();
2262 IntRect newRect = innerBorder.rect();
2269 overshoot = newRadii.topLeft().width() + newRadii.topRight().width() - newRect.width();
2270 if (overshoot > 0) {
2271 ASSERT(!(newRadii.topLeft().width() && newRadii.topRight().width()));
2272 newRect.setWidth(newRect.width() + overshoot);
2273 if (!newRadii.topLeft().width())
2274 newRect.move(-overshoot, 0);
2276 newRadii.setBottomLeft(IntSize(0, 0));
2277 newRadii.setBottomRight(IntSize(0, 0));
2278 maxRadii = max(newRadii.topLeft().height(), newRadii.topRight().height());
2279 if (maxRadii > newRect.height())
2280 newRect.setHeight(maxRadii);
2284 overshoot = newRadii.bottomLeft().width() + newRadii.bottomRight().width() - newRect.width();
2285 if (overshoot > 0) {
2286 ASSERT(!(newRadii.bottomLeft().width() && newRadii.bottomRight().width()));
2287 newRect.setWidth(newRect.width() + overshoot);
2288 if (!newRadii.bottomLeft().width())
2289 newRect.move(-overshoot, 0);
2291 newRadii.setTopLeft(IntSize(0, 0));
2292 newRadii.setTopRight(IntSize(0, 0));
2293 maxRadii = max(newRadii.bottomLeft().height(), newRadii.bottomRight().height());
2294 if (maxRadii > newRect.height()) {
2295 newRect.move(0, newRect.height() - maxRadii);
2296 newRect.setHeight(maxRadii);
2301 overshoot = newRadii.topLeft().height() + newRadii.bottomLeft().height() - newRect.height();
2302 if (overshoot > 0) {
2303 ASSERT(!(newRadii.topLeft().height() && newRadii.bottomLeft().height()));
2304 newRect.setHeight(newRect.height() + overshoot);
2305 if (!newRadii.topLeft().height())
2306 newRect.move(0, -overshoot);
2308 newRadii.setTopRight(IntSize(0, 0));
2309 newRadii.setBottomRight(IntSize(0, 0));
2310 maxRadii = max(newRadii.topLeft().width(), newRadii.bottomLeft().width());
2311 if (maxRadii > newRect.width())
2312 newRect.setWidth(maxRadii);
2316 overshoot = newRadii.topRight().height() + newRadii.bottomRight().height() - newRect.height();
2317 if (overshoot > 0) {
2318 ASSERT(!(newRadii.topRight().height() && newRadii.bottomRight().height()));
2319 newRect.setHeight(newRect.height() + overshoot);
2320 if (!newRadii.topRight().height())
2321 newRect.move(0, -overshoot);
2323 newRadii.setTopLeft(IntSize(0, 0));
2324 newRadii.setBottomLeft(IntSize(0, 0));
2325 maxRadii = max(newRadii.topRight().width(), newRadii.bottomRight().width());
2326 if (maxRadii > newRect.width()) {
2327 newRect.move(newRect.width() - maxRadii, 0);
2328 newRect.setWidth(maxRadii);
2333 return RoundedRect(newRect, newRadii);
2336 void RenderBoxModelObject::clipBorderSideForComplexInnerPath(GraphicsContext* graphicsContext, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
2337 BoxSide side, const class BorderEdge edges[])
2339 graphicsContext->clip(calculateSideRectIncludingInner(outerBorder, edges, side));
2340 graphicsContext->clipOutRoundedRect(calculateAdjustedInnerBorder(innerBorder, side));
2343 void RenderBoxModelObject::getBorderEdgeInfo(BorderEdge edges[], const RenderStyle* style, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
2345 bool horizontal = style->isHorizontalWritingMode();
2347 edges[BSTop] = BorderEdge(style->borderTopWidth(),
2348 style->visitedDependentColor(CSSPropertyBorderTopColor),
2349 style->borderTopStyle(),
2350 style->borderTopIsTransparent(),
2351 horizontal || includeLogicalLeftEdge);
2353 edges[BSRight] = BorderEdge(style->borderRightWidth(),
2354 style->visitedDependentColor(CSSPropertyBorderRightColor),
2355 style->borderRightStyle(),
2356 style->borderRightIsTransparent(),
2357 !horizontal || includeLogicalRightEdge);
2359 edges[BSBottom] = BorderEdge(style->borderBottomWidth(),
2360 style->visitedDependentColor(CSSPropertyBorderBottomColor),
2361 style->borderBottomStyle(),
2362 style->borderBottomIsTransparent(),
2363 horizontal || includeLogicalRightEdge);
2365 edges[BSLeft] = BorderEdge(style->borderLeftWidth(),
2366 style->visitedDependentColor(CSSPropertyBorderLeftColor),
2367 style->borderLeftStyle(),
2368 style->borderLeftIsTransparent(),
2369 !horizontal || includeLogicalLeftEdge);
2372 bool RenderBoxModelObject::borderObscuresBackgroundEdge(const FloatSize& contextScale) const
2374 BorderEdge edges[4];
2375 getBorderEdgeInfo(edges, style());
2377 for (int i = BSTop; i <= BSLeft; ++i) {
2378 const BorderEdge& currEdge = edges[i];
2379 // FIXME: for vertical text
2380 float axisScale = (i == BSTop || i == BSBottom) ? contextScale.height() : contextScale.width();
2381 if (!currEdge.obscuresBackgroundEdge(axisScale))
2388 bool RenderBoxModelObject::borderObscuresBackground() const
2390 if (!style()->hasBorder())
2393 // Bail if we have any border-image for now. We could look at the image alpha to improve this.
2394 if (style()->borderImage().image())
2397 BorderEdge edges[4];
2398 getBorderEdgeInfo(edges, style());
2400 for (int i = BSTop; i <= BSLeft; ++i) {
2401 const BorderEdge& currEdge = edges[i];
2402 if (!currEdge.obscuresBackground())
2409 bool RenderBoxModelObject::boxShadowShouldBeAppliedToBackground(BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* inlineFlowBox) const
2411 if (bleedAvoidance != BackgroundBleedNone)
2414 if (style()->hasAppearance())
2417 bool hasOneNormalBoxShadow = false;
2418 for (const ShadowData* currentShadow = style()->boxShadow(); currentShadow; currentShadow = currentShadow->next()) {
2419 if (currentShadow->style() != Normal)
2422 if (hasOneNormalBoxShadow)
2424 hasOneNormalBoxShadow = true;
2426 if (currentShadow->spread())
2430 if (!hasOneNormalBoxShadow)
2433 Color backgroundColor = style()->visitedDependentColor(CSSPropertyBackgroundColor);
2434 if (!backgroundColor.isValid() || backgroundColor.alpha() < 255)
2437 const FillLayer* lastBackgroundLayer = style()->backgroundLayers();
2438 for (const FillLayer* next = lastBackgroundLayer->next(); next; next = lastBackgroundLayer->next())
2439 lastBackgroundLayer = next;
2441 if (lastBackgroundLayer->clip() != BorderFillBox)
2444 if (lastBackgroundLayer->image() && style()->hasBorderRadius())
2447 if (inlineFlowBox && !inlineFlowBox->boxShadowCanBeAppliedToBackground(*lastBackgroundLayer))
2450 if (hasOverflowClip() && lastBackgroundLayer->attachment() == LocalBackgroundAttachment)
2456 static inline IntRect areaCastingShadowInHole(const IntRect& holeRect, int shadowBlur, int shadowSpread, const IntSize& shadowOffset)
2458 IntRect bounds(holeRect);
2460 bounds.inflate(shadowBlur);
2462 if (shadowSpread < 0)
2463 bounds.inflate(-shadowSpread);
2465 IntRect offsetBounds = bounds;
2466 offsetBounds.move(-shadowOffset);
2467 return unionRect(bounds, offsetBounds);
2470 void RenderBoxModelObject::paintBoxShadow(const PaintInfo& info, const LayoutRect& paintRect, const RenderStyle* s, ShadowStyle shadowStyle, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
2472 // FIXME: Deal with border-image. Would be great to use border-image as a mask.
2473 GraphicsContext* context = info.context;
2474 if (context->paintingDisabled() || !s->boxShadow())
2477 RoundedRect border = (shadowStyle == Inset) ? s->getRoundedInnerBorderFor(paintRect, includeLogicalLeftEdge, includeLogicalRightEdge)
2478 : s->getRoundedBorderFor(paintRect, view(), includeLogicalLeftEdge, includeLogicalRightEdge);
2480 bool hasBorderRadius = s->hasBorderRadius();
2481 bool isHorizontal = s->isHorizontalWritingMode();
2483 bool hasOpaqueBackground = s->visitedDependentColor(CSSPropertyBackgroundColor).isValid() && s->visitedDependentColor(CSSPropertyBackgroundColor).alpha() == 255;
2484 for (const ShadowData* shadow = s->boxShadow(); shadow; shadow = shadow->next()) {
2485 if (shadow->style() != shadowStyle)
2488 IntSize shadowOffset(shadow->x(), shadow->y());
2489 int shadowBlur = shadow->blur();
2490 int shadowSpread = shadow->spread();
2492 if (shadowOffset.isZero() && !shadowBlur && !shadowSpread)
2495 const Color& shadowColor = shadow->color();
2497 if (shadow->style() == Normal) {
2498 RoundedRect fillRect = border;
2499 fillRect.inflate(shadowSpread);
2500 if (fillRect.isEmpty())
2503 IntRect shadowRect(border.rect());
2504 shadowRect.inflate(shadowBlur + shadowSpread);
2505 shadowRect.move(shadowOffset);
2507 GraphicsContextStateSaver stateSaver(*context);
2508 context->clip(shadowRect);
2510 // Move the fill just outside the clip, adding 1 pixel separation so that the fill does not
2511 // bleed in (due to antialiasing) if the context is transformed.
2512 IntSize extraOffset(paintRect.pixelSnappedWidth() + max(0, shadowOffset.width()) + shadowBlur + 2 * shadowSpread + 1, 0);
2513 shadowOffset -= extraOffset;
2514 fillRect.move(extraOffset);
2516 if (shadow->isWebkitBoxShadow())
2517 context->setLegacyShadow(shadowOffset, shadowBlur, shadowColor, s->colorSpace());
2519 context->setShadow(shadowOffset, shadowBlur, shadowColor, s->colorSpace());
2521 if (hasBorderRadius) {
2522 RoundedRect rectToClipOut = border;
2524 // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
2525 // when painting the shadow. On the other hand, it introduces subpixel gaps along the
2526 // corners. Those are avoided by insetting the clipping path by one pixel.
2527 if (hasOpaqueBackground) {
2528 rectToClipOut.inflateWithRadii(-1);
2531 if (!rectToClipOut.isEmpty())
2532 context->clipOutRoundedRect(rectToClipOut);
2534 RoundedRect influenceRect(shadowRect, border.radii());
2535 influenceRect.expandRadii(2 * shadowBlur + shadowSpread);
2536 if (allCornersClippedOut(influenceRect, info.rect))
2537 context->fillRect(fillRect.rect(), Color::black, s->colorSpace());
2539 fillRect.expandRadii(shadowSpread);
2540 context->fillRoundedRect(fillRect, Color::black, s->colorSpace());
2543 IntRect rectToClipOut = border.rect();
2545 // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
2546 // when painting the shadow. On the other hand, it introduces subpixel gaps along the
2547 // edges if they are not pixel-aligned. Those are avoided by insetting the clipping path
2549 if (hasOpaqueBackground) {
2550 // FIXME: The function to decide on the policy based on the transform should be a named function.
2551 // FIXME: It's not clear if this check is right. What about integral scale factors?
2552 AffineTransform transform = context->getCTM();
2553 if (transform.a() != 1 || (transform.d() != 1 && transform.d() != -1) || transform.b() || transform.c())
2554 rectToClipOut.inflate(-1);
2557 if (!rectToClipOut.isEmpty())
2558 context->clipOut(rectToClipOut);
2559 context->fillRect(fillRect.rect(), Color::black, s->colorSpace());
2563 IntRect holeRect(border.rect());
2564 holeRect.inflate(-shadowSpread);
2566 if (holeRect.isEmpty()) {
2567 if (hasBorderRadius)
2568 context->fillRoundedRect(border, shadowColor, s->colorSpace());
2570 context->fillRect(border.rect(), shadowColor, s->colorSpace());
2574 if (!includeLogicalLeftEdge) {
2576 holeRect.move(-max(shadowOffset.width(), 0) - shadowBlur, 0);
2577 holeRect.setWidth(holeRect.width() + max(shadowOffset.width(), 0) + shadowBlur);
2579 holeRect.move(0, -max(shadowOffset.height(), 0) - shadowBlur);
2580 holeRect.setHeight(holeRect.height() + max(shadowOffset.height(), 0) + shadowBlur);
2583 if (!includeLogicalRightEdge) {
2585 holeRect.setWidth(holeRect.width() - min(shadowOffset.width(), 0) + shadowBlur);
2587 holeRect.setHeight(holeRect.height() - min(shadowOffset.height(), 0) + shadowBlur);
2590 Color fillColor(shadowColor.red(), shadowColor.green(), shadowColor.blue(), 255);
2592 IntRect outerRect = areaCastingShadowInHole(border.rect(), shadowBlur, shadowSpread, shadowOffset);
2593 RoundedRect roundedHole(holeRect, border.radii());
2595 GraphicsContextStateSaver stateSaver(*context);
2596 if (hasBorderRadius) {
2598 path.addRoundedRect(border);
2599 context->clip(path);
2600 roundedHole.shrinkRadii(shadowSpread);
2602 context->clip(border.rect());
2604 IntSize extraOffset(2 * paintRect.pixelSnappedWidth() + max(0, shadowOffset.width()) + shadowBlur - 2 * shadowSpread + 1, 0);
2605 context->translate(extraOffset.width(), extraOffset.height());
2606 shadowOffset -= extraOffset;
2608 if (shadow->isWebkitBoxShadow())
2609 context->setLegacyShadow(shadowOffset, shadowBlur, shadowColor, s->colorSpace());
2611 context->setShadow(shadowOffset, shadowBlur, shadowColor, s->colorSpace());
2613 context->fillRectWithRoundedHole(outerRect, roundedHole, fillColor, s->colorSpace());
2618 LayoutUnit RenderBoxModelObject::containingBlockLogicalWidthForContent() const
2620 return containingBlock()->availableLogicalWidth();
2623 RenderBoxModelObject* RenderBoxModelObject::continuation() const
2625 if (!continuationMap)
2627 return continuationMap->get(this);
2630 void RenderBoxModelObject::setContinuation(RenderBoxModelObject* continuation)
2633 if (!continuationMap)
2634 continuationMap = new ContinuationMap;
2635 continuationMap->set(this, continuation);
2637 if (continuationMap)
2638 continuationMap->remove(this);
2642 RenderObject* RenderBoxModelObject::firstLetterRemainingText() const
2644 if (!firstLetterRemainingTextMap)
2646 return firstLetterRemainingTextMap->get(this);
2649 void RenderBoxModelObject::setFirstLetterRemainingText(RenderObject* remainingText)
2651 if (remainingText) {
2652 if (!firstLetterRemainingTextMap)
2653 firstLetterRemainingTextMap = new FirstLetterRemainingTextMap;
2654 firstLetterRemainingTextMap->set(this, remainingText);
2655 } else if (firstLetterRemainingTextMap)
2656 firstLetterRemainingTextMap->remove(this);
2659 LayoutRect RenderBoxModelObject::localCaretRectForEmptyElement(LayoutUnit width, LayoutUnit textIndentOffset)
2661 ASSERT(!firstChild());
2663 // FIXME: This does not take into account either :first-line or :first-letter
2664 // However, as soon as some content is entered, the line boxes will be
2665 // constructed and this kludge is not called any more. So only the caret size
2666 // of an empty :first-line'd block is wrong. I think we can live with that.
2667 RenderStyle* currentStyle = firstLineStyle();
2668 LayoutUnit height = lineHeight(true, currentStyle->isHorizontalWritingMode() ? HorizontalLine : VerticalLine);
2670 enum CaretAlignment { alignLeft, alignRight, alignCenter };
2672 CaretAlignment alignment = alignLeft;
2674 switch (currentStyle->textAlign()) {
2680 alignment = alignCenter;
2684 alignment = alignRight;
2688 if (!currentStyle->isLeftToRightDirection())
2689 alignment = alignRight;
2692 if (currentStyle->isLeftToRightDirection())
2693 alignment = alignRight;
2697 LayoutUnit x = borderLeft() + paddingLeft();
2698 LayoutUnit maxX = width - borderRight() - paddingRight();
2700 switch (alignment) {
2702 if (currentStyle->isLeftToRightDirection())
2703 x += textIndentOffset;
2707 if (currentStyle->isLeftToRightDirection())
2708 x += textIndentOffset / 2;
2710 x -= textIndentOffset / 2;
2713 x = maxX - caretWidth;
2714 if (!currentStyle->isLeftToRightDirection())
2715 x -= textIndentOffset;
2718 x = min(x, max(maxX - caretWidth, ZERO_LAYOUT_UNIT));
2720 LayoutUnit y = paddingTop() + borderTop();
2722 return LayoutRect(x, y, caretWidth, height);
2725 bool RenderBoxModelObject::shouldAntialiasLines(GraphicsContext* context)
2727 #if ENABLE(TIZEN_FIX_SHOULD_AA_LINES_CONDITION)
2728 return !context->getCTM().isIdentityOrTranslationOrFlipped() || !context->getCTM().isIntegerTranslation() || !context->getCTM().isScaledByIntegerValue();
2730 return !context->getCTM().isIdentityOrTranslationOrFlipped();
2734 void RenderBoxModelObject::mapAbsoluteToLocalPoint(bool fixed, bool useTransforms, TransformState& transformState) const
2736 // We don't expect absoluteToLocal() to be called during layout (yet)
2737 ASSERT(!view() || !view()->layoutStateEnabled());
2739 RenderObject* o = container();
2743 o->mapAbsoluteToLocalPoint(fixed, useTransforms, transformState);
2745 LayoutSize containerOffset = offsetFromContainer(o, LayoutPoint());
2747 if (!style()->isOutOfFlowPositioned() && o->hasColumns()) {
2748 RenderBlock* block = static_cast<RenderBlock*>(o);
2749 LayoutPoint point(roundedLayoutPoint(transformState.mappedPoint()));
2750 point -= containerOffset;
2751 block->adjustForColumnRect(containerOffset, point);
2754 bool preserve3D = useTransforms && (o->style()->preserves3D() || style()->preserves3D());
2755 if (useTransforms && shouldUseTransformFromContainer(o)) {
2756 TransformationMatrix t;
2757 getTransformFromContainer(o, containerOffset, t);
2758 transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
2760 transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
2763 void RenderBoxModelObject::moveChildTo(RenderBoxModelObject* toBoxModelObject, RenderObject* child, RenderObject* beforeChild, bool fullRemoveInsert)
2765 // FIXME: We need a performant way to handle clearing positioned objects from our list that are
2766 // in |child|'s subtree so we could just clear them here. Because of this, we assume that callers
2767 // have cleared their positioned objects list for child moves (!fullRemoveInsert) to avoid any badness.
2768 ASSERT(!fullRemoveInsert || !isRenderBlock() || !toRenderBlock(this)->hasPositionedObjects());
2770 ASSERT(this == child->parent());
2771 ASSERT(!beforeChild || toBoxModelObject == beforeChild->parent());
2772 if (fullRemoveInsert && (toBoxModelObject->isRenderBlock() || toBoxModelObject->isRenderInline())) {
2773 // Takes care of adding the new child correctly if toBlock and fromBlock
2774 // have different kind of children (block vs inline).
2775 toBoxModelObject->addChild(virtualChildren()->removeChildNode(this, child), beforeChild);
2777 toBoxModelObject->virtualChildren()->insertChildNode(toBoxModelObject, virtualChildren()->removeChildNode(this, child, fullRemoveInsert), beforeChild, fullRemoveInsert);
2780 void RenderBoxModelObject::moveChildrenTo(RenderBoxModelObject* toBoxModelObject, RenderObject* startChild, RenderObject* endChild, RenderObject* beforeChild, bool fullRemoveInsert)
2782 // This condition is rarely hit since this function is usually called on
2783 // anonymous blocks which can no longer carry positioned objects (see r120761)
2784 // or when fullRemoveInsert is false.
2785 if (fullRemoveInsert && isRenderBlock()) {
2786 RenderBlock* block = toRenderBlock(this);
2787 if (block->hasPositionedObjects())
2788 block->removePositionedObjects(0);
2791 ASSERT(!beforeChild || toBoxModelObject == beforeChild->parent());
2792 for (RenderObject* child = startChild; child && child != endChild; ) {
2793 // Save our next sibling as moveChildTo will clear it.
2794 RenderObject* nextSibling = child->nextSibling();
2795 moveChildTo(toBoxModelObject, child, beforeChild, fullRemoveInsert);
2796 child = nextSibling;
2800 } // namespace WebCore