2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
5 * (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
6 * Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
7 * Copyright (C) 2010 Google Inc. All rights reserved.
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Library General Public
11 * License as published by the Free Software Foundation; either
12 * version 2 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Library General Public License for more details.
19 * You should have received a copy of the GNU Library General Public License
20 * along with this library; see the file COPYING.LIB. If not, write to
21 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22 * Boston, MA 02110-1301, USA.
27 #include "RenderBoxModelObject.h"
29 #include "GraphicsContext.h"
30 #include "HTMLFrameOwnerElement.h"
31 #include "HTMLNames.h"
32 #include "ImageBuffer.h"
35 #include "RenderBlock.h"
36 #include "RenderInline.h"
37 #include "RenderLayer.h"
38 #include "RenderNamedFlowThread.h"
39 #include "RenderRegion.h"
40 #include "RenderTable.h"
41 #include "RenderView.h"
42 #include "ScrollingConstraints.h"
44 #include "TransformState.h"
46 #if USE(ACCELERATED_COMPOSITING)
47 #include "RenderLayerBacking.h"
48 #include "RenderLayerCompositor.h"
55 using namespace HTMLNames;
57 static const double cInterpolationCutoff = 800. * 800.;
58 static const double cLowQualityTimeThreshold = 0.500; // 500 ms
60 typedef HashMap<const void*, LayoutSize> LayerSizeMap;
61 typedef HashMap<RenderBoxModelObject*, LayerSizeMap> ObjectLayerSizeMap;
63 // The HashMap for storing continuation pointers.
64 // An inline can be split with blocks occuring in between the inline content.
65 // When this occurs we need a pointer to the next object. We can basically be
66 // split into a sequence of inlines and blocks. The continuation will either be
67 // an anonymous block (that houses other blocks) or it will be an inline flow.
68 // <b><i><p>Hello</p></i></b>. In this example the <i> will have a block as
69 // its continuation but the <b> will just have an inline as its continuation.
70 typedef HashMap<const RenderBoxModelObject*, RenderBoxModelObject*> ContinuationMap;
71 static ContinuationMap* continuationMap = 0;
73 // This HashMap is similar to the continuation map, but connects first-letter
74 // renderers to their remaining text fragments.
75 typedef HashMap<const RenderBoxModelObject*, RenderTextFragment*> FirstLetterRemainingTextMap;
76 static FirstLetterRemainingTextMap* firstLetterRemainingTextMap = 0;
78 class ImageQualityController {
79 WTF_MAKE_NONCOPYABLE(ImageQualityController); WTF_MAKE_FAST_ALLOCATED;
81 ImageQualityController();
82 bool shouldPaintAtLowQuality(GraphicsContext*, RenderBoxModelObject*, Image*, const void* layer, const LayoutSize&);
83 void removeLayer(RenderBoxModelObject*, LayerSizeMap* innerMap, const void* layer);
84 void set(RenderBoxModelObject*, LayerSizeMap* innerMap, const void* layer, const LayoutSize&);
85 void objectDestroyed(RenderBoxModelObject*);
86 bool isEmpty() { return m_objectLayerSizeMap.isEmpty(); }
89 void highQualityRepaintTimerFired(Timer<ImageQualityController>*);
92 ObjectLayerSizeMap m_objectLayerSizeMap;
93 Timer<ImageQualityController> m_timer;
94 bool m_animatedResizeIsActive;
95 bool m_liveResizeOptimizationIsActive;
98 ImageQualityController::ImageQualityController()
99 : m_timer(this, &ImageQualityController::highQualityRepaintTimerFired)
100 , m_animatedResizeIsActive(false)
101 , m_liveResizeOptimizationIsActive(false)
105 void ImageQualityController::removeLayer(RenderBoxModelObject* object, LayerSizeMap* innerMap, const void* layer)
108 innerMap->remove(layer);
109 if (innerMap->isEmpty())
110 objectDestroyed(object);
114 void ImageQualityController::set(RenderBoxModelObject* object, LayerSizeMap* innerMap, const void* layer, const LayoutSize& size)
117 innerMap->set(layer, size);
119 LayerSizeMap newInnerMap;
120 newInnerMap.set(layer, size);
121 m_objectLayerSizeMap.set(object, newInnerMap);
125 void ImageQualityController::objectDestroyed(RenderBoxModelObject* object)
127 m_objectLayerSizeMap.remove(object);
128 if (m_objectLayerSizeMap.isEmpty()) {
129 m_animatedResizeIsActive = false;
134 void ImageQualityController::highQualityRepaintTimerFired(Timer<ImageQualityController>*)
136 if (!m_animatedResizeIsActive && !m_liveResizeOptimizationIsActive)
138 m_animatedResizeIsActive = false;
140 for (ObjectLayerSizeMap::iterator it = m_objectLayerSizeMap.begin(); it != m_objectLayerSizeMap.end(); ++it) {
141 if (Frame* frame = it->key->document().frame()) {
142 // If this renderer's containing FrameView is in live resize, punt the timer and hold back for now.
143 if (frame->view() && frame->view()->inLiveResize()) {
151 m_liveResizeOptimizationIsActive = false;
154 void ImageQualityController::restartTimer()
156 m_timer.startOneShot(cLowQualityTimeThreshold);
159 bool ImageQualityController::shouldPaintAtLowQuality(GraphicsContext* context, RenderBoxModelObject* object, Image* image, const void *layer, const LayoutSize& size)
161 // If the image is not a bitmap image, then none of this is relevant and we just paint at high
163 if (!image || !image->isBitmapImage() || context->paintingDisabled())
166 switch (object->style()->imageRendering()) {
167 case ImageRenderingOptimizeSpeed:
168 case ImageRenderingCrispEdges:
170 case ImageRenderingOptimizeQuality:
172 case ImageRenderingAuto:
176 // Make sure to use the unzoomed image size, since if a full page zoom is in effect, the image
177 // is actually being scaled.
178 IntSize imageSize(image->width(), image->height());
180 // Look ourselves up in the hashtables.
181 ObjectLayerSizeMap::iterator i = m_objectLayerSizeMap.find(object);
182 LayerSizeMap* innerMap = i != m_objectLayerSizeMap.end() ? &i->value : 0;
184 bool isFirstResize = true;
186 LayerSizeMap::iterator j = innerMap->find(layer);
187 if (j != innerMap->end()) {
188 isFirstResize = false;
193 // If the containing FrameView is being resized, paint at low quality until resizing is finished.
194 if (Frame* frame = object->document().frame()) {
195 bool frameViewIsCurrentlyInLiveResize = frame->view() && frame->view()->inLiveResize();
196 if (frameViewIsCurrentlyInLiveResize) {
197 set(object, innerMap, layer, size);
199 m_liveResizeOptimizationIsActive = true;
202 if (m_liveResizeOptimizationIsActive) {
203 // Live resize has ended, paint in HQ and remove this object from the list.
204 removeLayer(object, innerMap, layer);
209 const AffineTransform& currentTransform = context->getCTM();
210 bool contextIsScaled = !currentTransform.isIdentityOrTranslationOrFlipped();
211 if (!contextIsScaled && size == imageSize) {
212 // There is no scale in effect. If we had a scale in effect before, we can just remove this object from the list.
213 removeLayer(object, innerMap, layer);
217 // There is no need to hash scaled images that always use low quality mode when the page demands it. This is the iChat case.
218 if (object->document().page()->inLowQualityImageInterpolationMode()) {
219 double totalPixels = static_cast<double>(image->width()) * static_cast<double>(image->height());
220 if (totalPixels > cInterpolationCutoff)
224 // If an animated resize is active, paint in low quality and kick the timer ahead.
225 if (m_animatedResizeIsActive) {
226 set(object, innerMap, layer, size);
230 // If this is the first time resizing this image, or its size is the
231 // same as the last resize, draw at high res, but record the paint
232 // size and set the timer.
233 if (isFirstResize || oldSize == size) {
235 set(object, innerMap, layer, size);
238 // If the timer is no longer active, draw at high quality and don't
240 if (!m_timer.isActive()) {
241 removeLayer(object, innerMap, layer);
244 // This object has been resized to two different sizes while the timer
245 // is active, so draw at low quality, set the flag for animated resizes and
246 // the object to the list for high quality redraw.
247 set(object, innerMap, layer, size);
248 m_animatedResizeIsActive = true;
253 static ImageQualityController* gImageQualityController = 0;
255 static ImageQualityController* imageQualityController()
257 if (!gImageQualityController)
258 gImageQualityController = new ImageQualityController;
260 return gImageQualityController;
263 void RenderBoxModelObject::setSelectionState(SelectionState state)
265 if (state == SelectionInside && selectionState() != SelectionNone)
268 if ((state == SelectionStart && selectionState() == SelectionEnd)
269 || (state == SelectionEnd && selectionState() == SelectionStart))
270 RenderObject::setSelectionState(SelectionBoth);
272 RenderObject::setSelectionState(state);
274 // FIXME: We should consider whether it is OK propagating to ancestor RenderInlines.
275 // This is a workaround for http://webkit.org/b/32123
276 // The containing block can be null in case of an orphaned tree.
277 RenderBlock* containingBlock = this->containingBlock();
278 if (containingBlock && !containingBlock->isRenderView())
279 containingBlock->setSelectionState(state);
282 #if USE(ACCELERATED_COMPOSITING)
283 void RenderBoxModelObject::contentChanged(ContentChangeType changeType)
288 layer()->contentChanged(changeType);
291 bool RenderBoxModelObject::hasAcceleratedCompositing() const
293 return view().compositor().hasAcceleratedCompositing();
296 bool RenderBoxModelObject::startTransition(double timeOffset, CSSPropertyID propertyId, const RenderStyle* fromStyle, const RenderStyle* toStyle)
299 ASSERT(isComposited());
300 return layer()->backing()->startTransition(timeOffset, propertyId, fromStyle, toStyle);
303 void RenderBoxModelObject::transitionPaused(double timeOffset, CSSPropertyID propertyId)
306 ASSERT(isComposited());
307 layer()->backing()->transitionPaused(timeOffset, propertyId);
310 void RenderBoxModelObject::transitionFinished(CSSPropertyID propertyId)
313 ASSERT(isComposited());
314 layer()->backing()->transitionFinished(propertyId);
317 bool RenderBoxModelObject::startAnimation(double timeOffset, const Animation* animation, const KeyframeList& keyframes)
320 ASSERT(isComposited());
321 return layer()->backing()->startAnimation(timeOffset, animation, keyframes);
324 void RenderBoxModelObject::animationPaused(double timeOffset, const String& name)
327 ASSERT(isComposited());
328 layer()->backing()->animationPaused(timeOffset, name);
331 void RenderBoxModelObject::animationFinished(const String& name)
334 ASSERT(isComposited());
335 layer()->backing()->animationFinished(name);
338 void RenderBoxModelObject::suspendAnimations(double time)
341 ASSERT(isComposited());
342 layer()->backing()->suspendAnimations(time);
346 bool RenderBoxModelObject::shouldPaintAtLowQuality(GraphicsContext* context, Image* image, const void* layer, const LayoutSize& size)
348 return imageQualityController()->shouldPaintAtLowQuality(context, this, image, layer, size);
351 RenderBoxModelObject::RenderBoxModelObject(ContainerNode* node)
352 : RenderLayerModelObject(node)
356 RenderBoxModelObject::~RenderBoxModelObject()
358 if (gImageQualityController) {
359 gImageQualityController->objectDestroyed(this);
360 if (gImageQualityController->isEmpty()) {
361 delete gImageQualityController;
362 gImageQualityController = 0;
367 void RenderBoxModelObject::willBeDestroyed()
369 // A continuation of this RenderObject should be destroyed at subclasses.
370 ASSERT(!continuation());
372 // If this is a first-letter object with a remaining text fragment then the
373 // entry needs to be cleared from the map.
374 if (firstLetterRemainingText())
375 setFirstLetterRemainingText(0);
377 RenderLayerModelObject::willBeDestroyed();
380 void RenderBoxModelObject::updateFromStyle()
382 RenderLayerModelObject::updateFromStyle();
384 // Set the appropriate bits for a box model object. Since all bits are cleared in styleWillChange,
385 // we only check for bits that could possibly be set to true.
386 RenderStyle* styleToUse = style();
387 setHasBoxDecorations(hasBackground() || styleToUse->hasBorder() || styleToUse->hasAppearance() || styleToUse->boxShadow());
388 setInline(styleToUse->isDisplayInlineType());
389 setPositionState(styleToUse->position());
390 setHorizontalWritingMode(styleToUse->isHorizontalWritingMode());
393 static LayoutSize accumulateInFlowPositionOffsets(const RenderObject* child)
395 if (!child->isAnonymousBlock() || !child->isInFlowPositioned())
398 RenderObject* p = toRenderBlock(child)->inlineElementContinuation();
399 while (p && p->isRenderInline()) {
400 if (p->isInFlowPositioned()) {
401 RenderInline* renderInline = toRenderInline(p);
402 offset += renderInline->offsetForInFlowPosition();
409 bool RenderBoxModelObject::hasAutoHeightOrContainingBlockWithAutoHeight() const
411 Length logicalHeightLength = style()->logicalHeight();
412 if (logicalHeightLength.isAuto())
415 // For percentage heights: The percentage is calculated with respect to the height of the generated box's
416 // containing block. If the height of the containing block is not specified explicitly (i.e., it depends
417 // on content height), and this element is not absolutely positioned, the value computes to 'auto'.
418 if (!logicalHeightLength.isPercent() || isOutOfFlowPositioned() || document().inQuirksMode())
421 // Anonymous block boxes are ignored when resolving percentage values that would refer to it:
422 // the closest non-anonymous ancestor box is used instead.
423 RenderBlock* cb = containingBlock();
424 while (cb->isAnonymous())
425 cb = cb->containingBlock();
427 // Matching RenderBox::percentageLogicalHeightIsResolvableFromBlock() by
428 // ignoring table cell's attribute value, where it says that table cells violate
429 // what the CSS spec says to do with heights. Basically we
430 // don't care if the cell specified a height or not.
431 if (cb->isTableCell())
434 if (!cb->style()->logicalHeight().isAuto() || (!cb->style()->logicalTop().isAuto() && !cb->style()->logicalBottom().isAuto()))
440 LayoutSize RenderBoxModelObject::relativePositionOffset() const
442 LayoutSize offset = accumulateInFlowPositionOffsets(this);
444 RenderBlock* containingBlock = this->containingBlock();
446 // Objects that shrink to avoid floats normally use available line width when computing containing block width. However
447 // in the case of relative positioning using percentages, we can't do this. The offset should always be resolved using the
448 // available width of the containing block. Therefore we don't use containingBlockLogicalWidthForContent() here, but instead explicitly
449 // call availableWidth on our containing block.
450 if (!style()->left().isAuto()) {
451 if (!style()->right().isAuto() && !containingBlock->style()->isLeftToRightDirection())
452 offset.setWidth(-valueForLength(style()->right(), containingBlock->availableWidth(), &view()));
454 offset.expand(valueForLength(style()->left(), containingBlock->availableWidth(), &view()), 0);
455 } else if (!style()->right().isAuto()) {
456 offset.expand(-valueForLength(style()->right(), containingBlock->availableWidth(), &view()), 0);
459 // If the containing block of a relatively positioned element does not
460 // specify a height, a percentage top or bottom offset should be resolved as
461 // auto. An exception to this is if the containing block has the WinIE quirk
462 // where <html> and <body> assume the size of the viewport. In this case,
463 // calculate the percent offset based on this height.
464 // See <https://bugs.webkit.org/show_bug.cgi?id=26396>.
465 if (!style()->top().isAuto()
466 && (!containingBlock->hasAutoHeightOrContainingBlockWithAutoHeight()
467 || !style()->top().isPercent()
468 || containingBlock->stretchesToViewport()))
469 offset.expand(0, valueForLength(style()->top(), containingBlock->availableHeight(), &view()));
471 else if (!style()->bottom().isAuto()
472 && (!containingBlock->hasAutoHeightOrContainingBlockWithAutoHeight()
473 || !style()->bottom().isPercent()
474 || containingBlock->stretchesToViewport()))
475 offset.expand(0, -valueForLength(style()->bottom(), containingBlock->availableHeight(), &view()));
480 LayoutPoint RenderBoxModelObject::adjustedPositionRelativeToOffsetParent(const LayoutPoint& startPoint) const
482 // If the element is the HTML body element or doesn't have a parent
483 // return 0 and stop this algorithm.
484 if (isBody() || !parent())
485 return LayoutPoint();
487 LayoutPoint referencePoint = startPoint;
488 referencePoint.move(parent()->offsetForColumns(referencePoint));
490 // If the offsetParent of the element is null, or is the HTML body element,
491 // return the distance between the canvas origin and the left border edge
492 // of the element and stop this algorithm.
493 if (const RenderBoxModelObject* offsetParent = this->offsetParent()) {
494 if (offsetParent->isBox() && !offsetParent->isBody() && !offsetParent->isTable())
495 referencePoint.move(-toRenderBox(offsetParent)->borderLeft(), -toRenderBox(offsetParent)->borderTop());
496 if (!isOutOfFlowPositioned() || flowThreadContainingBlock()) {
497 if (isRelPositioned())
498 referencePoint.move(relativePositionOffset());
499 else if (isStickyPositioned())
500 referencePoint.move(stickyPositionOffset());
502 // CSS regions specification says that region flows should return the body element as their offsetParent.
503 // Since we will bypass the body’s renderer anyway, just end the loop if we encounter a region flow (named flow thread).
504 // See http://dev.w3.org/csswg/css-regions/#cssomview-offset-attributes
505 RenderObject* curr = parent();
506 while (curr != offsetParent && !curr->isRenderNamedFlowThread()) {
507 // FIXME: What are we supposed to do inside SVG content?
508 if (!isOutOfFlowPositioned()) {
509 if (curr->isBox() && !curr->isTableRow())
510 referencePoint.moveBy(toRenderBox(curr)->topLeftLocation());
511 referencePoint.move(curr->parent()->offsetForColumns(referencePoint));
513 curr = curr->parent();
516 // Compute the offset position for elements inside named flow threads for which the offsetParent was the body.
517 // See https://bugs.webkit.org/show_bug.cgi?id=115899
518 if (curr->isRenderNamedFlowThread())
519 referencePoint = toRenderNamedFlowThread(curr)->adjustedPositionRelativeToOffsetParent(*this, referencePoint);
520 else if (offsetParent->isBox() && offsetParent->isBody() && !offsetParent->isPositioned())
521 referencePoint.moveBy(toRenderBox(offsetParent)->topLeftLocation());
525 return referencePoint;
528 void RenderBoxModelObject::computeStickyPositionConstraints(StickyPositionViewportConstraints& constraints, const FloatRect& constrainingRect) const
530 constraints.setConstrainingRectAtLastLayout(constrainingRect);
532 RenderBlock* containingBlock = this->containingBlock();
533 RenderLayer* enclosingClippingLayer = layer()->enclosingOverflowClipLayer(ExcludeSelf);
534 RenderBox* enclosingClippingBox = enclosingClippingLayer ? toRenderBox(&enclosingClippingLayer->renderer()) : &view();
536 LayoutRect containerContentRect;
537 if (!enclosingClippingLayer || (containingBlock != enclosingClippingBox))
538 containerContentRect = containingBlock->contentBoxRect();
540 containerContentRect = containingBlock->layoutOverflowRect();
541 LayoutPoint containerLocation = containerContentRect.location() + LayoutPoint(containingBlock->borderLeft() + containingBlock->paddingLeft(),
542 containingBlock->borderTop() + containingBlock->paddingTop());
543 containerContentRect.setLocation(containerLocation);
546 LayoutUnit maxWidth = containingBlock->availableLogicalWidth();
548 // Sticky positioned element ignore any override logical width on the containing block (as they don't call
549 // containingBlockLogicalWidthForContent). It's unclear whether this is totally fine.
550 LayoutBoxExtent minMargin(minimumValueForLength(style()->marginTop(), maxWidth, &view()),
551 minimumValueForLength(style()->marginRight(), maxWidth, &view()),
552 minimumValueForLength(style()->marginBottom(), maxWidth, &view()),
553 minimumValueForLength(style()->marginLeft(), maxWidth, &view()));
555 // Compute the container-relative area within which the sticky element is allowed to move.
556 containerContentRect.contract(minMargin);
558 // Finally compute container rect relative to the scrolling ancestor.
559 FloatRect containerRectRelativeToScrollingAncestor = containingBlock->localToContainerQuad(FloatRect(containerContentRect), enclosingClippingBox).boundingBox();
560 if (enclosingClippingLayer) {
561 FloatPoint containerLocationRelativeToScrollingAncestor = containerRectRelativeToScrollingAncestor.location() -
562 FloatSize(enclosingClippingBox->borderLeft() + enclosingClippingBox->paddingLeft(),
563 enclosingClippingBox->borderTop() + enclosingClippingBox->paddingTop());
564 if (enclosingClippingBox != containingBlock)
565 containerLocationRelativeToScrollingAncestor += enclosingClippingLayer->scrollOffset();
566 containerRectRelativeToScrollingAncestor.setLocation(containerLocationRelativeToScrollingAncestor);
568 constraints.setContainingBlockRect(containerRectRelativeToScrollingAncestor);
570 // Now compute the sticky box rect, also relative to the scrolling ancestor.
571 LayoutRect stickyBoxRect = frameRectForStickyPositioning();
572 LayoutRect flippedStickyBoxRect = stickyBoxRect;
573 containingBlock->flipForWritingMode(flippedStickyBoxRect);
574 FloatRect stickyBoxRelativeToScrollingAnecstor = flippedStickyBoxRect;
576 // FIXME: sucks to call localToContainerQuad again, but we can't just offset from the previously computed rect if there are transforms.
577 // Map to the view to avoid including page scale factor.
578 FloatPoint stickyLocationRelativeToScrollingAncestor = flippedStickyBoxRect.location() + containingBlock->localToContainerQuad(FloatRect(FloatPoint(), containingBlock->size()), enclosingClippingBox).boundingBox().location();
579 if (enclosingClippingLayer) {
580 stickyLocationRelativeToScrollingAncestor -= FloatSize(enclosingClippingBox->borderLeft() + enclosingClippingBox->paddingLeft(),
581 enclosingClippingBox->borderTop() + enclosingClippingBox->paddingTop());
582 if (enclosingClippingBox != containingBlock)
583 stickyLocationRelativeToScrollingAncestor += enclosingClippingLayer->scrollOffset();
585 // FIXME: For now, assume that |this| is not transformed.
586 stickyBoxRelativeToScrollingAnecstor.setLocation(stickyLocationRelativeToScrollingAncestor);
587 constraints.setStickyBoxRect(stickyBoxRelativeToScrollingAnecstor);
589 if (!style()->left().isAuto()) {
590 constraints.setLeftOffset(valueForLength(style()->left(), constrainingRect.width(), &view()));
591 constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeLeft);
594 if (!style()->right().isAuto()) {
595 constraints.setRightOffset(valueForLength(style()->right(), constrainingRect.width(), &view()));
596 constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeRight);
599 if (!style()->top().isAuto()) {
600 constraints.setTopOffset(valueForLength(style()->top(), constrainingRect.height(), &view()));
601 constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeTop);
604 if (!style()->bottom().isAuto()) {
605 constraints.setBottomOffset(valueForLength(style()->bottom(), constrainingRect.height(), &view()));
606 constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeBottom);
610 LayoutSize RenderBoxModelObject::stickyPositionOffset() const
612 FloatRect constrainingRect;
615 RenderLayer* enclosingClippingLayer = layer()->enclosingOverflowClipLayer(ExcludeSelf);
616 if (enclosingClippingLayer) {
617 RenderBox* enclosingClippingBox = toRenderBox(&enclosingClippingLayer->renderer());
618 LayoutRect clipRect = enclosingClippingBox->overflowClipRect(LayoutPoint(), 0); // FIXME: make this work in regions.
619 constrainingRect = enclosingClippingBox->localToContainerQuad(FloatRect(clipRect), &view()).boundingBox();
621 FloatPoint scrollOffset = FloatPoint() + enclosingClippingLayer->scrollOffset();
622 constrainingRect.setLocation(scrollOffset);
624 LayoutRect viewportRect = view().frameView().viewportConstrainedVisibleContentRect();
625 float scale = view().frameView().frame().frameScaleFactor();
626 viewportRect.scale(1 / scale);
627 constrainingRect = viewportRect;
630 StickyPositionViewportConstraints constraints;
631 computeStickyPositionConstraints(constraints, constrainingRect);
633 // The sticky offset is physical, so we can just return the delta computed in absolute coords (though it may be wrong with transforms).
634 return LayoutSize(constraints.computeStickyOffset(constrainingRect));
637 LayoutSize RenderBoxModelObject::offsetForInFlowPosition() const
639 if (isRelPositioned())
640 return relativePositionOffset();
642 if (isStickyPositioned())
643 return stickyPositionOffset();
648 LayoutUnit RenderBoxModelObject::offsetLeft() const
650 // Note that RenderInline and RenderBox override this to pass a different
651 // startPoint to adjustedPositionRelativeToOffsetParent.
652 return adjustedPositionRelativeToOffsetParent(LayoutPoint()).x();
655 LayoutUnit RenderBoxModelObject::offsetTop() const
657 // Note that RenderInline and RenderBox override this to pass a different
658 // startPoint to adjustedPositionRelativeToOffsetParent.
659 return adjustedPositionRelativeToOffsetParent(LayoutPoint()).y();
662 int RenderBoxModelObject::pixelSnappedOffsetWidth() const
664 return snapSizeToPixel(offsetWidth(), offsetLeft());
667 int RenderBoxModelObject::pixelSnappedOffsetHeight() const
669 return snapSizeToPixel(offsetHeight(), offsetTop());
672 LayoutUnit RenderBoxModelObject::computedCSSPadding(Length padding) const
675 RenderView* renderView = 0;
676 if (padding.isPercent())
677 w = containingBlockLogicalWidthForContent();
678 else if (padding.isViewportPercentage())
679 renderView = &view();
680 return minimumValueForLength(padding, w, renderView);
683 RoundedRect RenderBoxModelObject::getBackgroundRoundedRect(const LayoutRect& borderRect, InlineFlowBox* box, LayoutUnit inlineBoxWidth, LayoutUnit inlineBoxHeight,
684 bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
686 RoundedRect border = style()->getRoundedBorderFor(borderRect, &view(), includeLogicalLeftEdge, includeLogicalRightEdge);
687 if (box && (box->nextLineBox() || box->prevLineBox())) {
688 RoundedRect segmentBorder = style()->getRoundedBorderFor(LayoutRect(0, 0, inlineBoxWidth, inlineBoxHeight), &view(), includeLogicalLeftEdge, includeLogicalRightEdge);
689 border.setRadii(segmentBorder.radii());
695 void RenderBoxModelObject::clipRoundedInnerRect(GraphicsContext * context, const LayoutRect& rect, const RoundedRect& clipRect)
697 if (clipRect.isRenderable())
698 context->clipRoundedRect(clipRect);
700 // We create a rounded rect for each of the corners and clip it, while making sure we clip opposing corners together.
701 if (!clipRect.radii().topLeft().isEmpty() || !clipRect.radii().bottomRight().isEmpty()) {
702 IntRect topCorner(clipRect.rect().x(), clipRect.rect().y(), rect.maxX() - clipRect.rect().x(), rect.maxY() - clipRect.rect().y());
703 RoundedRect::Radii topCornerRadii;
704 topCornerRadii.setTopLeft(clipRect.radii().topLeft());
705 context->clipRoundedRect(RoundedRect(topCorner, topCornerRadii));
707 IntRect bottomCorner(rect.x(), rect.y(), clipRect.rect().maxX() - rect.x(), clipRect.rect().maxY() - rect.y());
708 RoundedRect::Radii bottomCornerRadii;
709 bottomCornerRadii.setBottomRight(clipRect.radii().bottomRight());
710 context->clipRoundedRect(RoundedRect(bottomCorner, bottomCornerRadii));
713 if (!clipRect.radii().topRight().isEmpty() || !clipRect.radii().bottomLeft().isEmpty()) {
714 IntRect topCorner(rect.x(), clipRect.rect().y(), clipRect.rect().maxX() - rect.x(), rect.maxY() - clipRect.rect().y());
715 RoundedRect::Radii topCornerRadii;
716 topCornerRadii.setTopRight(clipRect.radii().topRight());
717 context->clipRoundedRect(RoundedRect(topCorner, topCornerRadii));
719 IntRect bottomCorner(clipRect.rect().x(), rect.y(), rect.maxX() - clipRect.rect().x(), clipRect.rect().maxY() - rect.y());
720 RoundedRect::Radii bottomCornerRadii;
721 bottomCornerRadii.setBottomLeft(clipRect.radii().bottomLeft());
722 context->clipRoundedRect(RoundedRect(bottomCorner, bottomCornerRadii));
727 static LayoutRect shrinkRectByOnePixel(GraphicsContext* context, const LayoutRect& rect)
729 LayoutRect shrunkRect = rect;
730 AffineTransform transform = context->getCTM();
731 shrunkRect.inflateX(-static_cast<LayoutUnit>(ceil(1 / transform.xScale())));
732 shrunkRect.inflateY(-static_cast<LayoutUnit>(ceil(1 / transform.yScale())));
736 LayoutRect RenderBoxModelObject::borderInnerRectAdjustedForBleedAvoidance(GraphicsContext* context, const LayoutRect& rect, BackgroundBleedAvoidance bleedAvoidance) const
738 // We shrink the rectangle by one pixel on each side to make it fully overlap the anti-aliased background border
739 return (bleedAvoidance == BackgroundBleedBackgroundOverBorder) ? shrinkRectByOnePixel(context, rect) : rect;
742 RoundedRect RenderBoxModelObject::backgroundRoundedRectAdjustedForBleedAvoidance(GraphicsContext* context, const LayoutRect& borderRect, BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* box, const LayoutSize& boxSize, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
744 if (bleedAvoidance == BackgroundBleedShrinkBackground) {
745 // We shrink the rectangle by one pixel on each side because the bleed is one pixel maximum.
746 return getBackgroundRoundedRect(shrinkRectByOnePixel(context, borderRect), box, boxSize.width(), boxSize.height(), includeLogicalLeftEdge, includeLogicalRightEdge);
748 if (bleedAvoidance == BackgroundBleedBackgroundOverBorder)
749 return style()->getRoundedInnerBorderFor(borderRect, includeLogicalLeftEdge, includeLogicalRightEdge);
751 return getBackgroundRoundedRect(borderRect, box, boxSize.width(), boxSize.height(), includeLogicalLeftEdge, includeLogicalRightEdge);
754 static void applyBoxShadowForBackground(GraphicsContext* context, RenderStyle* style)
756 const ShadowData* boxShadow = style->boxShadow();
757 while (boxShadow->style() != Normal)
758 boxShadow = boxShadow->next();
760 FloatSize shadowOffset(boxShadow->x(), boxShadow->y());
761 if (!boxShadow->isWebkitBoxShadow())
762 context->setShadow(shadowOffset, boxShadow->radius(), boxShadow->color(), style->colorSpace());
764 context->setLegacyShadow(shadowOffset, boxShadow->radius(), boxShadow->color(), style->colorSpace());
767 void RenderBoxModelObject::paintFillLayerExtended(const PaintInfo& paintInfo, const Color& color, const FillLayer* bgLayer, const LayoutRect& rect,
768 BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* box, const LayoutSize& boxSize, CompositeOperator op, RenderObject* backgroundObject)
770 GraphicsContext* context = paintInfo.context;
771 if (context->paintingDisabled() || rect.isEmpty())
774 bool includeLeftEdge = box ? box->includeLogicalLeftEdge() : true;
775 bool includeRightEdge = box ? box->includeLogicalRightEdge() : true;
777 bool hasRoundedBorder = style()->hasBorderRadius() && (includeLeftEdge || includeRightEdge);
778 bool clippedWithLocalScrolling = hasOverflowClip() && bgLayer->attachment() == LocalBackgroundAttachment;
779 bool isBorderFill = bgLayer->clip() == BorderFillBox;
780 bool isRoot = this->isRoot();
782 Color bgColor = color;
783 StyleImage* bgImage = bgLayer->image();
784 bool shouldPaintBackgroundImage = bgImage && bgImage->canRender(this, style()->effectiveZoom());
786 bool forceBackgroundToWhite = false;
787 if (document().printing()) {
788 if (style()->printColorAdjust() == PrintColorAdjustEconomy)
789 forceBackgroundToWhite = true;
790 if (frame().settings().shouldPrintBackgrounds())
791 forceBackgroundToWhite = false;
794 // When printing backgrounds is disabled or using economy mode,
795 // change existing background colors and images to a solid white background.
796 // If there's no bg color or image, leave it untouched to avoid affecting transparency.
797 // We don't try to avoid loading the background images, because this style flag is only set
798 // when printing, and at that point we've already loaded the background images anyway. (To avoid
799 // loading the background images we'd have to do this check when applying styles rather than
801 if (forceBackgroundToWhite) {
802 // Note that we can't reuse this variable below because the bgColor might be changed
803 bool shouldPaintBackgroundColor = !bgLayer->next() && bgColor.isValid() && bgColor.alpha();
804 if (shouldPaintBackgroundImage || shouldPaintBackgroundColor) {
805 bgColor = Color::white;
806 shouldPaintBackgroundImage = false;
810 bool colorVisible = bgColor.isValid() && bgColor.alpha();
812 // Fast path for drawing simple color backgrounds.
813 if (!isRoot && !clippedWithLocalScrolling && !shouldPaintBackgroundImage && isBorderFill && !bgLayer->next()) {
817 bool boxShadowShouldBeAppliedToBackground = this->boxShadowShouldBeAppliedToBackground(bleedAvoidance, box);
818 GraphicsContextStateSaver shadowStateSaver(*context, boxShadowShouldBeAppliedToBackground);
819 if (boxShadowShouldBeAppliedToBackground)
820 applyBoxShadowForBackground(context, style());
822 if (hasRoundedBorder && bleedAvoidance != BackgroundBleedUseTransparencyLayer) {
823 RoundedRect border = backgroundRoundedRectAdjustedForBleedAvoidance(context, rect, bleedAvoidance, box, boxSize, includeLeftEdge, includeRightEdge);
824 if (border.isRenderable())
825 context->fillRoundedRect(border, bgColor, style()->colorSpace());
828 clipRoundedInnerRect(context, rect, border);
829 context->fillRect(border.rect(), bgColor, style()->colorSpace());
833 context->fillRect(pixelSnappedIntRect(rect), bgColor, style()->colorSpace());
838 // BorderFillBox radius clipping is taken care of by BackgroundBleedUseTransparencyLayer
839 bool clipToBorderRadius = hasRoundedBorder && !(isBorderFill && bleedAvoidance == BackgroundBleedUseTransparencyLayer);
840 GraphicsContextStateSaver clipToBorderStateSaver(*context, clipToBorderRadius);
841 if (clipToBorderRadius) {
842 RoundedRect border = isBorderFill ? backgroundRoundedRectAdjustedForBleedAvoidance(context, rect, bleedAvoidance, box, boxSize, includeLeftEdge, includeRightEdge) : getBackgroundRoundedRect(rect, box, boxSize.width(), boxSize.height(), includeLeftEdge, includeRightEdge);
844 // Clip to the padding or content boxes as necessary.
845 if (bgLayer->clip() == ContentFillBox) {
846 border = style()->getRoundedInnerBorderFor(border.rect(),
847 paddingTop() + borderTop(), paddingBottom() + borderBottom(), paddingLeft() + borderLeft(), paddingRight() + borderRight(), includeLeftEdge, includeRightEdge);
848 } else if (bgLayer->clip() == PaddingFillBox)
849 border = style()->getRoundedInnerBorderFor(border.rect(), includeLeftEdge, includeRightEdge);
851 clipRoundedInnerRect(context, rect, border);
854 int bLeft = includeLeftEdge ? borderLeft() : 0;
855 int bRight = includeRightEdge ? borderRight() : 0;
856 LayoutUnit pLeft = includeLeftEdge ? paddingLeft() : LayoutUnit();
857 LayoutUnit pRight = includeRightEdge ? paddingRight() : LayoutUnit();
859 GraphicsContextStateSaver clipWithScrollingStateSaver(*context, clippedWithLocalScrolling);
860 LayoutRect scrolledPaintRect = rect;
861 if (clippedWithLocalScrolling) {
862 // Clip to the overflow area.
863 RenderBox* thisBox = toRenderBox(this);
864 context->clip(thisBox->overflowClipRect(rect.location(), paintInfo.renderRegion));
866 // Adjust the paint rect to reflect a scrolled content box with borders at the ends.
867 IntSize offset = thisBox->scrolledContentOffset();
868 scrolledPaintRect.move(-offset);
869 scrolledPaintRect.setWidth(bLeft + layer()->scrollWidth() + bRight);
870 scrolledPaintRect.setHeight(borderTop() + layer()->scrollHeight() + borderBottom());
873 GraphicsContextStateSaver backgroundClipStateSaver(*context, false);
874 OwnPtr<ImageBuffer> maskImage;
877 if (bgLayer->clip() == PaddingFillBox || bgLayer->clip() == ContentFillBox) {
878 // Clip to the padding or content boxes as necessary.
879 if (!clipToBorderRadius) {
880 bool includePadding = bgLayer->clip() == ContentFillBox;
881 LayoutRect clipRect = LayoutRect(scrolledPaintRect.x() + bLeft + (includePadding ? pLeft : LayoutUnit()),
882 scrolledPaintRect.y() + borderTop() + (includePadding ? paddingTop() : LayoutUnit()),
883 scrolledPaintRect.width() - bLeft - bRight - (includePadding ? pLeft + pRight : LayoutUnit()),
884 scrolledPaintRect.height() - borderTop() - borderBottom() - (includePadding ? paddingTop() + paddingBottom() : LayoutUnit()));
885 backgroundClipStateSaver.save();
886 context->clip(clipRect);
888 } else if (bgLayer->clip() == TextFillBox) {
889 // We have to draw our text into a mask that can then be used to clip background drawing.
890 // First figure out how big the mask has to be. It should be no bigger than what we need
891 // to actually render, so we should intersect the dirty rect with the border box of the background.
892 maskRect = pixelSnappedIntRect(rect);
893 maskRect.intersect(paintInfo.rect);
895 // Now create the mask.
896 maskImage = context->createCompatibleBuffer(maskRect.size());
900 GraphicsContext* maskImageContext = maskImage->context();
901 maskImageContext->translate(-maskRect.x(), -maskRect.y());
903 // Now add the text to the clip. We do this by painting using a special paint phase that signals to
904 // InlineTextBoxes that they should just add their contents to the clip.
905 PaintInfo info(maskImageContext, maskRect, PaintPhaseTextClip, PaintBehaviorForceBlackText, 0, paintInfo.renderRegion);
907 RootInlineBox* root = box->root();
908 box->paint(info, LayoutPoint(scrolledPaintRect.x() - box->x(), scrolledPaintRect.y() - box->y()), root->lineTop(), root->lineBottom());
910 LayoutSize localOffset = isBox() ? toRenderBox(this)->locationOffset() : LayoutSize();
911 paint(info, scrolledPaintRect.location() - localOffset);
914 // The mask has been created. Now we just need to clip to it.
915 backgroundClipStateSaver.save();
916 context->clip(maskRect);
917 context->beginTransparencyLayer(1);
920 // Only fill with a base color (e.g., white) if we're the root document, since iframes/frames with
921 // no background in the child document should show the parent's background.
922 bool isOpaqueRoot = false;
925 if (!bgLayer->next() && !(bgColor.isValid() && bgColor.alpha() == 255)) {
926 Element* ownerElement = document().ownerElement();
928 if (!ownerElement->hasTagName(frameTag)) {
929 // Locate the <body> element using the DOM. This is easier than trying
930 // to crawl around a render tree with potential :before/:after content and
931 // anonymous blocks created by inline <body> tags etc. We can locate the <body>
932 // render object very easily via the DOM.
933 HTMLElement* body = document().body();
935 // Can't scroll a frameset document anyway.
936 isOpaqueRoot = body->hasLocalName(framesetTag);
940 // SVG documents and XML documents with SVG root nodes are transparent.
941 isOpaqueRoot = !document().hasSVGRootNode();
946 isOpaqueRoot = !view().frameView().isTransparent();
948 view().frameView().setContentIsOpaque(isOpaqueRoot);
951 // Paint the color first underneath all images, culled if background image occludes it.
952 // FIXME: In the bgLayer->hasFiniteBounds() case, we could improve the culling test
953 // by verifying whether the background image covers the entire layout rect.
954 if (!bgLayer->next()) {
955 IntRect backgroundRect(pixelSnappedIntRect(scrolledPaintRect));
956 bool boxShadowShouldBeAppliedToBackground = this->boxShadowShouldBeAppliedToBackground(bleedAvoidance, box);
957 if (boxShadowShouldBeAppliedToBackground || !shouldPaintBackgroundImage || !bgLayer->hasOpaqueImage(this) || !bgLayer->hasRepeatXY()) {
958 if (!boxShadowShouldBeAppliedToBackground)
959 backgroundRect.intersect(paintInfo.rect);
961 // If we have an alpha and we are painting the root element, go ahead and blend with the base background color.
963 bool shouldClearBackground = false;
965 baseColor = view().frameView().baseBackgroundColor();
966 if (!baseColor.alpha())
967 shouldClearBackground = true;
970 GraphicsContextStateSaver shadowStateSaver(*context, boxShadowShouldBeAppliedToBackground);
971 if (boxShadowShouldBeAppliedToBackground)
972 applyBoxShadowForBackground(context, style());
974 if (baseColor.alpha()) {
976 baseColor = baseColor.blend(bgColor);
978 context->fillRect(backgroundRect, baseColor, style()->colorSpace(), CompositeCopy);
979 } else if (bgColor.alpha()) {
980 CompositeOperator operation = shouldClearBackground ? CompositeCopy : context->compositeOperation();
981 context->fillRect(backgroundRect, bgColor, style()->colorSpace(), operation);
982 } else if (shouldClearBackground)
983 context->clearRect(backgroundRect);
987 // no progressive loading of the background image
988 if (shouldPaintBackgroundImage) {
989 BackgroundImageGeometry geometry;
990 calculateBackgroundImageGeometry(paintInfo.paintContainer, bgLayer, scrolledPaintRect, geometry, backgroundObject);
991 geometry.clip(paintInfo.rect);
992 if (!geometry.destRect().isEmpty()) {
993 CompositeOperator compositeOp = op == CompositeSourceOver ? bgLayer->composite() : op;
994 RenderObject* clientForBackgroundImage = backgroundObject ? backgroundObject : this;
995 RefPtr<Image> image = bgImage->image(clientForBackgroundImage, geometry.tileSize());
996 bool useLowQualityScaling = shouldPaintAtLowQuality(context, image.get(), bgLayer, geometry.tileSize());
997 context->drawTiledImage(image.get(), style()->colorSpace(), geometry.destRect(), geometry.relativePhase(), geometry.tileSize(),
998 compositeOp, useLowQualityScaling, bgLayer->blendMode());
1002 if (bgLayer->clip() == TextFillBox) {
1003 context->drawImageBuffer(maskImage.get(), ColorSpaceDeviceRGB, maskRect, CompositeDestinationIn);
1004 context->endTransparencyLayer();
1008 static inline int resolveWidthForRatio(int height, const FloatSize& intrinsicRatio)
1010 return ceilf(height * intrinsicRatio.width() / intrinsicRatio.height());
1013 static inline int resolveHeightForRatio(int width, const FloatSize& intrinsicRatio)
1015 return ceilf(width * intrinsicRatio.height() / intrinsicRatio.width());
1018 static inline IntSize resolveAgainstIntrinsicWidthOrHeightAndRatio(const IntSize& size, const FloatSize& intrinsicRatio, int useWidth, int useHeight)
1020 if (intrinsicRatio.isEmpty()) {
1022 return IntSize(useWidth, size.height());
1023 return IntSize(size.width(), useHeight);
1027 return IntSize(useWidth, resolveHeightForRatio(useWidth, intrinsicRatio));
1028 return IntSize(resolveWidthForRatio(useHeight, intrinsicRatio), useHeight);
1031 static inline IntSize resolveAgainstIntrinsicRatio(const IntSize& size, const FloatSize& intrinsicRatio)
1033 // Two possible solutions: (size.width(), solutionHeight) or (solutionWidth, size.height())
1034 // "... must be assumed to be the largest dimensions..." = easiest answer: the rect with the largest surface area.
1036 int solutionWidth = resolveWidthForRatio(size.height(), intrinsicRatio);
1037 int solutionHeight = resolveHeightForRatio(size.width(), intrinsicRatio);
1038 if (solutionWidth <= size.width()) {
1039 if (solutionHeight <= size.height()) {
1040 // If both solutions fit, choose the one covering the larger area.
1041 int areaOne = solutionWidth * size.height();
1042 int areaTwo = size.width() * solutionHeight;
1043 if (areaOne < areaTwo)
1044 return IntSize(size.width(), solutionHeight);
1045 return IntSize(solutionWidth, size.height());
1048 // Only the first solution fits.
1049 return IntSize(solutionWidth, size.height());
1052 // Only the second solution fits, assert that.
1053 ASSERT(solutionHeight <= size.height());
1054 return IntSize(size.width(), solutionHeight);
1057 IntSize RenderBoxModelObject::calculateImageIntrinsicDimensions(StyleImage* image, const IntSize& positioningAreaSize, ScaleByEffectiveZoomOrNot shouldScaleOrNot) const
1059 // A generated image without a fixed size, will always return the container size as intrinsic size.
1060 if (image->isGeneratedImage() && image->usesImageContainerSize())
1061 return IntSize(positioningAreaSize.width(), positioningAreaSize.height());
1063 Length intrinsicWidth;
1064 Length intrinsicHeight;
1065 FloatSize intrinsicRatio;
1066 image->computeIntrinsicDimensions(this, intrinsicWidth, intrinsicHeight, intrinsicRatio);
1068 // Intrinsic dimensions expressed as percentages must be resolved relative to the dimensions of the rectangle
1069 // that establishes the coordinate system for the 'background-position' property.
1071 // FIXME: Remove unnecessary rounding when layout is off ints: webkit.org/b/63656
1072 if (intrinsicWidth.isPercent() && intrinsicHeight.isPercent() && intrinsicRatio.isEmpty()) {
1073 // Resolve width/height percentages against positioningAreaSize, only if no intrinsic ratio is provided.
1074 int resolvedWidth = static_cast<int>(round(positioningAreaSize.width() * intrinsicWidth.percent() / 100));
1075 int resolvedHeight = static_cast<int>(round(positioningAreaSize.height() * intrinsicHeight.percent() / 100));
1076 return IntSize(resolvedWidth, resolvedHeight);
1079 IntSize resolvedSize(intrinsicWidth.isFixed() ? intrinsicWidth.value() : 0, intrinsicHeight.isFixed() ? intrinsicHeight.value() : 0);
1080 IntSize minimumSize(resolvedSize.width() > 0 ? 1 : 0, resolvedSize.height() > 0 ? 1 : 0);
1081 if (shouldScaleOrNot == ScaleByEffectiveZoom)
1082 resolvedSize.scale(style()->effectiveZoom());
1083 resolvedSize.clampToMinimumSize(minimumSize);
1085 if (!resolvedSize.isEmpty())
1086 return resolvedSize;
1088 // If the image has one of either an intrinsic width or an intrinsic height:
1089 // * and an intrinsic aspect ratio, then the missing dimension is calculated from the given dimension and the ratio.
1090 // * and no intrinsic aspect ratio, then the missing dimension is assumed to be the size of the rectangle that
1091 // establishes the coordinate system for the 'background-position' property.
1092 if (resolvedSize.width() > 0 || resolvedSize.height() > 0)
1093 return resolveAgainstIntrinsicWidthOrHeightAndRatio(positioningAreaSize, intrinsicRatio, resolvedSize.width(), resolvedSize.height());
1095 // If the image has no intrinsic dimensions and has an intrinsic ratio the dimensions must be assumed to be the
1096 // largest dimensions at that ratio such that neither dimension exceeds the dimensions of the rectangle that
1097 // establishes the coordinate system for the 'background-position' property.
1098 if (!intrinsicRatio.isEmpty())
1099 return resolveAgainstIntrinsicRatio(positioningAreaSize, intrinsicRatio);
1101 // If the image has no intrinsic ratio either, then the dimensions must be assumed to be the rectangle that
1102 // establishes the coordinate system for the 'background-position' property.
1103 return positioningAreaSize;
1106 static inline void applySubPixelHeuristicForTileSize(LayoutSize& tileSize, const IntSize& positioningAreaSize)
1108 tileSize.setWidth(positioningAreaSize.width() - tileSize.width() <= 1 ? tileSize.width().ceil() : tileSize.width().floor());
1109 tileSize.setHeight(positioningAreaSize.height() - tileSize.height() <= 1 ? tileSize.height().ceil() : tileSize.height().floor());
1112 IntSize RenderBoxModelObject::calculateFillTileSize(const FillLayer* fillLayer, const IntSize& positioningAreaSize) const
1114 StyleImage* image = fillLayer->image();
1115 EFillSizeType type = fillLayer->size().type;
1117 IntSize imageIntrinsicSize = calculateImageIntrinsicDimensions(image, positioningAreaSize, ScaleByEffectiveZoom);
1118 imageIntrinsicSize.scale(1 / image->imageScaleFactor(), 1 / image->imageScaleFactor());
1119 RenderView* renderView = &view();
1122 LayoutSize tileSize = positioningAreaSize;
1124 Length layerWidth = fillLayer->size().size.width();
1125 Length layerHeight = fillLayer->size().size.height();
1127 if (layerWidth.isFixed())
1128 tileSize.setWidth(layerWidth.value());
1129 else if (layerWidth.isPercent() || layerWidth.isViewportPercentage())
1130 tileSize.setWidth(valueForLength(layerWidth, positioningAreaSize.width(), renderView));
1132 if (layerHeight.isFixed())
1133 tileSize.setHeight(layerHeight.value());
1134 else if (layerHeight.isPercent() || layerHeight.isViewportPercentage())
1135 tileSize.setHeight(valueForLength(layerHeight, positioningAreaSize.height(), renderView));
1137 applySubPixelHeuristicForTileSize(tileSize, positioningAreaSize);
1139 // If one of the values is auto we have to use the appropriate
1140 // scale to maintain our aspect ratio.
1141 if (layerWidth.isAuto() && !layerHeight.isAuto()) {
1142 if (imageIntrinsicSize.height())
1143 tileSize.setWidth(imageIntrinsicSize.width() * tileSize.height() / imageIntrinsicSize.height());
1144 } else if (!layerWidth.isAuto() && layerHeight.isAuto()) {
1145 if (imageIntrinsicSize.width())
1146 tileSize.setHeight(imageIntrinsicSize.height() * tileSize.width() / imageIntrinsicSize.width());
1147 } else if (layerWidth.isAuto() && layerHeight.isAuto()) {
1148 // If both width and height are auto, use the image's intrinsic size.
1149 tileSize = imageIntrinsicSize;
1152 tileSize.clampNegativeToZero();
1153 return flooredIntSize(tileSize);
1156 // If both values are ‘auto’ then the intrinsic width and/or height of the image should be used, if any.
1157 if (!imageIntrinsicSize.isEmpty())
1158 return imageIntrinsicSize;
1160 // If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for ‘contain’.
1165 float horizontalScaleFactor = imageIntrinsicSize.width()
1166 ? static_cast<float>(positioningAreaSize.width()) / imageIntrinsicSize.width() : 1;
1167 float verticalScaleFactor = imageIntrinsicSize.height()
1168 ? static_cast<float>(positioningAreaSize.height()) / imageIntrinsicSize.height() : 1;
1169 float scaleFactor = type == Contain ? min(horizontalScaleFactor, verticalScaleFactor) : max(horizontalScaleFactor, verticalScaleFactor);
1170 return IntSize(max(1, static_cast<int>(imageIntrinsicSize.width() * scaleFactor)), max(1, static_cast<int>(imageIntrinsicSize.height() * scaleFactor)));
1174 ASSERT_NOT_REACHED();
1178 void RenderBoxModelObject::BackgroundImageGeometry::setNoRepeatX(int xOffset)
1180 m_destRect.move(max(xOffset, 0), 0);
1181 m_phase.setX(-min(xOffset, 0));
1182 m_destRect.setWidth(m_tileSize.width() + min(xOffset, 0));
1184 void RenderBoxModelObject::BackgroundImageGeometry::setNoRepeatY(int yOffset)
1186 m_destRect.move(0, max(yOffset, 0));
1187 m_phase.setY(-min(yOffset, 0));
1188 m_destRect.setHeight(m_tileSize.height() + min(yOffset, 0));
1191 void RenderBoxModelObject::BackgroundImageGeometry::useFixedAttachment(const IntPoint& attachmentPoint)
1193 IntPoint alignedPoint = attachmentPoint;
1194 m_phase.move(max(alignedPoint.x() - m_destRect.x(), 0), max(alignedPoint.y() - m_destRect.y(), 0));
1197 void RenderBoxModelObject::BackgroundImageGeometry::clip(const IntRect& clipRect)
1199 m_destRect.intersect(clipRect);
1202 IntPoint RenderBoxModelObject::BackgroundImageGeometry::relativePhase() const
1204 IntPoint phase = m_phase;
1205 phase += m_destRect.location() - m_destOrigin;
1209 bool RenderBoxModelObject::fixedBackgroundPaintsInLocalCoordinates() const
1211 #if USE(ACCELERATED_COMPOSITING)
1215 if (view().frameView().paintBehavior() & PaintBehaviorFlattenCompositingLayers)
1218 RenderLayer* rootLayer = view().layer();
1219 if (!rootLayer || !rootLayer->isComposited())
1222 return rootLayer->backing()->backgroundLayerPaintsFixedRootBackground();
1228 void RenderBoxModelObject::calculateBackgroundImageGeometry(const RenderLayerModelObject* paintContainer, const FillLayer* fillLayer, const LayoutRect& paintRect,
1229 BackgroundImageGeometry& geometry, RenderObject* backgroundObject) const
1231 LayoutUnit left = 0;
1233 IntSize positioningAreaSize;
1234 IntRect snappedPaintRect = pixelSnappedIntRect(paintRect);
1236 // Determine the background positioning area and set destRect to the background painting area.
1237 // destRect will be adjusted later if the background is non-repeating.
1238 // FIXME: transforms spec says that fixed backgrounds behave like scroll inside transforms. https://bugs.webkit.org/show_bug.cgi?id=15679
1239 bool fixedAttachment = fillLayer->attachment() == FixedBackgroundAttachment;
1241 #if ENABLE(FAST_MOBILE_SCROLLING)
1242 if (view().frameView().canBlitOnScroll()) {
1243 // As a side effect of an optimization to blit on scroll, we do not honor the CSS
1244 // property "background-attachment: fixed" because it may result in rendering
1245 // artifacts. Note, these artifacts only appear if we are blitting on scroll of
1246 // a page that has fixed background images.
1247 fixedAttachment = false;
1251 if (!fixedAttachment) {
1252 geometry.setDestRect(snappedPaintRect);
1254 LayoutUnit right = 0;
1255 LayoutUnit bottom = 0;
1256 // Scroll and Local.
1257 if (fillLayer->origin() != BorderFillBox) {
1258 left = borderLeft();
1259 right = borderRight();
1261 bottom = borderBottom();
1262 if (fillLayer->origin() == ContentFillBox) {
1263 left += paddingLeft();
1264 right += paddingRight();
1265 top += paddingTop();
1266 bottom += paddingBottom();
1270 // The background of the box generated by the root element covers the entire canvas including
1271 // its margins. Since those were added in already, we have to factor them out when computing
1272 // the background positioning area.
1274 positioningAreaSize = pixelSnappedIntSize(toRenderBox(this)->size() - LayoutSize(left + right, top + bottom), toRenderBox(this)->location());
1275 left += marginLeft();
1278 positioningAreaSize = pixelSnappedIntSize(paintRect.size() - LayoutSize(left + right, top + bottom), paintRect.location());
1280 geometry.setHasNonLocalGeometry();
1282 IntRect viewportRect = pixelSnappedIntRect(viewRect());
1283 if (fixedBackgroundPaintsInLocalCoordinates())
1284 viewportRect.setLocation(IntPoint());
1286 viewportRect.setLocation(IntPoint(view().frameView().scrollOffsetForFixedPosition()));
1288 if (paintContainer) {
1289 IntPoint absoluteContainerOffset = roundedIntPoint(paintContainer->localToAbsolute(FloatPoint()));
1290 viewportRect.moveBy(-absoluteContainerOffset);
1293 geometry.setDestRect(pixelSnappedIntRect(viewportRect));
1294 positioningAreaSize = geometry.destRect().size();
1297 const RenderObject* clientForBackgroundImage = backgroundObject ? backgroundObject : this;
1298 IntSize fillTileSize = calculateFillTileSize(fillLayer, positioningAreaSize);
1299 fillLayer->image()->setContainerSizeForRenderer(clientForBackgroundImage, fillTileSize, style()->effectiveZoom());
1300 geometry.setTileSize(fillTileSize);
1302 EFillRepeat backgroundRepeatX = fillLayer->repeatX();
1303 EFillRepeat backgroundRepeatY = fillLayer->repeatY();
1304 int availableWidth = positioningAreaSize.width() - geometry.tileSize().width();
1305 int availableHeight = positioningAreaSize.height() - geometry.tileSize().height();
1307 LayoutUnit computedXPosition = minimumValueForLength(fillLayer->xPosition(), availableWidth, &view(), true);
1308 if (backgroundRepeatX == RoundFill && positioningAreaSize.width() > 0 && fillTileSize.width() > 0) {
1309 int nrTiles = ceil((double)positioningAreaSize.width() / fillTileSize.width());
1311 if (fillLayer->size().size.height().isAuto() && backgroundRepeatY != RoundFill)
1312 fillTileSize.setHeight(fillTileSize.height() * positioningAreaSize.width() / (nrTiles * fillTileSize.width()));
1314 fillTileSize.setWidth(positioningAreaSize.width() / nrTiles);
1315 geometry.setTileSize(fillTileSize);
1316 geometry.setPhaseX(geometry.tileSize().width() ? geometry.tileSize().width() - roundToInt(computedXPosition + left) % geometry.tileSize().width() : 0);
1319 LayoutUnit computedYPosition = minimumValueForLength(fillLayer->yPosition(), availableHeight, &view(), true);
1320 if (backgroundRepeatY == RoundFill && positioningAreaSize.height() > 0 && fillTileSize.height() > 0) {
1321 int nrTiles = ceil((double)positioningAreaSize.height() / fillTileSize.height());
1323 if (fillLayer->size().size.width().isAuto() && backgroundRepeatX != RoundFill)
1324 fillTileSize.setWidth(fillTileSize.width() * positioningAreaSize.height() / (nrTiles * fillTileSize.height()));
1326 fillTileSize.setHeight(positioningAreaSize.height() / nrTiles);
1327 geometry.setTileSize(fillTileSize);
1328 geometry.setPhaseY(geometry.tileSize().height() ? geometry.tileSize().height() - roundToInt(computedYPosition + top) % geometry.tileSize().height() : 0);
1331 if (backgroundRepeatX == RepeatFill)
1332 geometry.setPhaseX(geometry.tileSize().width() ? geometry.tileSize().width() - roundToInt(computedXPosition + left) % geometry.tileSize().width() : 0);
1333 else if (backgroundRepeatX == NoRepeatFill) {
1334 int xOffset = fillLayer->backgroundXOrigin() == RightEdge ? availableWidth - computedXPosition : computedXPosition;
1335 geometry.setNoRepeatX(left + xOffset);
1338 if (backgroundRepeatY == RepeatFill)
1339 geometry.setPhaseY(geometry.tileSize().height() ? geometry.tileSize().height() - roundToInt(computedYPosition + top) % geometry.tileSize().height() : 0);
1340 else if (backgroundRepeatY == NoRepeatFill) {
1341 int yOffset = fillLayer->backgroundYOrigin() == BottomEdge ? availableHeight - computedYPosition : computedYPosition;
1342 geometry.setNoRepeatY(top + yOffset);
1345 if (fixedAttachment)
1346 geometry.useFixedAttachment(snappedPaintRect.location());
1348 geometry.clip(snappedPaintRect);
1349 geometry.setDestOrigin(geometry.destRect().location());
1352 void RenderBoxModelObject::getGeometryForBackgroundImage(const RenderLayerModelObject* paintContainer, IntRect& destRect, IntPoint& phase, IntSize& tileSize) const
1354 const FillLayer* backgroundLayer = style()->backgroundLayers();
1355 BackgroundImageGeometry geometry;
1356 calculateBackgroundImageGeometry(paintContainer, backgroundLayer, destRect, geometry);
1357 phase = geometry.phase();
1358 tileSize = geometry.tileSize();
1359 destRect = geometry.destRect();
1362 static LayoutUnit computeBorderImageSide(Length borderSlice, LayoutUnit borderSide, LayoutUnit imageSide, LayoutUnit boxExtent, RenderView* renderView)
1364 if (borderSlice.isRelative())
1365 return borderSlice.value() * borderSide;
1366 if (borderSlice.isAuto())
1368 return valueForLength(borderSlice, boxExtent, renderView);
1371 bool RenderBoxModelObject::paintNinePieceImage(GraphicsContext* graphicsContext, const LayoutRect& rect, const RenderStyle* style,
1372 const NinePieceImage& ninePieceImage, CompositeOperator op)
1374 StyleImage* styleImage = ninePieceImage.image();
1378 if (!styleImage->isLoaded())
1379 return true; // Never paint a nine-piece image incrementally, but don't paint the fallback borders either.
1381 if (!styleImage->canRender(this, style->effectiveZoom()))
1384 // FIXME: border-image is broken with full page zooming when tiling has to happen, since the tiling function
1385 // doesn't have any understanding of the zoom that is in effect on the tile.
1386 LayoutRect rectWithOutsets = rect;
1387 rectWithOutsets.expand(style->imageOutsets(ninePieceImage));
1388 IntRect borderImageRect = pixelSnappedIntRect(rectWithOutsets);
1390 IntSize imageSize = calculateImageIntrinsicDimensions(styleImage, borderImageRect.size(), DoNotScaleByEffectiveZoom);
1392 // If both values are ‘auto’ then the intrinsic width and/or height of the image should be used, if any.
1393 styleImage->setContainerSizeForRenderer(this, imageSize, style->effectiveZoom());
1395 int imageWidth = imageSize.width();
1396 int imageHeight = imageSize.height();
1397 RenderView* renderView = &view();
1399 float imageScaleFactor = styleImage->imageScaleFactor();
1400 int topSlice = min<int>(imageHeight, valueForLength(ninePieceImage.imageSlices().top(), imageHeight, renderView)) * imageScaleFactor;
1401 int rightSlice = min<int>(imageWidth, valueForLength(ninePieceImage.imageSlices().right(), imageWidth, renderView)) * imageScaleFactor;
1402 int bottomSlice = min<int>(imageHeight, valueForLength(ninePieceImage.imageSlices().bottom(), imageHeight, renderView)) * imageScaleFactor;
1403 int leftSlice = min<int>(imageWidth, valueForLength(ninePieceImage.imageSlices().left(), imageWidth, renderView)) * imageScaleFactor;
1405 ENinePieceImageRule hRule = ninePieceImage.horizontalRule();
1406 ENinePieceImageRule vRule = ninePieceImage.verticalRule();
1408 int topWidth = computeBorderImageSide(ninePieceImage.borderSlices().top(), style->borderTopWidth(), topSlice, borderImageRect.height(), renderView);
1409 int rightWidth = computeBorderImageSide(ninePieceImage.borderSlices().right(), style->borderRightWidth(), rightSlice, borderImageRect.width(), renderView);
1410 int bottomWidth = computeBorderImageSide(ninePieceImage.borderSlices().bottom(), style->borderBottomWidth(), bottomSlice, borderImageRect.height(), renderView);
1411 int leftWidth = computeBorderImageSide(ninePieceImage.borderSlices().left(), style->borderLeftWidth(), leftSlice, borderImageRect.width(), renderView);
1413 // Reduce the widths if they're too large.
1414 // The spec says: Given Lwidth as the width of the border image area, Lheight as its height, and Wside as the border image width
1415 // offset for the side, let f = min(Lwidth/(Wleft+Wright), Lheight/(Wtop+Wbottom)). If f < 1, then all W are reduced by
1416 // multiplying them by f.
1417 int borderSideWidth = max(1, leftWidth + rightWidth);
1418 int borderSideHeight = max(1, topWidth + bottomWidth);
1419 float borderSideScaleFactor = min((float)borderImageRect.width() / borderSideWidth, (float)borderImageRect.height() / borderSideHeight);
1420 if (borderSideScaleFactor < 1) {
1421 topWidth *= borderSideScaleFactor;
1422 rightWidth *= borderSideScaleFactor;
1423 bottomWidth *= borderSideScaleFactor;
1424 leftWidth *= borderSideScaleFactor;
1427 bool drawLeft = leftSlice > 0 && leftWidth > 0;
1428 bool drawTop = topSlice > 0 && topWidth > 0;
1429 bool drawRight = rightSlice > 0 && rightWidth > 0;
1430 bool drawBottom = bottomSlice > 0 && bottomWidth > 0;
1431 bool drawMiddle = ninePieceImage.fill() && (imageWidth - leftSlice - rightSlice) > 0 && (borderImageRect.width() - leftWidth - rightWidth) > 0
1432 && (imageHeight - topSlice - bottomSlice) > 0 && (borderImageRect.height() - topWidth - bottomWidth) > 0;
1434 RefPtr<Image> image = styleImage->image(this, imageSize);
1435 ColorSpace colorSpace = style->colorSpace();
1437 float destinationWidth = borderImageRect.width() - leftWidth - rightWidth;
1438 float destinationHeight = borderImageRect.height() - topWidth - bottomWidth;
1440 float sourceWidth = imageWidth - leftSlice - rightSlice;
1441 float sourceHeight = imageHeight - topSlice - bottomSlice;
1443 float leftSideScale = drawLeft ? (float)leftWidth / leftSlice : 1;
1444 float rightSideScale = drawRight ? (float)rightWidth / rightSlice : 1;
1445 float topSideScale = drawTop ? (float)topWidth / topSlice : 1;
1446 float bottomSideScale = drawBottom ? (float)bottomWidth / bottomSlice : 1;
1449 // Paint the top and bottom left corners.
1451 // The top left corner rect is (tx, ty, leftWidth, topWidth)
1452 // The rect to use from within the image is obtained from our slice, and is (0, 0, leftSlice, topSlice)
1454 graphicsContext->drawImage(image.get(), colorSpace, IntRect(borderImageRect.location(), IntSize(leftWidth, topWidth)),
1455 LayoutRect(0, 0, leftSlice, topSlice), op, ImageOrientationDescription());
1457 // The bottom left corner rect is (tx, ty + h - bottomWidth, leftWidth, bottomWidth)
1458 // The rect to use from within the image is (0, imageHeight - bottomSlice, leftSlice, botomSlice)
1460 graphicsContext->drawImage(image.get(), colorSpace, IntRect(borderImageRect.x(), borderImageRect.maxY() - bottomWidth, leftWidth, bottomWidth),
1461 LayoutRect(0, imageHeight - bottomSlice, leftSlice, bottomSlice), op, ImageOrientationDescription());
1463 // Paint the left edge.
1464 // Have to scale and tile into the border rect.
1465 if (sourceHeight > 0)
1466 graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(borderImageRect.x(), borderImageRect.y() + topWidth, leftWidth,
1468 IntRect(0, topSlice, leftSlice, sourceHeight),
1469 FloatSize(leftSideScale, leftSideScale), Image::StretchTile, (Image::TileRule)vRule, op);
1473 // Paint the top and bottom right corners
1474 // The top right corner rect is (tx + w - rightWidth, ty, rightWidth, topWidth)
1475 // The rect to use from within the image is obtained from our slice, and is (imageWidth - rightSlice, 0, rightSlice, topSlice)
1477 graphicsContext->drawImage(image.get(), colorSpace, IntRect(borderImageRect.maxX() - rightWidth, borderImageRect.y(), rightWidth, topWidth),
1478 LayoutRect(imageWidth - rightSlice, 0, rightSlice, topSlice), op, ImageOrientationDescription());
1480 // The bottom right corner rect is (tx + w - rightWidth, ty + h - bottomWidth, rightWidth, bottomWidth)
1481 // The rect to use from within the image is (imageWidth - rightSlice, imageHeight - bottomSlice, rightSlice, bottomSlice)
1483 graphicsContext->drawImage(image.get(), colorSpace, IntRect(borderImageRect.maxX() - rightWidth, borderImageRect.maxY() - bottomWidth, rightWidth, bottomWidth),
1484 LayoutRect(imageWidth - rightSlice, imageHeight - bottomSlice, rightSlice, bottomSlice), op, ImageOrientationDescription());
1486 // Paint the right edge.
1487 if (sourceHeight > 0)
1488 graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(borderImageRect.maxX() - rightWidth, borderImageRect.y() + topWidth, rightWidth,
1490 IntRect(imageWidth - rightSlice, topSlice, rightSlice, sourceHeight),
1491 FloatSize(rightSideScale, rightSideScale),
1492 Image::StretchTile, (Image::TileRule)vRule, op);
1495 // Paint the top edge.
1496 if (drawTop && sourceWidth > 0)
1497 graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(borderImageRect.x() + leftWidth, borderImageRect.y(), destinationWidth, topWidth),
1498 IntRect(leftSlice, 0, sourceWidth, topSlice),
1499 FloatSize(topSideScale, topSideScale), (Image::TileRule)hRule, Image::StretchTile, op);
1501 // Paint the bottom edge.
1502 if (drawBottom && sourceWidth > 0)
1503 graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(borderImageRect.x() + leftWidth, borderImageRect.maxY() - bottomWidth,
1504 destinationWidth, bottomWidth),
1505 IntRect(leftSlice, imageHeight - bottomSlice, sourceWidth, bottomSlice),
1506 FloatSize(bottomSideScale, bottomSideScale),
1507 (Image::TileRule)hRule, Image::StretchTile, op);
1509 // Paint the middle.
1511 FloatSize middleScaleFactor(1, 1);
1513 middleScaleFactor.setWidth(topSideScale);
1514 else if (drawBottom)
1515 middleScaleFactor.setWidth(bottomSideScale);
1517 middleScaleFactor.setHeight(leftSideScale);
1519 middleScaleFactor.setHeight(rightSideScale);
1521 // For "stretch" rules, just override the scale factor and replace. We only had to do this for the
1522 // center tile, since sides don't even use the scale factor unless they have a rule other than "stretch".
1523 // The middle however can have "stretch" specified in one axis but not the other, so we have to
1524 // correct the scale here.
1525 if (hRule == StretchImageRule)
1526 middleScaleFactor.setWidth(destinationWidth / sourceWidth);
1528 if (vRule == StretchImageRule)
1529 middleScaleFactor.setHeight(destinationHeight / sourceHeight);
1531 graphicsContext->drawTiledImage(image.get(), colorSpace,
1532 IntRect(borderImageRect.x() + leftWidth, borderImageRect.y() + topWidth, destinationWidth, destinationHeight),
1533 IntRect(leftSlice, topSlice, sourceWidth, sourceHeight),
1534 middleScaleFactor, (Image::TileRule)hRule, (Image::TileRule)vRule, op);
1542 BorderEdge(int edgeWidth, const Color& edgeColor, EBorderStyle edgeStyle, bool edgeIsTransparent, bool edgeIsPresent = true)
1546 , isTransparent(edgeIsTransparent)
1547 , isPresent(edgeIsPresent)
1549 if (style == DOUBLE && edgeWidth < 3)
1556 , isTransparent(false)
1561 bool hasVisibleColorAndStyle() const { return style > BHIDDEN && !isTransparent; }
1562 bool shouldRender() const { return isPresent && width && hasVisibleColorAndStyle(); }
1563 bool presentButInvisible() const { return usedWidth() && !hasVisibleColorAndStyle(); }
1564 bool obscuresBackgroundEdge(float scale) const
1566 if (!isPresent || isTransparent || (width * scale) < 2 || color.hasAlpha() || style == BHIDDEN)
1569 if (style == DOTTED || style == DASHED)
1572 if (style == DOUBLE)
1573 return width >= 5 * scale; // The outer band needs to be >= 2px wide at unit scale.
1577 bool obscuresBackground() const
1579 if (!isPresent || isTransparent || color.hasAlpha() || style == BHIDDEN)
1582 if (style == DOTTED || style == DASHED || style == DOUBLE)
1588 int usedWidth() const { return isPresent ? width : 0; }
1590 void getDoubleBorderStripeWidths(int& outerWidth, int& innerWidth) const
1592 int fullWidth = usedWidth();
1593 outerWidth = fullWidth / 3;
1594 innerWidth = fullWidth * 2 / 3;
1596 // We need certain integer rounding results
1597 if (fullWidth % 3 == 2)
1600 if (fullWidth % 3 == 1)
1611 static bool allCornersClippedOut(const RoundedRect& border, const LayoutRect& clipRect)
1613 LayoutRect boundingRect = border.rect();
1614 if (clipRect.contains(boundingRect))
1617 RoundedRect::Radii radii = border.radii();
1619 LayoutRect topLeftRect(boundingRect.location(), radii.topLeft());
1620 if (clipRect.intersects(topLeftRect))
1623 LayoutRect topRightRect(boundingRect.location(), radii.topRight());
1624 topRightRect.setX(boundingRect.maxX() - topRightRect.width());
1625 if (clipRect.intersects(topRightRect))
1628 LayoutRect bottomLeftRect(boundingRect.location(), radii.bottomLeft());
1629 bottomLeftRect.setY(boundingRect.maxY() - bottomLeftRect.height());
1630 if (clipRect.intersects(bottomLeftRect))
1633 LayoutRect bottomRightRect(boundingRect.location(), radii.bottomRight());
1634 bottomRightRect.setX(boundingRect.maxX() - bottomRightRect.width());
1635 bottomRightRect.setY(boundingRect.maxY() - bottomRightRect.height());
1636 if (clipRect.intersects(bottomRightRect))
1642 static bool borderWillArcInnerEdge(const LayoutSize& firstRadius, const FloatSize& secondRadius)
1644 return !firstRadius.isZero() || !secondRadius.isZero();
1647 enum BorderEdgeFlag {
1648 TopBorderEdge = 1 << BSTop,
1649 RightBorderEdge = 1 << BSRight,
1650 BottomBorderEdge = 1 << BSBottom,
1651 LeftBorderEdge = 1 << BSLeft,
1652 AllBorderEdges = TopBorderEdge | BottomBorderEdge | LeftBorderEdge | RightBorderEdge
1655 static inline BorderEdgeFlag edgeFlagForSide(BoxSide side)
1657 return static_cast<BorderEdgeFlag>(1 << side);
1660 static inline bool includesEdge(BorderEdgeFlags flags, BoxSide side)
1662 return flags & edgeFlagForSide(side);
1665 static inline bool includesAdjacentEdges(BorderEdgeFlags flags)
1667 return (flags & (TopBorderEdge | RightBorderEdge)) == (TopBorderEdge | RightBorderEdge)
1668 || (flags & (RightBorderEdge | BottomBorderEdge)) == (RightBorderEdge | BottomBorderEdge)
1669 || (flags & (BottomBorderEdge | LeftBorderEdge)) == (BottomBorderEdge | LeftBorderEdge)
1670 || (flags & (LeftBorderEdge | TopBorderEdge)) == (LeftBorderEdge | TopBorderEdge);
1673 inline bool edgesShareColor(const BorderEdge& firstEdge, const BorderEdge& secondEdge)
1675 return firstEdge.color == secondEdge.color;
1678 inline bool styleRequiresClipPolygon(EBorderStyle style)
1680 return style == DOTTED || style == DASHED; // These are drawn with a stroke, so we have to clip to get corner miters.
1683 static bool borderStyleFillsBorderArea(EBorderStyle style)
1685 return !(style == DOTTED || style == DASHED || style == DOUBLE);
1688 static bool borderStyleHasInnerDetail(EBorderStyle style)
1690 return style == GROOVE || style == RIDGE || style == DOUBLE;
1693 static bool borderStyleIsDottedOrDashed(EBorderStyle style)
1695 return style == DOTTED || style == DASHED;
1698 // OUTSET darkens the bottom and right (and maybe lightens the top and left)
1699 // INSET darkens the top and left (and maybe lightens the bottom and right)
1700 static inline bool borderStyleHasUnmatchedColorsAtCorner(EBorderStyle style, BoxSide side, BoxSide adjacentSide)
1702 // These styles match at the top/left and bottom/right.
1703 if (style == INSET || style == GROOVE || style == RIDGE || style == OUTSET) {
1704 const BorderEdgeFlags topRightFlags = edgeFlagForSide(BSTop) | edgeFlagForSide(BSRight);
1705 const BorderEdgeFlags bottomLeftFlags = edgeFlagForSide(BSBottom) | edgeFlagForSide(BSLeft);
1707 BorderEdgeFlags flags = edgeFlagForSide(side) | edgeFlagForSide(adjacentSide);
1708 return flags == topRightFlags || flags == bottomLeftFlags;
1713 static inline bool colorsMatchAtCorner(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1715 if (edges[side].shouldRender() != edges[adjacentSide].shouldRender())
1718 if (!edgesShareColor(edges[side], edges[adjacentSide]))
1721 return !borderStyleHasUnmatchedColorsAtCorner(edges[side].style, side, adjacentSide);
1725 static inline bool colorNeedsAntiAliasAtCorner(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1727 if (!edges[side].color.hasAlpha())
1730 if (edges[side].shouldRender() != edges[adjacentSide].shouldRender())
1733 if (!edgesShareColor(edges[side], edges[adjacentSide]))
1736 return borderStyleHasUnmatchedColorsAtCorner(edges[side].style, side, adjacentSide);
1739 // This assumes that we draw in order: top, bottom, left, right.
1740 static inline bool willBeOverdrawn(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1745 if (edges[adjacentSide].presentButInvisible())
1748 if (!edgesShareColor(edges[side], edges[adjacentSide]) && edges[adjacentSide].color.hasAlpha())
1751 if (!borderStyleFillsBorderArea(edges[adjacentSide].style))
1758 // These draw last, so are never overdrawn.
1764 static inline bool borderStylesRequireMitre(BoxSide side, BoxSide adjacentSide, EBorderStyle style, EBorderStyle adjacentStyle)
1766 if (style == DOUBLE || adjacentStyle == DOUBLE || adjacentStyle == GROOVE || adjacentStyle == RIDGE)
1769 if (borderStyleIsDottedOrDashed(style) != borderStyleIsDottedOrDashed(adjacentStyle))
1772 if (style != adjacentStyle)
1775 return borderStyleHasUnmatchedColorsAtCorner(style, side, adjacentSide);
1778 static bool joinRequiresMitre(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[], bool allowOverdraw)
1780 if ((edges[side].isTransparent && edges[adjacentSide].isTransparent) || !edges[adjacentSide].isPresent)
1783 if (allowOverdraw && willBeOverdrawn(side, adjacentSide, edges))
1786 if (!edgesShareColor(edges[side], edges[adjacentSide]))
1789 if (borderStylesRequireMitre(side, adjacentSide, edges[side].style, edges[adjacentSide].style))
1795 void RenderBoxModelObject::paintOneBorderSide(GraphicsContext* graphicsContext, const RenderStyle* style, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
1796 const IntRect& sideRect, BoxSide side, BoxSide adjacentSide1, BoxSide adjacentSide2, const BorderEdge edges[], const Path* path,
1797 BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias, const Color* overrideColor)
1799 const BorderEdge& edgeToRender = edges[side];
1800 ASSERT(edgeToRender.width);
1801 const BorderEdge& adjacentEdge1 = edges[adjacentSide1];
1802 const BorderEdge& adjacentEdge2 = edges[adjacentSide2];
1804 bool mitreAdjacentSide1 = joinRequiresMitre(side, adjacentSide1, edges, !antialias);
1805 bool mitreAdjacentSide2 = joinRequiresMitre(side, adjacentSide2, edges, !antialias);
1807 bool adjacentSide1StylesMatch = colorsMatchAtCorner(side, adjacentSide1, edges);
1808 bool adjacentSide2StylesMatch = colorsMatchAtCorner(side, adjacentSide2, edges);
1810 const Color& colorToPaint = overrideColor ? *overrideColor : edgeToRender.color;
1813 GraphicsContextStateSaver stateSaver(*graphicsContext);
1814 if (innerBorder.isRenderable())
1815 clipBorderSidePolygon(graphicsContext, outerBorder, innerBorder, side, adjacentSide1StylesMatch, adjacentSide2StylesMatch);
1817 clipBorderSideForComplexInnerPath(graphicsContext, outerBorder, innerBorder, side, edges);
1818 float thickness = max(max(edgeToRender.width, adjacentEdge1.width), adjacentEdge2.width);
1819 drawBoxSideFromPath(graphicsContext, outerBorder.rect(), *path, edges, edgeToRender.width, thickness, side, style,
1820 colorToPaint, edgeToRender.style, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
1822 bool clipForStyle = styleRequiresClipPolygon(edgeToRender.style) && (mitreAdjacentSide1 || mitreAdjacentSide2);
1823 bool clipAdjacentSide1 = colorNeedsAntiAliasAtCorner(side, adjacentSide1, edges) && mitreAdjacentSide1;
1824 bool clipAdjacentSide2 = colorNeedsAntiAliasAtCorner(side, adjacentSide2, edges) && mitreAdjacentSide2;
1825 bool shouldClip = clipForStyle || clipAdjacentSide1 || clipAdjacentSide2;
1827 GraphicsContextStateSaver clipStateSaver(*graphicsContext, shouldClip);
1829 bool aliasAdjacentSide1 = clipAdjacentSide1 || (clipForStyle && mitreAdjacentSide1);
1830 bool aliasAdjacentSide2 = clipAdjacentSide2 || (clipForStyle && mitreAdjacentSide2);
1831 clipBorderSidePolygon(graphicsContext, outerBorder, innerBorder, side, !aliasAdjacentSide1, !aliasAdjacentSide2);
1832 // Since we clipped, no need to draw with a mitre.
1833 mitreAdjacentSide1 = false;
1834 mitreAdjacentSide2 = false;
1837 drawLineForBoxSide(graphicsContext, sideRect.x(), sideRect.y(), sideRect.maxX(), sideRect.maxY(), side, colorToPaint, edgeToRender.style,
1838 mitreAdjacentSide1 ? adjacentEdge1.width : 0, mitreAdjacentSide2 ? adjacentEdge2.width : 0, antialias);
1842 static IntRect calculateSideRect(const RoundedRect& outerBorder, const BorderEdge edges[], int side)
1844 IntRect sideRect = outerBorder.rect();
1845 int width = edges[side].width;
1848 sideRect.setHeight(width);
1849 else if (side == BSBottom)
1850 sideRect.shiftYEdgeTo(sideRect.maxY() - width);
1851 else if (side == BSLeft)
1852 sideRect.setWidth(width);
1854 sideRect.shiftXEdgeTo(sideRect.maxX() - width);
1859 void RenderBoxModelObject::paintBorderSides(GraphicsContext* graphicsContext, const RenderStyle* style, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
1860 const IntPoint& innerBorderAdjustment, const BorderEdge edges[], BorderEdgeFlags edgeSet, BackgroundBleedAvoidance bleedAvoidance,
1861 bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias, const Color* overrideColor)
1863 bool renderRadii = outerBorder.isRounded();
1867 roundedPath.addRoundedRect(outerBorder);
1869 // The inner border adjustment for bleed avoidance mode BackgroundBleedBackgroundOverBorder
1870 // is only applied to sideRect, which is okay since BackgroundBleedBackgroundOverBorder
1871 // is only to be used for solid borders and the shape of the border painted by drawBoxSideFromPath
1872 // only depends on sideRect when painting solid borders.
1874 if (edges[BSTop].shouldRender() && includesEdge(edgeSet, BSTop)) {
1875 IntRect sideRect = outerBorder.rect();
1876 sideRect.setHeight(edges[BSTop].width + innerBorderAdjustment.y());
1878 bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSTop].style) || borderWillArcInnerEdge(innerBorder.radii().topLeft(), innerBorder.radii().topRight()));
1879 paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSTop, BSLeft, BSRight, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1882 if (edges[BSBottom].shouldRender() && includesEdge(edgeSet, BSBottom)) {
1883 IntRect sideRect = outerBorder.rect();
1884 sideRect.shiftYEdgeTo(sideRect.maxY() - edges[BSBottom].width - innerBorderAdjustment.y());
1886 bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSBottom].style) || borderWillArcInnerEdge(innerBorder.radii().bottomLeft(), innerBorder.radii().bottomRight()));
1887 paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSBottom, BSLeft, BSRight, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1890 if (edges[BSLeft].shouldRender() && includesEdge(edgeSet, BSLeft)) {
1891 IntRect sideRect = outerBorder.rect();
1892 sideRect.setWidth(edges[BSLeft].width + innerBorderAdjustment.x());
1894 bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSLeft].style) || borderWillArcInnerEdge(innerBorder.radii().bottomLeft(), innerBorder.radii().topLeft()));
1895 paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSLeft, BSTop, BSBottom, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1898 if (edges[BSRight].shouldRender() && includesEdge(edgeSet, BSRight)) {
1899 IntRect sideRect = outerBorder.rect();
1900 sideRect.shiftXEdgeTo(sideRect.maxX() - edges[BSRight].width - innerBorderAdjustment.x());
1902 bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSRight].style) || borderWillArcInnerEdge(innerBorder.radii().bottomRight(), innerBorder.radii().topRight()));
1903 paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSRight, BSTop, BSBottom, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1907 void RenderBoxModelObject::paintTranslucentBorderSides(GraphicsContext* graphicsContext, const RenderStyle* style, const RoundedRect& outerBorder, const RoundedRect& innerBorder, const IntPoint& innerBorderAdjustment,
1908 const BorderEdge edges[], BorderEdgeFlags edgesToDraw, BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias)
1910 // willBeOverdrawn assumes that we draw in order: top, bottom, left, right.
1911 // This is different from BoxSide enum order.
1912 static BoxSide paintOrder[] = { BSTop, BSBottom, BSLeft, BSRight };
1914 while (edgesToDraw) {
1915 // Find undrawn edges sharing a color.
1918 BorderEdgeFlags commonColorEdgeSet = 0;
1919 for (size_t i = 0; i < sizeof(paintOrder) / sizeof(paintOrder[0]); ++i) {
1920 BoxSide currSide = paintOrder[i];
1921 if (!includesEdge(edgesToDraw, currSide))
1925 if (!commonColorEdgeSet) {
1926 commonColor = edges[currSide].color;
1929 includeEdge = edges[currSide].color == commonColor;
1932 commonColorEdgeSet |= edgeFlagForSide(currSide);
1935 bool useTransparencyLayer = includesAdjacentEdges(commonColorEdgeSet) && commonColor.hasAlpha();
1936 if (useTransparencyLayer) {
1937 graphicsContext->beginTransparencyLayer(static_cast<float>(commonColor.alpha()) / 255);
1938 commonColor = Color(commonColor.red(), commonColor.green(), commonColor.blue());
1941 paintBorderSides(graphicsContext, style, outerBorder, innerBorder, innerBorderAdjustment, edges, commonColorEdgeSet, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, &commonColor);
1943 if (useTransparencyLayer)
1944 graphicsContext->endTransparencyLayer();
1946 edgesToDraw &= ~commonColorEdgeSet;
1950 void RenderBoxModelObject::paintBorder(const PaintInfo& info, const LayoutRect& rect, const RenderStyle* style,
1951 BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
1953 GraphicsContext* graphicsContext = info.context;
1954 // border-image is not affected by border-radius.
1955 if (paintNinePieceImage(graphicsContext, rect, style, style->borderImage()))
1958 if (graphicsContext->paintingDisabled())
1961 BorderEdge edges[4];
1962 getBorderEdgeInfo(edges, style, includeLogicalLeftEdge, includeLogicalRightEdge);
1963 RoundedRect outerBorder = style->getRoundedBorderFor(rect, &view(), includeLogicalLeftEdge, includeLogicalRightEdge);
1964 RoundedRect innerBorder = style->getRoundedInnerBorderFor(borderInnerRectAdjustedForBleedAvoidance(graphicsContext, rect, bleedAvoidance), includeLogicalLeftEdge, includeLogicalRightEdge);
1966 bool haveAlphaColor = false;
1967 bool haveAllSolidEdges = true;
1968 bool haveAllDoubleEdges = true;
1969 int numEdgesVisible = 4;
1970 bool allEdgesShareColor = true;
1971 int firstVisibleEdge = -1;
1972 BorderEdgeFlags edgesToDraw = 0;
1974 for (int i = BSTop; i <= BSLeft; ++i) {
1975 const BorderEdge& currEdge = edges[i];
1977 if (edges[i].shouldRender())
1978 edgesToDraw |= edgeFlagForSide(static_cast<BoxSide>(i));
1980 if (currEdge.presentButInvisible()) {
1982 allEdgesShareColor = false;
1986 if (!currEdge.width) {
1991 if (firstVisibleEdge == -1)
1992 firstVisibleEdge = i;
1993 else if (currEdge.color != edges[firstVisibleEdge].color)
1994 allEdgesShareColor = false;
1996 if (currEdge.color.hasAlpha())
1997 haveAlphaColor = true;
1999 if (currEdge.style != SOLID)
2000 haveAllSolidEdges = false;
2002 if (currEdge.style != DOUBLE)
2003 haveAllDoubleEdges = false;
2006 // If no corner intersects the clip region, we can pretend outerBorder is
2007 // rectangular to improve performance.
2008 if (haveAllSolidEdges && outerBorder.isRounded() && allCornersClippedOut(outerBorder, info.rect))
2009 outerBorder.setRadii(RoundedRect::Radii());
2011 // isRenderable() check avoids issue described in https://bugs.webkit.org/show_bug.cgi?id=38787
2012 if ((haveAllSolidEdges || haveAllDoubleEdges) && allEdgesShareColor && innerBorder.isRenderable()) {
2013 // Fast path for drawing all solid edges and all unrounded double edges
2014 if (numEdgesVisible == 4 && (outerBorder.isRounded() || haveAlphaColor)
2015 && (haveAllSolidEdges || (!outerBorder.isRounded() && !innerBorder.isRounded()))) {
2018 if (outerBorder.isRounded() && bleedAvoidance != BackgroundBleedUseTransparencyLayer)
2019 path.addRoundedRect(outerBorder);
2021 path.addRect(outerBorder.rect());
2023 if (haveAllDoubleEdges) {
2024 IntRect innerThirdRect = outerBorder.rect();
2025 IntRect outerThirdRect = outerBorder.rect();
2026 for (int side = BSTop; side <= BSLeft; ++side) {
2029 edges[side].getDoubleBorderStripeWidths(outerWidth, innerWidth);
2031 if (side == BSTop) {
2032 innerThirdRect.shiftYEdgeTo(innerThirdRect.y() + innerWidth);
2033 outerThirdRect.shiftYEdgeTo(outerThirdRect.y() + outerWidth);
2034 } else if (side == BSBottom) {
2035 innerThirdRect.setHeight(innerThirdRect.height() - innerWidth);
2036 outerThirdRect.setHeight(outerThirdRect.height() - outerWidth);
2037 } else if (side == BSLeft) {
2038 innerThirdRect.shiftXEdgeTo(innerThirdRect.x() + innerWidth);
2039 outerThirdRect.shiftXEdgeTo(outerThirdRect.x() + outerWidth);
2041 innerThirdRect.setWidth(innerThirdRect.width() - innerWidth);
2042 outerThirdRect.setWidth(outerThirdRect.width() - outerWidth);
2046 RoundedRect outerThird = outerBorder;
2047 RoundedRect innerThird = innerBorder;
2048 innerThird.setRect(innerThirdRect);
2049 outerThird.setRect(outerThirdRect);
2051 if (outerThird.isRounded() && bleedAvoidance != BackgroundBleedUseTransparencyLayer)
2052 path.addRoundedRect(outerThird);
2054 path.addRect(outerThird.rect());
2056 if (innerThird.isRounded() && bleedAvoidance != BackgroundBleedUseTransparencyLayer)
2057 path.addRoundedRect(innerThird);
2059 path.addRect(innerThird.rect());
2062 if (innerBorder.isRounded())
2063 path.addRoundedRect(innerBorder);
2065 path.addRect(innerBorder.rect());
2067 graphicsContext->setFillRule(RULE_EVENODD);
2068 graphicsContext->setFillColor(edges[firstVisibleEdge].color, style->colorSpace());
2069 graphicsContext->fillPath(path);
2072 // Avoid creating transparent layers
2073 if (haveAllSolidEdges && numEdgesVisible != 4 && !outerBorder.isRounded() && haveAlphaColor) {
2076 for (int i = BSTop; i <= BSLeft; ++i) {
2077 const BorderEdge& currEdge = edges[i];
2078 if (currEdge.shouldRender()) {
2079 IntRect sideRect = calculateSideRect(outerBorder, edges, i);
2080 path.addRect(sideRect);
2084 graphicsContext->setFillRule(RULE_NONZERO);
2085 graphicsContext->setFillColor(edges[firstVisibleEdge].color, style->colorSpace());
2086 graphicsContext->fillPath(path);
2091 bool clipToOuterBorder = outerBorder.isRounded();
2092 GraphicsContextStateSaver stateSaver(*graphicsContext, clipToOuterBorder);
2093 if (clipToOuterBorder) {
2094 // Clip to the inner and outer radii rects.
2095 if (bleedAvoidance != BackgroundBleedUseTransparencyLayer)
2096 graphicsContext->clipRoundedRect(outerBorder);
2097 // isRenderable() check avoids issue described in https://bugs.webkit.org/show_bug.cgi?id=38787
2098 // The inside will be clipped out later (in clipBorderSideForComplexInnerPath)
2099 if (innerBorder.isRenderable())
2100 graphicsContext->clipOutRoundedRect(innerBorder);
2103 // If only one edge visible antialiasing doesn't create seams
2104 bool antialias = shouldAntialiasLines(graphicsContext) || numEdgesVisible == 1;
2105 RoundedRect unadjustedInnerBorder = (bleedAvoidance == BackgroundBleedBackgroundOverBorder) ? style->getRoundedInnerBorderFor(rect, includeLogicalLeftEdge, includeLogicalRightEdge) : innerBorder;
2106 IntPoint innerBorderAdjustment(innerBorder.rect().x() - unadjustedInnerBorder.rect().x(), innerBorder.rect().y() - unadjustedInnerBorder.rect().y());
2108 paintTranslucentBorderSides(graphicsContext, style, outerBorder, unadjustedInnerBorder, innerBorderAdjustment, edges, edgesToDraw, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias);
2110 paintBorderSides(graphicsContext, style, outerBorder, unadjustedInnerBorder, innerBorderAdjustment, edges, edgesToDraw, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias);
2113 void RenderBoxModelObject::drawBoxSideFromPath(GraphicsContext* graphicsContext, const LayoutRect& borderRect, const Path& borderPath, const BorderEdge edges[],
2114 float thickness, float drawThickness, BoxSide side, const RenderStyle* style,
2115 Color color, EBorderStyle borderStyle, BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
2120 if (borderStyle == DOUBLE && thickness < 3)
2121 borderStyle = SOLID;
2123 switch (borderStyle) {
2129 graphicsContext->setStrokeColor(color, style->colorSpace());
2131 // The stroke is doubled here because the provided path is the
2132 // outside edge of the border so half the stroke is clipped off.
2133 // The extra multiplier is so that the clipping mask can antialias
2134 // the edges to prevent jaggies.
2135 graphicsContext->setStrokeThickness(drawThickness * 2 * 1.1f);
2136 graphicsContext->setStrokeStyle(borderStyle == DASHED ? DashedStroke : DottedStroke);
2138 // If the number of dashes that fit in the path is odd and non-integral then we
2139 // will have an awkwardly-sized dash at the end of the path. To try to avoid that
2140 // here, we simply make the whitespace dashes ever so slightly bigger.
2141 // FIXME: This could be even better if we tried to manipulate the dash offset
2142 // and possibly the gapLength to get the corners dash-symmetrical.
2143 float dashLength = thickness * ((borderStyle == DASHED) ? 3.0f : 1.0f);
2144 float gapLength = dashLength;
2145 float numberOfDashes = borderPath.length() / dashLength;
2146 // Don't try to show dashes if we have less than 2 dashes + 2 gaps.
2147 // FIXME: should do this test per side.
2148 if (numberOfDashes >= 4) {
2149 bool evenNumberOfFullDashes = !((int)numberOfDashes % 2);
2150 bool integralNumberOfDashes = !(numberOfDashes - (int)numberOfDashes);
2151 if (!evenNumberOfFullDashes && !integralNumberOfDashes) {
2152 float numberOfGaps = numberOfDashes / 2;
2153 gapLength += (dashLength / numberOfGaps);
2157 lineDash.append(dashLength);
2158 lineDash.append(gapLength);
2159 graphicsContext->setLineDash(lineDash, dashLength);
2162 // FIXME: stroking the border path causes issues with tight corners:
2163 // https://bugs.webkit.org/show_bug.cgi?id=58711
2164 // Also, to get the best appearance we should stroke a path between the two borders.
2165 graphicsContext->strokePath(borderPath);
2169 // Get the inner border rects for both the outer border line and the inner border line
2170 int outerBorderTopWidth;
2171 int innerBorderTopWidth;
2172 edges[BSTop].getDoubleBorderStripeWidths(outerBorderTopWidth, innerBorderTopWidth);
2174 int outerBorderRightWidth;
2175 int innerBorderRightWidth;
2176 edges[BSRight].getDoubleBorderStripeWidths(outerBorderRightWidth, innerBorderRightWidth);
2178 int outerBorderBottomWidth;
2179 int innerBorderBottomWidth;
2180 edges[BSBottom].getDoubleBorderStripeWidths(outerBorderBottomWidth, innerBorderBottomWidth);
2182 int outerBorderLeftWidth;
2183 int innerBorderLeftWidth;
2184 edges[BSLeft].getDoubleBorderStripeWidths(outerBorderLeftWidth, innerBorderLeftWidth);
2186 // Draw inner border line
2188 GraphicsContextStateSaver stateSaver(*graphicsContext);
2189 RoundedRect innerClip = style->getRoundedInnerBorderFor(borderRect,
2190 innerBorderTopWidth, innerBorderBottomWidth, innerBorderLeftWidth, innerBorderRightWidth,
2191 includeLogicalLeftEdge, includeLogicalRightEdge);
2193 graphicsContext->clipRoundedRect(innerClip);
2194 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, SOLID, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
2197 // Draw outer border line
2199 GraphicsContextStateSaver stateSaver(*graphicsContext);
2200 LayoutRect outerRect = borderRect;
2201 if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
2202 outerRect.inflate(1);
2203 ++outerBorderTopWidth;
2204 ++outerBorderBottomWidth;
2205 ++outerBorderLeftWidth;
2206 ++outerBorderRightWidth;
2209 RoundedRect outerClip = style->getRoundedInnerBorderFor(outerRect,
2210 outerBorderTopWidth, outerBorderBottomWidth, outerBorderLeftWidth, outerBorderRightWidth,
2211 includeLogicalLeftEdge, includeLogicalRightEdge);
2212 graphicsContext->clipOutRoundedRect(outerClip);
2213 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, SOLID, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
2222 if (borderStyle == GROOVE) {
2230 // Paint full border
2231 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, s1, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
2234 GraphicsContextStateSaver stateSaver(*graphicsContext);
2235 LayoutUnit topWidth = edges[BSTop].usedWidth() / 2;
2236 LayoutUnit bottomWidth = edges[BSBottom].usedWidth() / 2;
2237 LayoutUnit leftWidth = edges[BSLeft].usedWidth() / 2;
2238 LayoutUnit rightWidth = edges[BSRight].usedWidth() / 2;
2240 RoundedRect clipRect = style->getRoundedInnerBorderFor(borderRect,
2241 topWidth, bottomWidth, leftWidth, rightWidth,
2242 includeLogicalLeftEdge, includeLogicalRightEdge);
2244 graphicsContext->clipRoundedRect(clipRect);
2245 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, s2, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
2249 if (side == BSTop || side == BSLeft)
2250 color = color.dark();
2253 if (side == BSBottom || side == BSRight)
2254 color = color.dark();
2260 graphicsContext->setStrokeStyle(NoStroke);
2261 graphicsContext->setFillColor(color, style->colorSpace());
2262 graphicsContext->drawRect(pixelSnappedIntRect(borderRect));
2265 static void findInnerVertex(const FloatPoint& outerCorner, const FloatPoint& innerCorner, const FloatPoint& centerPoint, FloatPoint& result)
2267 // If the line between outer and inner corner is towards the horizontal, intersect with a vertical line through the center,
2268 // otherwise with a horizontal line through the center. The points that form this line are arbitrary (we use 0, 100).
2269 // Note that if findIntersection fails, it will leave result untouched.
2270 float diffInnerOuterX = fabs(innerCorner.x() - outerCorner.x());
2271 float diffInnerOuterY = fabs(innerCorner.y() - outerCorner.y());
2272 float diffCenterOuterX = fabs(centerPoint.x() - outerCorner.x());
2273 float diffCenterOuterY = fabs(centerPoint.y() - outerCorner.y());
2274 if (diffInnerOuterY * diffCenterOuterX < diffCenterOuterY * diffInnerOuterX)
2275 findIntersection(outerCorner, innerCorner, FloatPoint(centerPoint.x(), 0), FloatPoint(centerPoint.x(), 100), result);
2277 findIntersection(outerCorner, innerCorner, FloatPoint(0, centerPoint.y()), FloatPoint(100, centerPoint.y()), result);
2280 void RenderBoxModelObject::clipBorderSidePolygon(GraphicsContext* graphicsContext, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
2281 BoxSide side, bool firstEdgeMatches, bool secondEdgeMatches)
2285 const LayoutRect& outerRect = outerBorder.rect();
2286 const LayoutRect& innerRect = innerBorder.rect();
2288 FloatPoint centerPoint(innerRect.location().x() + static_cast<float>(innerRect.width()) / 2, innerRect.location().y() + static_cast<float>(innerRect.height()) / 2);
2290 // For each side, create a quad that encompasses all parts of that side that may draw,
2291 // including areas inside the innerBorder.
2293 // 0----------------3
2295 // |\ 1----------- 2 /|
2300 // |/ 1------------2 \|
2302 // 0----------------3
2306 quad[0] = outerRect.minXMinYCorner();
2307 quad[1] = innerRect.minXMinYCorner();
2308 quad[2] = innerRect.maxXMinYCorner();
2309 quad[3] = outerRect.maxXMinYCorner();
2311 if (!innerBorder.radii().topLeft().isZero())
2312 findInnerVertex(outerRect.minXMinYCorner(), innerRect.minXMinYCorner(), centerPoint, quad[1]);
2314 if (!innerBorder.radii().topRight().isZero())
2315 findInnerVertex(outerRect.maxXMinYCorner(), innerRect.maxXMinYCorner(), centerPoint, quad[2]);
2319 quad[0] = outerRect.minXMinYCorner();
2320 quad[1] = innerRect.minXMinYCorner();
2321 quad[2] = innerRect.minXMaxYCorner();
2322 quad[3] = outerRect.minXMaxYCorner();
2324 if (!innerBorder.radii().topLeft().isZero())
2325 findInnerVertex(outerRect.minXMinYCorner(), innerRect.minXMinYCorner(), centerPoint, quad[1]);
2327 if (!innerBorder.radii().bottomLeft().isZero())
2328 findInnerVertex(outerRect.minXMaxYCorner(), innerRect.minXMaxYCorner(), centerPoint, quad[2]);
2332 quad[0] = outerRect.minXMaxYCorner();
2333 quad[1] = innerRect.minXMaxYCorner();
2334 quad[2] = innerRect.maxXMaxYCorner();
2335 quad[3] = outerRect.maxXMaxYCorner();
2337 if (!innerBorder.radii().bottomLeft().isZero())
2338 findInnerVertex(outerRect.minXMaxYCorner(), innerRect.minXMaxYCorner(), centerPoint, quad[1]);
2340 if (!innerBorder.radii().bottomRight().isZero())
2341 findInnerVertex(outerRect.maxXMaxYCorner(), innerRect.maxXMaxYCorner(), centerPoint, quad[2]);
2345 quad[0] = outerRect.maxXMinYCorner();
2346 quad[1] = innerRect.maxXMinYCorner();
2347 quad[2] = innerRect.maxXMaxYCorner();
2348 quad[3] = outerRect.maxXMaxYCorner();
2350 if (!innerBorder.radii().topRight().isZero())
2351 findInnerVertex(outerRect.maxXMinYCorner(), innerRect.maxXMinYCorner(), centerPoint, quad[1]);
2353 if (!innerBorder.radii().bottomRight().isZero())
2354 findInnerVertex(outerRect.maxXMaxYCorner(), innerRect.maxXMaxYCorner(), centerPoint, quad[2]);
2358 // If the border matches both of its adjacent sides, don't anti-alias the clip, and
2359 // if neither side matches, anti-alias the clip.
2360 if (firstEdgeMatches == secondEdgeMatches) {
2361 graphicsContext->clipConvexPolygon(4, quad, !firstEdgeMatches);
2365 // Square off the end which shouldn't be affected by antialiasing, and clip.
2366 FloatPoint firstQuad[4];
2367 firstQuad[0] = quad[0];
2368 firstQuad[1] = quad[1];
2369 firstQuad[2] = side == BSTop || side == BSBottom ? FloatPoint(quad[3].x(), quad[2].y())
2370 : FloatPoint(quad[2].x(), quad[3].y());
2371 firstQuad[3] = quad[3];
2372 graphicsContext->clipConvexPolygon(4, firstQuad, !firstEdgeMatches);
2374 FloatPoint secondQuad[4];
2375 secondQuad[0] = quad[0];
2376 secondQuad[1] = side == BSTop || side == BSBottom ? FloatPoint(quad[0].x(), quad[1].y())
2377 : FloatPoint(quad[1].x(), quad[0].y());
2378 secondQuad[2] = quad[2];
2379 secondQuad[3] = quad[3];
2380 // Antialiasing affects the second side.
2381 graphicsContext->clipConvexPolygon(4, secondQuad, !secondEdgeMatches);
2384 static IntRect calculateSideRectIncludingInner(const RoundedRect& outerBorder, const BorderEdge edges[], BoxSide side)
2386 IntRect sideRect = outerBorder.rect();
2391 width = sideRect.height() - edges[BSBottom].width;
2392 sideRect.setHeight(width);
2395 width = sideRect.height() - edges[BSTop].width;
2396 sideRect.shiftYEdgeTo(sideRect.maxY() - width);
2399 width = sideRect.width() - edges[BSRight].width;
2400 sideRect.setWidth(width);
2403 width = sideRect.width() - edges[BSLeft].width;
2404 sideRect.shiftXEdgeTo(sideRect.maxX() - width);
2411 static RoundedRect calculateAdjustedInnerBorder(const RoundedRect&innerBorder, BoxSide side)
2413 // Expand the inner border as necessary to make it a rounded rect (i.e. radii contained within each edge).
2414 // This function relies on the fact we only get radii not contained within each edge if one of the radii
2415 // for an edge is zero, so we can shift the arc towards the zero radius corner.
2416 RoundedRect::Radii newRadii = innerBorder.radii();
2417 IntRect newRect = innerBorder.rect();
2424 overshoot = newRadii.topLeft().width() + newRadii.topRight().width() - newRect.width();
2425 if (overshoot > 0) {
2426 ASSERT(!(newRadii.topLeft().width() && newRadii.topRight().width()));
2427 newRect.setWidth(newRect.width() + overshoot);
2428 if (!newRadii.topLeft().width())
2429 newRect.move(-overshoot, 0);
2431 newRadii.setBottomLeft(IntSize(0, 0));
2432 newRadii.setBottomRight(IntSize(0, 0));
2433 maxRadii = max(newRadii.topLeft().height(), newRadii.topRight().height());
2434 if (maxRadii > newRect.height())
2435 newRect.setHeight(maxRadii);
2439 overshoot = newRadii.bottomLeft().width() + newRadii.bottomRight().width() - newRect.width();
2440 if (overshoot > 0) {
2441 ASSERT(!(newRadii.bottomLeft().width() && newRadii.bottomRight().width()));
2442 newRect.setWidth(newRect.width() + overshoot);
2443 if (!newRadii.bottomLeft().width())
2444 newRect.move(-overshoot, 0);
2446 newRadii.setTopLeft(IntSize(0, 0));
2447 newRadii.setTopRight(IntSize(0, 0));
2448 maxRadii = max(newRadii.bottomLeft().height(), newRadii.bottomRight().height());
2449 if (maxRadii > newRect.height()) {
2450 newRect.move(0, newRect.height() - maxRadii);
2451 newRect.setHeight(maxRadii);
2456 overshoot = newRadii.topLeft().height() + newRadii.bottomLeft().height() - newRect.height();
2457 if (overshoot > 0) {
2458 ASSERT(!(newRadii.topLeft().height() && newRadii.bottomLeft().height()));
2459 newRect.setHeight(newRect.height() + overshoot);
2460 if (!newRadii.topLeft().height())
2461 newRect.move(0, -overshoot);
2463 newRadii.setTopRight(IntSize(0, 0));
2464 newRadii.setBottomRight(IntSize(0, 0));
2465 maxRadii = max(newRadii.topLeft().width(), newRadii.bottomLeft().width());
2466 if (maxRadii > newRect.width())
2467 newRect.setWidth(maxRadii);
2471 overshoot = newRadii.topRight().height() + newRadii.bottomRight().height() - newRect.height();
2472 if (overshoot > 0) {
2473 ASSERT(!(newRadii.topRight().height() && newRadii.bottomRight().height()));
2474 newRect.setHeight(newRect.height() + overshoot);
2475 if (!newRadii.topRight().height())
2476 newRect.move(0, -overshoot);
2478 newRadii.setTopLeft(IntSize(0, 0));
2479 newRadii.setBottomLeft(IntSize(0, 0));
2480 maxRadii = max(newRadii.topRight().width(), newRadii.bottomRight().width());
2481 if (maxRadii > newRect.width()) {
2482 newRect.move(newRect.width() - maxRadii, 0);
2483 newRect.setWidth(maxRadii);
2488 return RoundedRect(newRect, newRadii);
2491 void RenderBoxModelObject::clipBorderSideForComplexInnerPath(GraphicsContext* graphicsContext, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
2492 BoxSide side, const class BorderEdge edges[])
2494 graphicsContext->clip(calculateSideRectIncludingInner(outerBorder, edges, side));
2495 graphicsContext->clipOutRoundedRect(calculateAdjustedInnerBorder(innerBorder, side));
2498 void RenderBoxModelObject::getBorderEdgeInfo(BorderEdge edges[], const RenderStyle* style, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
2500 bool horizontal = style->isHorizontalWritingMode();
2502 edges[BSTop] = BorderEdge(style->borderTopWidth(),
2503 style->visitedDependentColor(CSSPropertyBorderTopColor),
2504 style->borderTopStyle(),
2505 style->borderTopIsTransparent(),
2506 horizontal || includeLogicalLeftEdge);
2508 edges[BSRight] = BorderEdge(style->borderRightWidth(),
2509 style->visitedDependentColor(CSSPropertyBorderRightColor),
2510 style->borderRightStyle(),
2511 style->borderRightIsTransparent(),
2512 !horizontal || includeLogicalRightEdge);
2514 edges[BSBottom] = BorderEdge(style->borderBottomWidth(),
2515 style->visitedDependentColor(CSSPropertyBorderBottomColor),
2516 style->borderBottomStyle(),
2517 style->borderBottomIsTransparent(),
2518 horizontal || includeLogicalRightEdge);
2520 edges[BSLeft] = BorderEdge(style->borderLeftWidth(),
2521 style->visitedDependentColor(CSSPropertyBorderLeftColor),
2522 style->borderLeftStyle(),
2523 style->borderLeftIsTransparent(),
2524 !horizontal || includeLogicalLeftEdge);
2527 bool RenderBoxModelObject::borderObscuresBackgroundEdge(const FloatSize& contextScale) const
2529 BorderEdge edges[4];
2530 getBorderEdgeInfo(edges, style());
2532 for (int i = BSTop; i <= BSLeft; ++i) {
2533 const BorderEdge& currEdge = edges[i];
2534 // FIXME: for vertical text
2535 float axisScale = (i == BSTop || i == BSBottom) ? contextScale.height() : contextScale.width();
2536 if (!currEdge.obscuresBackgroundEdge(axisScale))
2543 bool RenderBoxModelObject::borderObscuresBackground() const
2545 if (!style()->hasBorder())
2548 // Bail if we have any border-image for now. We could look at the image alpha to improve this.
2549 if (style()->borderImage().image())
2552 BorderEdge edges[4];
2553 getBorderEdgeInfo(edges, style());
2555 for (int i = BSTop; i <= BSLeft; ++i) {
2556 const BorderEdge& currEdge = edges[i];
2557 if (!currEdge.obscuresBackground())
2564 bool RenderBoxModelObject::boxShadowShouldBeAppliedToBackground(BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* inlineFlowBox) const
2566 if (bleedAvoidance != BackgroundBleedNone)
2569 if (style()->hasAppearance())
2572 bool hasOneNormalBoxShadow = false;
2573 for (const ShadowData* currentShadow = style()->boxShadow(); currentShadow; currentShadow = currentShadow->next()) {
2574 if (currentShadow->style() != Normal)
2577 if (hasOneNormalBoxShadow)
2579 hasOneNormalBoxShadow = true;
2581 if (currentShadow->spread())
2585 if (!hasOneNormalBoxShadow)
2588 Color backgroundColor = style()->visitedDependentColor(CSSPropertyBackgroundColor);
2589 if (!backgroundColor.isValid() || backgroundColor.hasAlpha())
2592 const FillLayer* lastBackgroundLayer = style()->backgroundLayers();
2593 for (const FillLayer* next = lastBackgroundLayer->next(); next; next = lastBackgroundLayer->next())
2594 lastBackgroundLayer = next;
2596 if (lastBackgroundLayer->clip() != BorderFillBox)
2599 if (lastBackgroundLayer->image() && style()->hasBorderRadius())
2602 if (inlineFlowBox && !inlineFlowBox->boxShadowCanBeAppliedToBackground(*lastBackgroundLayer))
2605 if (hasOverflowClip() && lastBackgroundLayer->attachment() == LocalBackgroundAttachment)
2611 static inline IntRect areaCastingShadowInHole(const IntRect& holeRect, int shadowExtent, int shadowSpread, const IntSize& shadowOffset)
2613 IntRect bounds(holeRect);
2615 bounds.inflate(shadowExtent);
2617 if (shadowSpread < 0)
2618 bounds.inflate(-shadowSpread);
2620 IntRect offsetBounds = bounds;
2621 offsetBounds.move(-shadowOffset);
2622 return unionRect(bounds, offsetBounds);
2625 void RenderBoxModelObject::paintBoxShadow(const PaintInfo& info, const LayoutRect& paintRect, const RenderStyle* s, ShadowStyle shadowStyle, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
2627 // FIXME: Deal with border-image. Would be great to use border-image as a mask.
2628 GraphicsContext* context = info.context;
2629 if (context->paintingDisabled() || !s->boxShadow())
2632 RoundedRect border = (shadowStyle == Inset)
2633 ? s->getRoundedInnerBorderFor(paintRect, includeLogicalLeftEdge, includeLogicalRightEdge)
2634 : s->getRoundedBorderFor(paintRect, &view(), includeLogicalLeftEdge, includeLogicalRightEdge);
2636 bool hasBorderRadius = s->hasBorderRadius();
2637 bool isHorizontal = s->isHorizontalWritingMode();
2639 bool hasOpaqueBackground = s->visitedDependentColor(CSSPropertyBackgroundColor).isValid() && s->visitedDependentColor(CSSPropertyBackgroundColor).alpha() == 255;
2640 for (const ShadowData* shadow = s->boxShadow(); shadow; shadow = shadow->next()) {
2641 if (shadow->style() != shadowStyle)
2644 IntSize shadowOffset(shadow->x(), shadow->y());
2645 int shadowRadius = shadow->radius();
2646 int shadowPaintingExtent = shadow->paintingExtent();
2647 int shadowSpread = shadow->spread();
2649 if (shadowOffset.isZero() && !shadowRadius && !shadowSpread)
2652 const Color& shadowColor = shadow->color();
2654 if (shadow->style() == Normal) {
2655 RoundedRect fillRect = border;
2656 fillRect.inflate(shadowSpread);
2657 if (fillRect.isEmpty())
2660 IntRect shadowRect(border.rect());
2661 shadowRect.inflate(shadowPaintingExtent + shadowSpread);
2662 shadowRect.move(shadowOffset);
2664 GraphicsContextStateSaver stateSaver(*context);
2665 context->clip(shadowRect);
2667 // Move the fill just outside the clip, adding 1 pixel separation so that the fill does not
2668 // bleed in (due to antialiasing) if the context is transformed.
2669 IntSize extraOffset(paintRect.pixelSnappedWidth() + max(0, shadowOffset.width()) + shadowPaintingExtent + 2 * shadowSpread + 1, 0);
2670 shadowOffset -= extraOffset;
2671 fillRect.move(extraOffset);
2673 if (shadow->isWebkitBoxShadow())
2674 context->setLegacyShadow(shadowOffset, shadowRadius, shadowColor, s->colorSpace());
2676 context->setShadow(shadowOffset, shadowRadius, shadowColor, s->colorSpace());
2678 if (hasBorderRadius) {
2679 RoundedRect rectToClipOut = border;
2681 // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
2682 // when painting the shadow. On the other hand, it introduces subpixel gaps along the
2683 // corners. Those are avoided by insetting the clipping path by one pixel.
2684 if (hasOpaqueBackground) {
2685 rectToClipOut.inflateWithRadii(-1);
2688 if (!rectToClipOut.isEmpty())
2689 context->clipOutRoundedRect(rectToClipOut);
2691 RoundedRect influenceRect(shadowRect, border.radii());
2692 influenceRect.expandRadii(2 * shadowPaintingExtent + shadowSpread);
2693 if (allCornersClippedOut(influenceRect, info.rect))
2694 context->fillRect(fillRect.rect(), Color::black, s->colorSpace());
2696 fillRect.expandRadii(shadowSpread);
2697 if (!fillRect.isRenderable())
2698 fillRect.adjustRadii();
2699 context->fillRoundedRect(fillRect, Color::black, s->colorSpace());
2702 IntRect rectToClipOut = border.rect();
2704 // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
2705 // when painting the shadow. On the other hand, it introduces subpixel gaps along the
2706 // edges if they are not pixel-aligned. Those are avoided by insetting the clipping path
2708 if (hasOpaqueBackground) {
2709 // FIXME: The function to decide on the policy based on the transform should be a named function.
2710 // FIXME: It's not clear if this check is right. What about integral scale factors?
2711 AffineTransform transform = context->getCTM();
2712 if (transform.a() != 1 || (transform.d() != 1 && transform.d() != -1) || transform.b() || transform.c())
2713 rectToClipOut.inflate(-1);
2716 if (!rectToClipOut.isEmpty())
2717 context->clipOut(rectToClipOut);
2718 context->fillRect(fillRect.rect(), Color::black, s->colorSpace());
2722 IntRect holeRect(border.rect());
2723 holeRect.inflate(-shadowSpread);
2725 if (holeRect.isEmpty()) {
2726 if (hasBorderRadius)
2727 context->fillRoundedRect(border, shadowColor, s->colorSpace());
2729 context->fillRect(border.rect(), shadowColor, s->colorSpace());
2733 if (!includeLogicalLeftEdge) {
2735 holeRect.move(-max(shadowOffset.width(), 0) - shadowPaintingExtent, 0);
2736 holeRect.setWidth(holeRect.width() + max(shadowOffset.width(), 0) + shadowPaintingExtent);
2738 holeRect.move(0, -max(shadowOffset.height(), 0) - shadowPaintingExtent);
2739 holeRect.setHeight(holeRect.height() + max(shadowOffset.height(), 0) + shadowPaintingExtent);
2742 if (!includeLogicalRightEdge) {
2744 holeRect.setWidth(holeRect.width() - min(shadowOffset.width(), 0) + shadowPaintingExtent);
2746 holeRect.setHeight(holeRect.height() - min(shadowOffset.height(), 0) + shadowPaintingExtent);
2749 Color fillColor(shadowColor.red(), shadowColor.green(), shadowColor.blue(), 255);
2751 IntRect outerRect = areaCastingShadowInHole(border.rect(), shadowPaintingExtent, shadowSpread, shadowOffset);
2752 RoundedRect roundedHole(holeRect, border.radii());
2754 GraphicsContextStateSaver stateSaver(*context);
2755 if (hasBorderRadius) {
2757 path.addRoundedRect(border);
2758 context->clip(path);
2759 roundedHole.shrinkRadii(shadowSpread);
2761 context->clip(border.rect());
2763 IntSize extraOffset(2 * paintRect.pixelSnappedWidth() + max(0, shadowOffset.width()) + shadowPaintingExtent - 2 * shadowSpread + 1, 0);
2764 context->translate(extraOffset.width(), extraOffset.height());
2765 shadowOffset -= extraOffset;
2767 if (shadow->isWebkitBoxShadow())
2768 context->setLegacyShadow(shadowOffset, shadowRadius, shadowColor, s->colorSpace());
2770 context->setShadow(shadowOffset, shadowRadius, shadowColor, s->colorSpace());
2772 context->fillRectWithRoundedHole(outerRect, roundedHole, fillColor, s->colorSpace());
2777 LayoutUnit RenderBoxModelObject::containingBlockLogicalWidthForContent() const
2779 return containingBlock()->availableLogicalWidth();
2782 RenderBoxModelObject* RenderBoxModelObject::continuation() const
2784 if (!continuationMap)
2786 return continuationMap->get(this);
2789 void RenderBoxModelObject::setContinuation(RenderBoxModelObject* continuation)
2792 if (!continuationMap)
2793 continuationMap = new ContinuationMap;
2794 continuationMap->set(this, continuation);
2796 if (continuationMap)
2797 continuationMap->remove(this);
2801 RenderTextFragment* RenderBoxModelObject::firstLetterRemainingText() const
2803 if (!firstLetterRemainingTextMap)
2805 return firstLetterRemainingTextMap->get(this);
2808 void RenderBoxModelObject::setFirstLetterRemainingText(RenderTextFragment* remainingText)
2810 if (remainingText) {
2811 if (!firstLetterRemainingTextMap)
2812 firstLetterRemainingTextMap = new FirstLetterRemainingTextMap;
2813 firstLetterRemainingTextMap->set(this, remainingText);
2814 } else if (firstLetterRemainingTextMap)
2815 firstLetterRemainingTextMap->remove(this);
2818 LayoutRect RenderBoxModelObject::localCaretRectForEmptyElement(LayoutUnit width, LayoutUnit textIndentOffset)
2820 ASSERT(!firstChild());
2822 // FIXME: This does not take into account either :first-line or :first-letter
2823 // However, as soon as some content is entered, the line boxes will be
2824 // constructed and this kludge is not called any more. So only the caret size
2825 // of an empty :first-line'd block is wrong. I think we can live with that.
2826 RenderStyle* currentStyle = firstLineStyle();
2827 LayoutUnit height = lineHeight(true, currentStyle->isHorizontalWritingMode() ? HorizontalLine : VerticalLine);
2829 enum CaretAlignment { alignLeft, alignRight, alignCenter };
2831 CaretAlignment alignment = alignLeft;
2833 switch (currentStyle->textAlign()) {
2839 alignment = alignCenter;
2843 alignment = alignRight;
2847 if (!currentStyle->isLeftToRightDirection())
2848 alignment = alignRight;
2851 if (currentStyle->isLeftToRightDirection())
2852 alignment = alignRight;
2856 LayoutUnit x = borderLeft() + paddingLeft();
2857 LayoutUnit maxX = width - borderRight() - paddingRight();
2859 switch (alignment) {
2861 if (currentStyle->isLeftToRightDirection())
2862 x += textIndentOffset;
2866 if (currentStyle->isLeftToRightDirection())
2867 x += textIndentOffset / 2;
2869 x -= textIndentOffset / 2;
2872 x = maxX - caretWidth;
2873 if (!currentStyle->isLeftToRightDirection())
2874 x -= textIndentOffset;
2877 x = min(x, max<LayoutUnit>(maxX - caretWidth, 0));
2879 LayoutUnit y = paddingTop() + borderTop();
2881 return currentStyle->isHorizontalWritingMode() ? LayoutRect(x, y, caretWidth, height) : LayoutRect(y, x, height, caretWidth);
2884 bool RenderBoxModelObject::shouldAntialiasLines(GraphicsContext* context)
2886 // FIXME: We may want to not antialias when scaled by an integral value,
2887 // and we may want to antialias when translated by a non-integral value.
2888 return !context->getCTM().isIdentityOrTranslationOrFlipped();
2891 void RenderBoxModelObject::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
2893 RenderObject* o = container();
2897 // The point inside a box that's inside a region has its coordinates relative to the region,
2898 // not the FlowThread that is its container in the RenderObject tree.
2899 if (o->isRenderFlowThread() && isRenderBlock()) {
2900 // FIXME (CSSREGIONS): switch to Box instead of Block when we'll have range information
2901 // for boxes as well, not just for blocks.
2902 RenderRegion* startRegion;
2903 RenderRegion* endRegion;
2904 toRenderFlowThread(o)->getRegionRangeForBox(toRenderBlock(this), startRegion, endRegion);
2909 o->mapAbsoluteToLocalPoint(mode, transformState);
2911 LayoutSize containerOffset = offsetFromContainer(o, LayoutPoint());
2913 if (!style()->hasOutOfFlowPosition() && o->hasColumns()) {
2914 RenderBlock* block = toRenderBlock(o);
2915 LayoutPoint point(roundedLayoutPoint(transformState.mappedPoint()));
2916 point -= containerOffset;
2917 block->adjustForColumnRect(containerOffset, point);
2920 bool preserve3D = mode & UseTransforms && (o->style()->preserves3D() || style()->preserves3D());
2921 if (mode & UseTransforms && shouldUseTransformFromContainer(o)) {
2922 TransformationMatrix t;
2923 getTransformFromContainer(o, containerOffset, t);
2924 transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
2926 transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
2929 void RenderBoxModelObject::moveChildTo(RenderBoxModelObject* toBoxModelObject, RenderObject* child, RenderObject* beforeChild, bool fullRemoveInsert)
2931 // We assume that callers have cleared their positioned objects list for child moves (!fullRemoveInsert) so the
2932 // positioned renderer maps don't become stale. It would be too slow to do the map lookup on each call.
2933 ASSERT(!fullRemoveInsert || !isRenderBlock() || !toRenderBlock(this)->hasPositionedObjects());
2935 ASSERT(this == child->parent());
2936 ASSERT(!beforeChild || toBoxModelObject == beforeChild->parent());
2937 if (fullRemoveInsert && (toBoxModelObject->isRenderBlock() || toBoxModelObject->isRenderInline())) {
2938 // Takes care of adding the new child correctly if toBlock and fromBlock
2939 // have different kind of children (block vs inline).
2940 toBoxModelObject->addChild(virtualChildren()->removeChildNode(this, child), beforeChild);
2942 toBoxModelObject->virtualChildren()->insertChildNode(toBoxModelObject, virtualChildren()->removeChildNode(this, child, fullRemoveInsert), beforeChild, fullRemoveInsert);
2945 void RenderBoxModelObject::moveChildrenTo(RenderBoxModelObject* toBoxModelObject, RenderObject* startChild, RenderObject* endChild, RenderObject* beforeChild, bool fullRemoveInsert)
2947 // This condition is rarely hit since this function is usually called on
2948 // anonymous blocks which can no longer carry positioned objects (see r120761)
2949 // or when fullRemoveInsert is false.
2950 if (fullRemoveInsert && isRenderBlock()) {
2951 RenderBlock* block = toRenderBlock(this);
2952 block->removePositionedObjects(0);
2953 block->removeFloatingObjects();
2956 ASSERT(!beforeChild || toBoxModelObject == beforeChild->parent());
2957 for (RenderObject* child = startChild; child && child != endChild; ) {
2958 // Save our next sibling as moveChildTo will clear it.
2959 RenderObject* nextSibling = child->nextSibling();
2960 moveChildTo(toBoxModelObject, child, beforeChild, fullRemoveInsert);
2961 child = nextSibling;
2965 } // namespace WebCore