2 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
3 * (C) 1999 Antti Koivisto (koivisto@kde.org)
4 * (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
5 * (C) 2005, 2006 Samuel Weinig (sam.weinig@gmail.com)
6 * Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
7 * Copyright (C) 2010 Google Inc. All rights reserved.
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Library General Public
11 * License as published by the Free Software Foundation; either
12 * version 2 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Library General Public License for more details.
19 * You should have received a copy of the GNU Library General Public License
20 * along with this library; see the file COPYING.LIB. If not, write to
21 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22 * Boston, MA 02110-1301, USA.
27 #include "RenderBoxModelObject.h"
29 #include "GraphicsContext.h"
30 #include "HTMLFrameOwnerElement.h"
31 #include "HTMLNames.h"
32 #include "ImageBuffer.h"
35 #include "RenderBlock.h"
36 #include "RenderInline.h"
37 #include "RenderLayer.h"
38 #include "RenderView.h"
39 #include "ScrollingConstraints.h"
41 #include "TransformState.h"
42 #include <wtf/CurrentTime.h>
44 #if USE(ACCELERATED_COMPOSITING)
45 #include "RenderLayerBacking.h"
46 #include "RenderLayerCompositor.h"
53 using namespace HTMLNames;
55 static const double cInterpolationCutoff = 800. * 800.;
56 static const double cLowQualityTimeThreshold = 0.500; // 500 ms
58 typedef HashMap<const void*, LayoutSize> LayerSizeMap;
59 typedef HashMap<RenderBoxModelObject*, LayerSizeMap> ObjectLayerSizeMap;
61 // The HashMap for storing continuation pointers.
62 // An inline can be split with blocks occuring in between the inline content.
63 // When this occurs we need a pointer to the next object. We can basically be
64 // split into a sequence of inlines and blocks. The continuation will either be
65 // an anonymous block (that houses other blocks) or it will be an inline flow.
66 // <b><i><p>Hello</p></i></b>. In this example the <i> will have a block as
67 // its continuation but the <b> will just have an inline as its continuation.
68 typedef HashMap<const RenderBoxModelObject*, RenderBoxModelObject*> ContinuationMap;
69 static ContinuationMap* continuationMap = 0;
71 // This HashMap is similar to the continuation map, but connects first-letter
72 // renderers to their remaining text fragments.
73 typedef HashMap<const RenderBoxModelObject*, RenderObject*> FirstLetterRemainingTextMap;
74 static FirstLetterRemainingTextMap* firstLetterRemainingTextMap = 0;
76 class ImageQualityController {
77 WTF_MAKE_NONCOPYABLE(ImageQualityController); WTF_MAKE_FAST_ALLOCATED;
79 ImageQualityController();
80 bool shouldPaintAtLowQuality(GraphicsContext*, RenderBoxModelObject*, Image*, const void* layer, const LayoutSize&);
81 void removeLayer(RenderBoxModelObject*, LayerSizeMap* innerMap, const void* layer);
82 void set(RenderBoxModelObject*, LayerSizeMap* innerMap, const void* layer, const LayoutSize&);
83 void objectDestroyed(RenderBoxModelObject*);
84 bool isEmpty() { return m_objectLayerSizeMap.isEmpty(); }
87 void highQualityRepaintTimerFired(Timer<ImageQualityController>*);
90 ObjectLayerSizeMap m_objectLayerSizeMap;
91 Timer<ImageQualityController> m_timer;
92 bool m_animatedResizeIsActive;
93 bool m_liveResizeOptimizationIsActive;
96 ImageQualityController::ImageQualityController()
97 : m_timer(this, &ImageQualityController::highQualityRepaintTimerFired)
98 , m_animatedResizeIsActive(false)
99 , m_liveResizeOptimizationIsActive(false)
103 void ImageQualityController::removeLayer(RenderBoxModelObject* object, LayerSizeMap* innerMap, const void* layer)
106 innerMap->remove(layer);
107 if (innerMap->isEmpty())
108 objectDestroyed(object);
112 void ImageQualityController::set(RenderBoxModelObject* object, LayerSizeMap* innerMap, const void* layer, const LayoutSize& size)
115 innerMap->set(layer, size);
117 LayerSizeMap newInnerMap;
118 newInnerMap.set(layer, size);
119 m_objectLayerSizeMap.set(object, newInnerMap);
123 void ImageQualityController::objectDestroyed(RenderBoxModelObject* object)
125 m_objectLayerSizeMap.remove(object);
126 if (m_objectLayerSizeMap.isEmpty()) {
127 m_animatedResizeIsActive = false;
132 void ImageQualityController::highQualityRepaintTimerFired(Timer<ImageQualityController>*)
134 if (!m_animatedResizeIsActive && !m_liveResizeOptimizationIsActive)
136 m_animatedResizeIsActive = false;
138 for (ObjectLayerSizeMap::iterator it = m_objectLayerSizeMap.begin(); it != m_objectLayerSizeMap.end(); ++it) {
139 if (Frame* frame = it->key->document()->frame()) {
140 // If this renderer's containing FrameView is in live resize, punt the timer and hold back for now.
141 if (frame->view() && frame->view()->inLiveResize()) {
149 m_liveResizeOptimizationIsActive = false;
152 void ImageQualityController::restartTimer()
154 m_timer.startOneShot(cLowQualityTimeThreshold);
157 bool ImageQualityController::shouldPaintAtLowQuality(GraphicsContext* context, RenderBoxModelObject* object, Image* image, const void *layer, const LayoutSize& size)
159 // If the image is not a bitmap image, then none of this is relevant and we just paint at high
161 if (!image || !image->isBitmapImage() || context->paintingDisabled())
164 if (object->style()->imageRendering() == ImageRenderingOptimizeContrast)
167 // Make sure to use the unzoomed image size, since if a full page zoom is in effect, the image
168 // is actually being scaled.
169 IntSize imageSize(image->width(), image->height());
171 // Look ourselves up in the hashtables.
172 ObjectLayerSizeMap::iterator i = m_objectLayerSizeMap.find(object);
173 LayerSizeMap* innerMap = i != m_objectLayerSizeMap.end() ? &i->value : 0;
175 bool isFirstResize = true;
177 LayerSizeMap::iterator j = innerMap->find(layer);
178 if (j != innerMap->end()) {
179 isFirstResize = false;
184 // If the containing FrameView is being resized, paint at low quality until resizing is finished.
185 if (Frame* frame = object->document()->frame()) {
186 bool frameViewIsCurrentlyInLiveResize = frame->view() && frame->view()->inLiveResize();
187 if (frameViewIsCurrentlyInLiveResize) {
188 set(object, innerMap, layer, size);
190 m_liveResizeOptimizationIsActive = true;
193 if (m_liveResizeOptimizationIsActive) {
194 // Live resize has ended, paint in HQ and remove this object from the list.
195 removeLayer(object, innerMap, layer);
200 const AffineTransform& currentTransform = context->getCTM();
201 bool contextIsScaled = !currentTransform.isIdentityOrTranslationOrFlipped();
202 if (!contextIsScaled && size == imageSize) {
203 // There is no scale in effect. If we had a scale in effect before, we can just remove this object from the list.
204 removeLayer(object, innerMap, layer);
208 // There is no need to hash scaled images that always use low quality mode when the page demands it. This is the iChat case.
209 if (object->document()->page()->inLowQualityImageInterpolationMode()) {
210 double totalPixels = static_cast<double>(image->width()) * static_cast<double>(image->height());
211 if (totalPixels > cInterpolationCutoff)
215 // If an animated resize is active, paint in low quality and kick the timer ahead.
216 if (m_animatedResizeIsActive) {
217 set(object, innerMap, layer, size);
221 // If this is the first time resizing this image, or its size is the
222 // same as the last resize, draw at high res, but record the paint
223 // size and set the timer.
224 if (isFirstResize || oldSize == size) {
226 set(object, innerMap, layer, size);
229 // If the timer is no longer active, draw at high quality and don't
231 if (!m_timer.isActive()) {
232 removeLayer(object, innerMap, layer);
235 // This object has been resized to two different sizes while the timer
236 // is active, so draw at low quality, set the flag for animated resizes and
237 // the object to the list for high quality redraw.
238 set(object, innerMap, layer, size);
239 m_animatedResizeIsActive = true;
244 static ImageQualityController* gImageQualityController = 0;
246 static ImageQualityController* imageQualityController()
248 if (!gImageQualityController)
249 gImageQualityController = new ImageQualityController;
251 return gImageQualityController;
254 void RenderBoxModelObject::setSelectionState(SelectionState state)
256 if (state == SelectionInside && selectionState() != SelectionNone)
259 if ((state == SelectionStart && selectionState() == SelectionEnd)
260 || (state == SelectionEnd && selectionState() == SelectionStart))
261 RenderObject::setSelectionState(SelectionBoth);
263 RenderObject::setSelectionState(state);
265 // FIXME: We should consider whether it is OK propagating to ancestor RenderInlines.
266 // This is a workaround for http://webkit.org/b/32123
267 // The containing block can be null in case of an orphaned tree.
268 RenderBlock* containingBlock = this->containingBlock();
269 if (containingBlock && !containingBlock->isRenderView())
270 containingBlock->setSelectionState(state);
273 #if USE(ACCELERATED_COMPOSITING)
274 void RenderBoxModelObject::contentChanged(ContentChangeType changeType)
279 layer()->contentChanged(changeType);
282 bool RenderBoxModelObject::hasAcceleratedCompositing() const
284 return view()->compositor()->hasAcceleratedCompositing();
287 bool RenderBoxModelObject::startTransition(double timeOffset, CSSPropertyID propertyId, const RenderStyle* fromStyle, const RenderStyle* toStyle)
290 ASSERT(isComposited());
291 return layer()->backing()->startTransition(timeOffset, propertyId, fromStyle, toStyle);
294 void RenderBoxModelObject::transitionPaused(double timeOffset, CSSPropertyID propertyId)
297 ASSERT(isComposited());
298 layer()->backing()->transitionPaused(timeOffset, propertyId);
301 void RenderBoxModelObject::transitionFinished(CSSPropertyID propertyId)
304 ASSERT(isComposited());
305 layer()->backing()->transitionFinished(propertyId);
308 bool RenderBoxModelObject::startAnimation(double timeOffset, const Animation* animation, const KeyframeList& keyframes)
311 ASSERT(isComposited());
312 return layer()->backing()->startAnimation(timeOffset, animation, keyframes);
315 void RenderBoxModelObject::animationPaused(double timeOffset, const String& name)
318 ASSERT(isComposited());
319 layer()->backing()->animationPaused(timeOffset, name);
322 void RenderBoxModelObject::animationFinished(const String& name)
325 ASSERT(isComposited());
326 layer()->backing()->animationFinished(name);
329 void RenderBoxModelObject::suspendAnimations(double time)
332 ASSERT(isComposited());
333 layer()->backing()->suspendAnimations(time);
337 bool RenderBoxModelObject::shouldPaintAtLowQuality(GraphicsContext* context, Image* image, const void* layer, const LayoutSize& size)
339 return imageQualityController()->shouldPaintAtLowQuality(context, this, image, layer, size);
342 RenderBoxModelObject::RenderBoxModelObject(ContainerNode* node)
343 : RenderLayerModelObject(node)
347 RenderBoxModelObject::~RenderBoxModelObject()
349 if (gImageQualityController) {
350 gImageQualityController->objectDestroyed(this);
351 if (gImageQualityController->isEmpty()) {
352 delete gImageQualityController;
353 gImageQualityController = 0;
358 void RenderBoxModelObject::willBeDestroyed()
360 // A continuation of this RenderObject should be destroyed at subclasses.
361 ASSERT(!continuation());
363 // If this is a first-letter object with a remaining text fragment then the
364 // entry needs to be cleared from the map.
365 if (firstLetterRemainingText())
366 setFirstLetterRemainingText(0);
368 RenderLayerModelObject::willBeDestroyed();
371 void RenderBoxModelObject::updateFromStyle()
373 RenderLayerModelObject::updateFromStyle();
375 // Set the appropriate bits for a box model object. Since all bits are cleared in styleWillChange,
376 // we only check for bits that could possibly be set to true.
377 RenderStyle* styleToUse = style();
378 setHasBoxDecorations(hasBackground() || styleToUse->hasBorder() || styleToUse->hasAppearance() || styleToUse->boxShadow());
379 setInline(styleToUse->isDisplayInlineType());
380 setPositionState(styleToUse->position());
381 setHorizontalWritingMode(styleToUse->isHorizontalWritingMode());
384 static LayoutSize accumulateInFlowPositionOffsets(const RenderObject* child)
386 if (!child->isAnonymousBlock() || !child->isInFlowPositioned())
389 RenderObject* p = toRenderBlock(child)->inlineElementContinuation();
390 while (p && p->isRenderInline()) {
391 if (p->isInFlowPositioned()) {
392 RenderInline* renderInline = toRenderInline(p);
393 offset += renderInline->offsetForInFlowPosition();
400 bool RenderBoxModelObject::hasAutoHeightOrContainingBlockWithAutoHeight() const
402 Length logicalHeightLength = style()->logicalHeight();
403 if (logicalHeightLength.isAuto())
406 // For percentage heights: The percentage is calculated with respect to the height of the generated box's
407 // containing block. If the height of the containing block is not specified explicitly (i.e., it depends
408 // on content height), and this element is not absolutely positioned, the value computes to 'auto'.
409 if (!logicalHeightLength.isPercent() || isOutOfFlowPositioned() || document()->inQuirksMode())
412 // Anonymous block boxes are ignored when resolving percentage values that would refer to it:
413 // the closest non-anonymous ancestor box is used instead.
414 RenderBlock* cb = containingBlock();
415 while (cb->isAnonymous())
416 cb = cb->containingBlock();
418 // Matching RenderBox::percentageLogicalHeightIsResolvableFromBlock() by
419 // ignoring table cell's attribute value, where it says that table cells violate
420 // what the CSS spec says to do with heights. Basically we
421 // don't care if the cell specified a height or not.
422 if (cb->isTableCell())
425 if (!cb->style()->logicalHeight().isAuto() || (!cb->style()->logicalTop().isAuto() && !cb->style()->logicalBottom().isAuto()))
431 LayoutSize RenderBoxModelObject::relativePositionOffset() const
433 LayoutSize offset = accumulateInFlowPositionOffsets(this);
435 RenderBlock* containingBlock = this->containingBlock();
437 // Objects that shrink to avoid floats normally use available line width when computing containing block width. However
438 // in the case of relative positioning using percentages, we can't do this. The offset should always be resolved using the
439 // available width of the containing block. Therefore we don't use containingBlockLogicalWidthForContent() here, but instead explicitly
440 // call availableWidth on our containing block.
441 if (!style()->left().isAuto()) {
442 if (!style()->right().isAuto() && !containingBlock->style()->isLeftToRightDirection())
443 offset.setWidth(-valueForLength(style()->right(), containingBlock->availableWidth(), view()));
445 offset.expand(valueForLength(style()->left(), containingBlock->availableWidth(), view()), 0);
446 } else if (!style()->right().isAuto()) {
447 offset.expand(-valueForLength(style()->right(), containingBlock->availableWidth(), view()), 0);
450 // If the containing block of a relatively positioned element does not
451 // specify a height, a percentage top or bottom offset should be resolved as
452 // auto. An exception to this is if the containing block has the WinIE quirk
453 // where <html> and <body> assume the size of the viewport. In this case,
454 // calculate the percent offset based on this height.
455 // See <https://bugs.webkit.org/show_bug.cgi?id=26396>.
456 if (!style()->top().isAuto()
457 && (!containingBlock->hasAutoHeightOrContainingBlockWithAutoHeight()
458 || !style()->top().isPercent()
459 || containingBlock->stretchesToViewport()))
460 offset.expand(0, valueForLength(style()->top(), containingBlock->availableHeight(), view()));
462 else if (!style()->bottom().isAuto()
463 && (!containingBlock->hasAutoHeightOrContainingBlockWithAutoHeight()
464 || !style()->bottom().isPercent()
465 || containingBlock->stretchesToViewport()))
466 offset.expand(0, -valueForLength(style()->bottom(), containingBlock->availableHeight(), view()));
471 LayoutPoint RenderBoxModelObject::adjustedPositionRelativeToOffsetParent(const LayoutPoint& startPoint) const
473 // If the element is the HTML body element or doesn't have a parent
474 // return 0 and stop this algorithm.
475 if (isBody() || !parent())
476 return LayoutPoint();
478 LayoutPoint referencePoint = startPoint;
479 referencePoint.move(parent()->offsetForColumns(referencePoint));
481 // If the offsetParent of the element is null, or is the HTML body element,
482 // return the distance between the canvas origin and the left border edge
483 // of the element and stop this algorithm.
484 Element* element = offsetParent();
486 return referencePoint;
488 if (const RenderBoxModelObject* offsetParent = element->renderBoxModelObject()) {
489 if (offsetParent->isBox() && !offsetParent->isBody())
490 referencePoint.move(-toRenderBox(offsetParent)->borderLeft(), -toRenderBox(offsetParent)->borderTop());
491 if (!isOutOfFlowPositioned()) {
492 if (isRelPositioned())
493 referencePoint.move(relativePositionOffset());
494 else if (isStickyPositioned())
495 referencePoint.move(stickyPositionOffset());
496 const RenderObject* curr = parent();
497 while (curr != offsetParent) {
498 // FIXME: What are we supposed to do inside SVG content?
499 if (curr->isBox() && !curr->isTableRow())
500 referencePoint.moveBy(toRenderBox(curr)->topLeftLocation());
501 referencePoint.move(curr->parent()->offsetForColumns(referencePoint));
502 curr = curr->parent();
504 if (offsetParent->isBox() && offsetParent->isBody() && !offsetParent->isPositioned())
505 referencePoint.moveBy(toRenderBox(offsetParent)->topLeftLocation());
509 return referencePoint;
512 void RenderBoxModelObject::computeStickyPositionConstraints(StickyPositionViewportConstraints& constraints, const FloatRect& viewportRect) const
514 RenderBlock* containingBlock = this->containingBlock();
516 LayoutRect containerContentRect = containingBlock->contentBoxRect();
517 LayoutUnit maxWidth = containingBlock->availableLogicalWidth();
519 // Sticky positioned element ignore any override logical width on the containing block (as they don't call
520 // containingBlockLogicalWidthForContent). It's unclear whether this is totally fine.
521 LayoutBoxExtent minMargin(minimumValueForLength(style()->marginTop(), maxWidth, view()),
522 minimumValueForLength(style()->marginRight(), maxWidth, view()),
523 minimumValueForLength(style()->marginBottom(), maxWidth, view()),
524 minimumValueForLength(style()->marginLeft(), maxWidth, view()));
526 // Compute the container-relative area within which the sticky element is allowed to move.
527 containerContentRect.contract(minMargin);
528 // Map to the view to avoid including page scale factor.
529 constraints.setAbsoluteContainingBlockRect(containingBlock->localToContainerQuad(FloatRect(containerContentRect), view()).boundingBox());
531 LayoutRect stickyBoxRect = frameRectForStickyPositioning();
532 LayoutRect flippedStickyBoxRect = stickyBoxRect;
533 containingBlock->flipForWritingMode(flippedStickyBoxRect);
534 LayoutPoint stickyLocation = flippedStickyBoxRect.location();
536 // FIXME: sucks to call localToAbsolute again, but we can't just offset from the previously computed rect if there are transforms.
537 // Map to the view to avoid including page scale factor.
538 FloatRect absContainerFrame = containingBlock->localToContainerQuad(FloatRect(FloatPoint(), containingBlock->size()), view()).boundingBox();
540 // We can't call localToAbsolute on |this| because that will recur. FIXME: For now, assume that |this| is not transformed.
541 FloatRect absoluteStickyBoxRect(absContainerFrame.location() + stickyLocation, flippedStickyBoxRect.size());
542 constraints.setAbsoluteStickyBoxRect(absoluteStickyBoxRect);
544 if (!style()->left().isAuto()) {
545 constraints.setLeftOffset(valueForLength(style()->left(), viewportRect.width(), view()));
546 constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeLeft);
549 if (!style()->right().isAuto()) {
550 constraints.setRightOffset(valueForLength(style()->right(), viewportRect.width(), view()));
551 constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeRight);
554 if (!style()->top().isAuto()) {
555 constraints.setTopOffset(valueForLength(style()->top(), viewportRect.height(), view()));
556 constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeTop);
559 if (!style()->bottom().isAuto()) {
560 constraints.setBottomOffset(valueForLength(style()->bottom(), viewportRect.height(), view()));
561 constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeBottom);
565 LayoutSize RenderBoxModelObject::stickyPositionOffset() const
567 LayoutRect viewportRect = view()->frameView()->viewportConstrainedVisibleContentRect();
569 if (Frame* frame = view()->frameView()->frame())
570 scale = frame->frameScaleFactor();
572 viewportRect.scale(1 / scale);
574 StickyPositionViewportConstraints constraints;
575 computeStickyPositionConstraints(constraints, viewportRect);
577 // The sticky offset is physical, so we can just return the delta computed in absolute coords (though it may be wrong with transforms).
578 return LayoutSize(constraints.computeStickyOffset(viewportRect));
581 LayoutSize RenderBoxModelObject::offsetForInFlowPosition() const
583 if (isRelPositioned())
584 return relativePositionOffset();
586 if (isStickyPositioned())
587 return stickyPositionOffset();
592 LayoutSize RenderBoxModelObject::paintOffset() const
594 LayoutSize offset = offsetForInFlowPosition();
596 #if ENABLE(CSS_EXCLUSIONS)
597 if (isBox() && isFloating())
598 if (ExclusionShapeOutsideInfo* shapeOutside = toRenderBox(this)->exclusionShapeOutsideInfo())
599 offset -= shapeOutside->shapeLogicalOffset();
605 LayoutUnit RenderBoxModelObject::offsetLeft() const
607 // Note that RenderInline and RenderBox override this to pass a different
608 // startPoint to adjustedPositionRelativeToOffsetParent.
609 return adjustedPositionRelativeToOffsetParent(LayoutPoint()).x();
612 LayoutUnit RenderBoxModelObject::offsetTop() const
614 // Note that RenderInline and RenderBox override this to pass a different
615 // startPoint to adjustedPositionRelativeToOffsetParent.
616 return adjustedPositionRelativeToOffsetParent(LayoutPoint()).y();
619 int RenderBoxModelObject::pixelSnappedOffsetWidth() const
621 return snapSizeToPixel(offsetWidth(), offsetLeft());
624 int RenderBoxModelObject::pixelSnappedOffsetHeight() const
626 return snapSizeToPixel(offsetHeight(), offsetTop());
629 LayoutUnit RenderBoxModelObject::computedCSSPadding(Length padding) const
632 RenderView* renderView = 0;
633 if (padding.isPercent())
634 w = containingBlockLogicalWidthForContent();
635 else if (padding.isViewportPercentage())
637 return minimumValueForLength(padding, w, renderView);
640 RoundedRect RenderBoxModelObject::getBackgroundRoundedRect(const LayoutRect& borderRect, InlineFlowBox* box, LayoutUnit inlineBoxWidth, LayoutUnit inlineBoxHeight,
641 bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
643 RenderView* renderView = view();
644 RoundedRect border = style()->getRoundedBorderFor(borderRect, renderView, includeLogicalLeftEdge, includeLogicalRightEdge);
645 if (box && (box->nextLineBox() || box->prevLineBox())) {
646 RoundedRect segmentBorder = style()->getRoundedBorderFor(LayoutRect(0, 0, inlineBoxWidth, inlineBoxHeight), renderView, includeLogicalLeftEdge, includeLogicalRightEdge);
647 border.setRadii(segmentBorder.radii());
653 void RenderBoxModelObject::clipRoundedInnerRect(GraphicsContext * context, const LayoutRect& rect, const RoundedRect& clipRect)
655 if (clipRect.isRenderable())
656 context->clipRoundedRect(clipRect);
658 // We create a rounded rect for each of the corners and clip it, while making sure we clip opposing corners together.
659 if (!clipRect.radii().topLeft().isEmpty() || !clipRect.radii().bottomRight().isEmpty()) {
660 IntRect topCorner(clipRect.rect().x(), clipRect.rect().y(), rect.maxX() - clipRect.rect().x(), rect.maxY() - clipRect.rect().y());
661 RoundedRect::Radii topCornerRadii;
662 topCornerRadii.setTopLeft(clipRect.radii().topLeft());
663 context->clipRoundedRect(RoundedRect(topCorner, topCornerRadii));
665 IntRect bottomCorner(rect.x(), rect.y(), clipRect.rect().maxX() - rect.x(), clipRect.rect().maxY() - rect.y());
666 RoundedRect::Radii bottomCornerRadii;
667 bottomCornerRadii.setBottomRight(clipRect.radii().bottomRight());
668 context->clipRoundedRect(RoundedRect(bottomCorner, bottomCornerRadii));
671 if (!clipRect.radii().topRight().isEmpty() || !clipRect.radii().bottomLeft().isEmpty()) {
672 IntRect topCorner(rect.x(), clipRect.rect().y(), clipRect.rect().maxX() - rect.x(), rect.maxY() - clipRect.rect().y());
673 RoundedRect::Radii topCornerRadii;
674 topCornerRadii.setTopRight(clipRect.radii().topRight());
675 context->clipRoundedRect(RoundedRect(topCorner, topCornerRadii));
677 IntRect bottomCorner(clipRect.rect().x(), rect.y(), rect.maxX() - clipRect.rect().x(), clipRect.rect().maxY() - rect.y());
678 RoundedRect::Radii bottomCornerRadii;
679 bottomCornerRadii.setBottomLeft(clipRect.radii().bottomLeft());
680 context->clipRoundedRect(RoundedRect(bottomCorner, bottomCornerRadii));
685 static LayoutRect shrinkRectByOnePixel(GraphicsContext* context, const LayoutRect& rect)
687 LayoutRect shrunkRect = rect;
688 AffineTransform transform = context->getCTM();
689 shrunkRect.inflateX(-static_cast<LayoutUnit>(ceil(1 / transform.xScale())));
690 shrunkRect.inflateY(-static_cast<LayoutUnit>(ceil(1 / transform.yScale())));
694 LayoutRect RenderBoxModelObject::borderInnerRectAdjustedForBleedAvoidance(GraphicsContext* context, const LayoutRect& rect, BackgroundBleedAvoidance bleedAvoidance) const
696 // We shrink the rectangle by one pixel on each side to make it fully overlap the anti-aliased background border
697 return (bleedAvoidance == BackgroundBleedBackgroundOverBorder) ? shrinkRectByOnePixel(context, rect) : rect;
700 RoundedRect RenderBoxModelObject::backgroundRoundedRectAdjustedForBleedAvoidance(GraphicsContext* context, const LayoutRect& borderRect, BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* box, const LayoutSize& boxSize, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
702 if (bleedAvoidance == BackgroundBleedShrinkBackground) {
703 // We shrink the rectangle by one pixel on each side because the bleed is one pixel maximum.
704 return getBackgroundRoundedRect(shrinkRectByOnePixel(context, borderRect), box, boxSize.width(), boxSize.height(), includeLogicalLeftEdge, includeLogicalRightEdge);
706 if (bleedAvoidance == BackgroundBleedBackgroundOverBorder)
707 return style()->getRoundedInnerBorderFor(borderRect, includeLogicalLeftEdge, includeLogicalRightEdge);
709 return getBackgroundRoundedRect(borderRect, box, boxSize.width(), boxSize.height(), includeLogicalLeftEdge, includeLogicalRightEdge);
712 static void applyBoxShadowForBackground(GraphicsContext* context, RenderStyle* style)
714 const ShadowData* boxShadow = style->boxShadow();
715 while (boxShadow->style() != Normal)
716 boxShadow = boxShadow->next();
718 FloatSize shadowOffset(boxShadow->x(), boxShadow->y());
719 if (!boxShadow->isWebkitBoxShadow())
720 context->setShadow(shadowOffset, boxShadow->radius(), boxShadow->color(), style->colorSpace());
722 context->setLegacyShadow(shadowOffset, boxShadow->radius(), boxShadow->color(), style->colorSpace());
725 void RenderBoxModelObject::paintFillLayerExtended(const PaintInfo& paintInfo, const Color& color, const FillLayer* bgLayer, const LayoutRect& rect,
726 BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* box, const LayoutSize& boxSize, CompositeOperator op, RenderObject* backgroundObject)
728 GraphicsContext* context = paintInfo.context;
729 if (context->paintingDisabled() || rect.isEmpty())
732 bool includeLeftEdge = box ? box->includeLogicalLeftEdge() : true;
733 bool includeRightEdge = box ? box->includeLogicalRightEdge() : true;
735 bool hasRoundedBorder = style()->hasBorderRadius() && (includeLeftEdge || includeRightEdge);
736 bool clippedWithLocalScrolling = hasOverflowClip() && bgLayer->attachment() == LocalBackgroundAttachment;
737 bool isBorderFill = bgLayer->clip() == BorderFillBox;
738 bool isRoot = this->isRoot();
740 Color bgColor = color;
741 StyleImage* bgImage = bgLayer->image();
742 bool shouldPaintBackgroundImage = bgImage && bgImage->canRender(this, style()->effectiveZoom());
744 bool forceBackgroundToWhite = false;
745 if (document()->printing()) {
746 if (style()->printColorAdjust() == PrintColorAdjustEconomy)
747 forceBackgroundToWhite = true;
748 if (document()->settings() && document()->settings()->shouldPrintBackgrounds())
749 forceBackgroundToWhite = false;
752 // When printing backgrounds is disabled or using economy mode,
753 // change existing background colors and images to a solid white background.
754 // If there's no bg color or image, leave it untouched to avoid affecting transparency.
755 // We don't try to avoid loading the background images, because this style flag is only set
756 // when printing, and at that point we've already loaded the background images anyway. (To avoid
757 // loading the background images we'd have to do this check when applying styles rather than
759 if (forceBackgroundToWhite) {
760 // Note that we can't reuse this variable below because the bgColor might be changed
761 bool shouldPaintBackgroundColor = !bgLayer->next() && bgColor.isValid() && bgColor.alpha();
762 if (shouldPaintBackgroundImage || shouldPaintBackgroundColor) {
763 bgColor = Color::white;
764 shouldPaintBackgroundImage = false;
768 bool colorVisible = bgColor.isValid() && bgColor.alpha();
770 // Fast path for drawing simple color backgrounds.
771 if (!isRoot && !clippedWithLocalScrolling && !shouldPaintBackgroundImage && isBorderFill && !bgLayer->next()) {
775 bool boxShadowShouldBeAppliedToBackground = this->boxShadowShouldBeAppliedToBackground(bleedAvoidance, box);
776 GraphicsContextStateSaver shadowStateSaver(*context, boxShadowShouldBeAppliedToBackground);
777 if (boxShadowShouldBeAppliedToBackground)
778 applyBoxShadowForBackground(context, style());
780 if (hasRoundedBorder && bleedAvoidance != BackgroundBleedUseTransparencyLayer) {
781 RoundedRect border = backgroundRoundedRectAdjustedForBleedAvoidance(context, rect, bleedAvoidance, box, boxSize, includeLeftEdge, includeRightEdge);
782 if (border.isRenderable())
783 context->fillRoundedRect(border, bgColor, style()->colorSpace());
786 clipRoundedInnerRect(context, rect, border);
787 context->fillRect(border.rect(), bgColor, style()->colorSpace());
791 context->fillRect(pixelSnappedIntRect(rect), bgColor, style()->colorSpace());
796 // BorderFillBox radius clipping is taken care of by BackgroundBleedUseTransparencyLayer
797 bool clipToBorderRadius = hasRoundedBorder && !(isBorderFill && bleedAvoidance == BackgroundBleedUseTransparencyLayer);
798 GraphicsContextStateSaver clipToBorderStateSaver(*context, clipToBorderRadius);
799 if (clipToBorderRadius) {
800 RoundedRect border = isBorderFill ? backgroundRoundedRectAdjustedForBleedAvoidance(context, rect, bleedAvoidance, box, boxSize, includeLeftEdge, includeRightEdge) : getBackgroundRoundedRect(rect, box, boxSize.width(), boxSize.height(), includeLeftEdge, includeRightEdge);
802 // Clip to the padding or content boxes as necessary.
803 if (bgLayer->clip() == ContentFillBox) {
804 border = style()->getRoundedInnerBorderFor(border.rect(),
805 paddingTop() + borderTop(), paddingBottom() + borderBottom(), paddingLeft() + borderLeft(), paddingRight() + borderRight(), includeLeftEdge, includeRightEdge);
806 } else if (bgLayer->clip() == PaddingFillBox)
807 border = style()->getRoundedInnerBorderFor(border.rect(), includeLeftEdge, includeRightEdge);
809 clipRoundedInnerRect(context, rect, border);
812 int bLeft = includeLeftEdge ? borderLeft() : 0;
813 int bRight = includeRightEdge ? borderRight() : 0;
814 LayoutUnit pLeft = includeLeftEdge ? paddingLeft() : LayoutUnit();
815 LayoutUnit pRight = includeRightEdge ? paddingRight() : LayoutUnit();
817 GraphicsContextStateSaver clipWithScrollingStateSaver(*context, clippedWithLocalScrolling);
818 LayoutRect scrolledPaintRect = rect;
819 if (clippedWithLocalScrolling) {
820 // Clip to the overflow area.
821 RenderBox* thisBox = toRenderBox(this);
822 context->clip(thisBox->overflowClipRect(rect.location(), paintInfo.renderRegion));
824 // Adjust the paint rect to reflect a scrolled content box with borders at the ends.
825 IntSize offset = thisBox->scrolledContentOffset();
826 scrolledPaintRect.move(-offset);
827 scrolledPaintRect.setWidth(bLeft + layer()->scrollWidth() + bRight);
828 scrolledPaintRect.setHeight(borderTop() + layer()->scrollHeight() + borderBottom());
831 GraphicsContextStateSaver backgroundClipStateSaver(*context, false);
832 OwnPtr<ImageBuffer> maskImage;
835 if (bgLayer->clip() == PaddingFillBox || bgLayer->clip() == ContentFillBox) {
836 // Clip to the padding or content boxes as necessary.
837 if (!clipToBorderRadius) {
838 bool includePadding = bgLayer->clip() == ContentFillBox;
839 LayoutRect clipRect = LayoutRect(scrolledPaintRect.x() + bLeft + (includePadding ? pLeft : LayoutUnit()),
840 scrolledPaintRect.y() + borderTop() + (includePadding ? paddingTop() : LayoutUnit()),
841 scrolledPaintRect.width() - bLeft - bRight - (includePadding ? pLeft + pRight : LayoutUnit()),
842 scrolledPaintRect.height() - borderTop() - borderBottom() - (includePadding ? paddingTop() + paddingBottom() : LayoutUnit()));
843 backgroundClipStateSaver.save();
844 context->clip(clipRect);
846 } else if (bgLayer->clip() == TextFillBox) {
847 // We have to draw our text into a mask that can then be used to clip background drawing.
848 // First figure out how big the mask has to be. It should be no bigger than what we need
849 // to actually render, so we should intersect the dirty rect with the border box of the background.
850 maskRect = pixelSnappedIntRect(rect);
851 maskRect.intersect(paintInfo.rect);
853 // Now create the mask.
854 maskImage = context->createCompatibleBuffer(maskRect.size());
858 GraphicsContext* maskImageContext = maskImage->context();
859 maskImageContext->translate(-maskRect.x(), -maskRect.y());
861 // Now add the text to the clip. We do this by painting using a special paint phase that signals to
862 // InlineTextBoxes that they should just add their contents to the clip.
863 PaintInfo info(maskImageContext, maskRect, PaintPhaseTextClip, PaintBehaviorForceBlackText, 0, paintInfo.renderRegion);
865 RootInlineBox* root = box->root();
866 box->paint(info, LayoutPoint(scrolledPaintRect.x() - box->x(), scrolledPaintRect.y() - box->y()), root->lineTop(), root->lineBottom());
868 LayoutSize localOffset = isBox() ? toRenderBox(this)->locationOffset() : LayoutSize();
869 paint(info, scrolledPaintRect.location() - localOffset);
872 // The mask has been created. Now we just need to clip to it.
873 backgroundClipStateSaver.save();
874 context->clip(maskRect);
875 context->beginTransparencyLayer(1);
878 // Only fill with a base color (e.g., white) if we're the root document, since iframes/frames with
879 // no background in the child document should show the parent's background.
880 bool isOpaqueRoot = false;
883 if (!bgLayer->next() && !(bgColor.isValid() && bgColor.alpha() == 255) && view()->frameView()) {
884 Element* ownerElement = document()->ownerElement();
886 if (!ownerElement->hasTagName(frameTag)) {
887 // Locate the <body> element using the DOM. This is easier than trying
888 // to crawl around a render tree with potential :before/:after content and
889 // anonymous blocks created by inline <body> tags etc. We can locate the <body>
890 // render object very easily via the DOM.
891 HTMLElement* body = document()->body();
893 // Can't scroll a frameset document anyway.
894 isOpaqueRoot = body->hasLocalName(framesetTag);
898 // SVG documents and XML documents with SVG root nodes are transparent.
899 isOpaqueRoot = !document()->hasSVGRootNode();
904 isOpaqueRoot = !view()->frameView()->isTransparent();
906 view()->frameView()->setContentIsOpaque(isOpaqueRoot);
909 // Paint the color first underneath all images, culled if background image occludes it.
910 // FIXME: In the bgLayer->hasFiniteBounds() case, we could improve the culling test
911 // by verifying whether the background image covers the entire layout rect.
912 if (!bgLayer->next()) {
913 IntRect backgroundRect(pixelSnappedIntRect(scrolledPaintRect));
914 bool boxShadowShouldBeAppliedToBackground = this->boxShadowShouldBeAppliedToBackground(bleedAvoidance, box);
915 if (boxShadowShouldBeAppliedToBackground || !shouldPaintBackgroundImage || !bgLayer->hasOpaqueImage(this) || !bgLayer->hasRepeatXY()) {
916 if (!boxShadowShouldBeAppliedToBackground)
917 backgroundRect.intersect(paintInfo.rect);
919 // If we have an alpha and we are painting the root element, go ahead and blend with the base background color.
921 bool shouldClearBackground = false;
923 baseColor = view()->frameView()->baseBackgroundColor();
924 if (!baseColor.alpha())
925 shouldClearBackground = true;
928 GraphicsContextStateSaver shadowStateSaver(*context, boxShadowShouldBeAppliedToBackground);
929 if (boxShadowShouldBeAppliedToBackground)
930 applyBoxShadowForBackground(context, style());
932 if (baseColor.alpha()) {
934 baseColor = baseColor.blend(bgColor);
936 context->fillRect(backgroundRect, baseColor, style()->colorSpace(), CompositeCopy);
937 } else if (bgColor.alpha()) {
938 CompositeOperator operation = shouldClearBackground ? CompositeCopy : context->compositeOperation();
939 context->fillRect(backgroundRect, bgColor, style()->colorSpace(), operation);
940 } else if (shouldClearBackground)
941 context->clearRect(backgroundRect);
945 // no progressive loading of the background image
946 if (shouldPaintBackgroundImage) {
947 BackgroundImageGeometry geometry;
948 calculateBackgroundImageGeometry(bgLayer, scrolledPaintRect, geometry, backgroundObject);
949 geometry.clip(paintInfo.rect);
950 if (!geometry.destRect().isEmpty()) {
951 CompositeOperator compositeOp = op == CompositeSourceOver ? bgLayer->composite() : op;
952 RenderObject* clientForBackgroundImage = backgroundObject ? backgroundObject : this;
953 RefPtr<Image> image = bgImage->image(clientForBackgroundImage, geometry.tileSize());
954 bool useLowQualityScaling = shouldPaintAtLowQuality(context, image.get(), bgLayer, geometry.tileSize());
955 context->drawTiledImage(image.get(), style()->colorSpace(), geometry.destRect(), geometry.relativePhase(), geometry.tileSize(),
956 compositeOp, useLowQualityScaling, bgLayer->blendMode());
960 if (bgLayer->clip() == TextFillBox) {
961 context->drawImageBuffer(maskImage.get(), ColorSpaceDeviceRGB, maskRect, CompositeDestinationIn);
962 context->endTransparencyLayer();
966 static inline int resolveWidthForRatio(int height, const FloatSize& intrinsicRatio)
968 return ceilf(height * intrinsicRatio.width() / intrinsicRatio.height());
971 static inline int resolveHeightForRatio(int width, const FloatSize& intrinsicRatio)
973 return ceilf(width * intrinsicRatio.height() / intrinsicRatio.width());
976 static inline IntSize resolveAgainstIntrinsicWidthOrHeightAndRatio(const IntSize& size, const FloatSize& intrinsicRatio, int useWidth, int useHeight)
978 if (intrinsicRatio.isEmpty()) {
980 return IntSize(useWidth, size.height());
981 return IntSize(size.width(), useHeight);
985 return IntSize(useWidth, resolveHeightForRatio(useWidth, intrinsicRatio));
986 return IntSize(resolveWidthForRatio(useHeight, intrinsicRatio), useHeight);
989 static inline IntSize resolveAgainstIntrinsicRatio(const IntSize& size, const FloatSize& intrinsicRatio)
991 // Two possible solutions: (size.width(), solutionHeight) or (solutionWidth, size.height())
992 // "... must be assumed to be the largest dimensions..." = easiest answer: the rect with the largest surface area.
994 int solutionWidth = resolveWidthForRatio(size.height(), intrinsicRatio);
995 int solutionHeight = resolveHeightForRatio(size.width(), intrinsicRatio);
996 if (solutionWidth <= size.width()) {
997 if (solutionHeight <= size.height()) {
998 // If both solutions fit, choose the one covering the larger area.
999 int areaOne = solutionWidth * size.height();
1000 int areaTwo = size.width() * solutionHeight;
1001 if (areaOne < areaTwo)
1002 return IntSize(size.width(), solutionHeight);
1003 return IntSize(solutionWidth, size.height());
1006 // Only the first solution fits.
1007 return IntSize(solutionWidth, size.height());
1010 // Only the second solution fits, assert that.
1011 ASSERT(solutionHeight <= size.height());
1012 return IntSize(size.width(), solutionHeight);
1015 IntSize RenderBoxModelObject::calculateImageIntrinsicDimensions(StyleImage* image, const IntSize& positioningAreaSize, ScaleByEffectiveZoomOrNot shouldScaleOrNot) const
1017 // A generated image without a fixed size, will always return the container size as intrinsic size.
1018 if (image->isGeneratedImage() && image->usesImageContainerSize())
1019 return IntSize(positioningAreaSize.width(), positioningAreaSize.height());
1021 Length intrinsicWidth;
1022 Length intrinsicHeight;
1023 FloatSize intrinsicRatio;
1024 image->computeIntrinsicDimensions(this, intrinsicWidth, intrinsicHeight, intrinsicRatio);
1026 // Intrinsic dimensions expressed as percentages must be resolved relative to the dimensions of the rectangle
1027 // that establishes the coordinate system for the 'background-position' property.
1029 // FIXME: Remove unnecessary rounding when layout is off ints: webkit.org/b/63656
1030 if (intrinsicWidth.isPercent() && intrinsicHeight.isPercent() && intrinsicRatio.isEmpty()) {
1031 // Resolve width/height percentages against positioningAreaSize, only if no intrinsic ratio is provided.
1032 int resolvedWidth = static_cast<int>(round(positioningAreaSize.width() * intrinsicWidth.percent() / 100));
1033 int resolvedHeight = static_cast<int>(round(positioningAreaSize.height() * intrinsicHeight.percent() / 100));
1034 return IntSize(resolvedWidth, resolvedHeight);
1037 IntSize resolvedSize(intrinsicWidth.isFixed() ? intrinsicWidth.value() : 0, intrinsicHeight.isFixed() ? intrinsicHeight.value() : 0);
1038 IntSize minimumSize(resolvedSize.width() > 0 ? 1 : 0, resolvedSize.height() > 0 ? 1 : 0);
1039 if (shouldScaleOrNot == ScaleByEffectiveZoom)
1040 resolvedSize.scale(style()->effectiveZoom());
1041 resolvedSize.clampToMinimumSize(minimumSize);
1043 if (!resolvedSize.isEmpty())
1044 return resolvedSize;
1046 // If the image has one of either an intrinsic width or an intrinsic height:
1047 // * and an intrinsic aspect ratio, then the missing dimension is calculated from the given dimension and the ratio.
1048 // * and no intrinsic aspect ratio, then the missing dimension is assumed to be the size of the rectangle that
1049 // establishes the coordinate system for the 'background-position' property.
1050 if (resolvedSize.width() > 0 || resolvedSize.height() > 0)
1051 return resolveAgainstIntrinsicWidthOrHeightAndRatio(positioningAreaSize, intrinsicRatio, resolvedSize.width(), resolvedSize.height());
1053 // If the image has no intrinsic dimensions and has an intrinsic ratio the dimensions must be assumed to be the
1054 // largest dimensions at that ratio such that neither dimension exceeds the dimensions of the rectangle that
1055 // establishes the coordinate system for the 'background-position' property.
1056 if (!intrinsicRatio.isEmpty())
1057 return resolveAgainstIntrinsicRatio(positioningAreaSize, intrinsicRatio);
1059 // If the image has no intrinsic ratio either, then the dimensions must be assumed to be the rectangle that
1060 // establishes the coordinate system for the 'background-position' property.
1061 return positioningAreaSize;
1064 static inline void applySubPixelHeuristicForTileSize(LayoutSize& tileSize, const IntSize& positioningAreaSize)
1066 tileSize.setWidth(positioningAreaSize.width() - tileSize.width() <= 1 ? tileSize.width().ceil() : tileSize.width().floor());
1067 tileSize.setHeight(positioningAreaSize.height() - tileSize.height() <= 1 ? tileSize.height().ceil() : tileSize.height().floor());
1070 IntSize RenderBoxModelObject::calculateFillTileSize(const FillLayer* fillLayer, const IntSize& positioningAreaSize) const
1072 StyleImage* image = fillLayer->image();
1073 EFillSizeType type = fillLayer->size().type;
1075 IntSize imageIntrinsicSize = calculateImageIntrinsicDimensions(image, positioningAreaSize, ScaleByEffectiveZoom);
1076 imageIntrinsicSize.scale(1 / image->imageScaleFactor(), 1 / image->imageScaleFactor());
1077 RenderView* renderView = view();
1080 LayoutSize tileSize = positioningAreaSize;
1082 Length layerWidth = fillLayer->size().size.width();
1083 Length layerHeight = fillLayer->size().size.height();
1085 if (layerWidth.isFixed())
1086 tileSize.setWidth(layerWidth.value());
1087 else if (layerWidth.isPercent() || layerWidth.isViewportPercentage())
1088 tileSize.setWidth(valueForLength(layerWidth, positioningAreaSize.width(), renderView));
1090 if (layerHeight.isFixed())
1091 tileSize.setHeight(layerHeight.value());
1092 else if (layerHeight.isPercent() || layerHeight.isViewportPercentage())
1093 tileSize.setHeight(valueForLength(layerHeight, positioningAreaSize.height(), renderView));
1095 applySubPixelHeuristicForTileSize(tileSize, positioningAreaSize);
1097 // If one of the values is auto we have to use the appropriate
1098 // scale to maintain our aspect ratio.
1099 if (layerWidth.isAuto() && !layerHeight.isAuto()) {
1100 if (imageIntrinsicSize.height())
1101 tileSize.setWidth(imageIntrinsicSize.width() * tileSize.height() / imageIntrinsicSize.height());
1102 } else if (!layerWidth.isAuto() && layerHeight.isAuto()) {
1103 if (imageIntrinsicSize.width())
1104 tileSize.setHeight(imageIntrinsicSize.height() * tileSize.width() / imageIntrinsicSize.width());
1105 } else if (layerWidth.isAuto() && layerHeight.isAuto()) {
1106 // If both width and height are auto, use the image's intrinsic size.
1107 tileSize = imageIntrinsicSize;
1110 tileSize.clampNegativeToZero();
1111 return flooredIntSize(tileSize);
1114 // If both values are ‘auto’ then the intrinsic width and/or height of the image should be used, if any.
1115 if (!imageIntrinsicSize.isEmpty())
1116 return imageIntrinsicSize;
1118 // If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for ‘contain’.
1123 float horizontalScaleFactor = imageIntrinsicSize.width()
1124 ? static_cast<float>(positioningAreaSize.width()) / imageIntrinsicSize.width() : 1;
1125 float verticalScaleFactor = imageIntrinsicSize.height()
1126 ? static_cast<float>(positioningAreaSize.height()) / imageIntrinsicSize.height() : 1;
1127 float scaleFactor = type == Contain ? min(horizontalScaleFactor, verticalScaleFactor) : max(horizontalScaleFactor, verticalScaleFactor);
1128 return IntSize(max(1, static_cast<int>(imageIntrinsicSize.width() * scaleFactor)), max(1, static_cast<int>(imageIntrinsicSize.height() * scaleFactor)));
1132 ASSERT_NOT_REACHED();
1136 void RenderBoxModelObject::BackgroundImageGeometry::setNoRepeatX(int xOffset)
1138 m_destRect.move(max(xOffset, 0), 0);
1139 m_phase.setX(-min(xOffset, 0));
1140 m_destRect.setWidth(m_tileSize.width() + min(xOffset, 0));
1142 void RenderBoxModelObject::BackgroundImageGeometry::setNoRepeatY(int yOffset)
1144 m_destRect.move(0, max(yOffset, 0));
1145 m_phase.setY(-min(yOffset, 0));
1146 m_destRect.setHeight(m_tileSize.height() + min(yOffset, 0));
1149 void RenderBoxModelObject::BackgroundImageGeometry::useFixedAttachment(const IntPoint& attachmentPoint)
1151 IntPoint alignedPoint = attachmentPoint;
1152 m_phase.move(max(alignedPoint.x() - m_destRect.x(), 0), max(alignedPoint.y() - m_destRect.y(), 0));
1155 void RenderBoxModelObject::BackgroundImageGeometry::clip(const IntRect& clipRect)
1157 m_destRect.intersect(clipRect);
1160 IntPoint RenderBoxModelObject::BackgroundImageGeometry::relativePhase() const
1162 IntPoint phase = m_phase;
1163 phase += m_destRect.location() - m_destOrigin;
1167 bool RenderBoxModelObject::fixedBackgroundPaintsInLocalCoordinates() const
1169 #if USE(ACCELERATED_COMPOSITING)
1173 if (view()->frameView() && view()->frameView()->paintBehavior() & PaintBehaviorFlattenCompositingLayers)
1176 RenderLayer* rootLayer = view()->layer();
1177 if (!rootLayer || !rootLayer->isComposited())
1180 return rootLayer->backing()->backgroundLayerPaintsFixedRootBackground();
1186 void RenderBoxModelObject::calculateBackgroundImageGeometry(const FillLayer* fillLayer, const LayoutRect& paintRect,
1187 BackgroundImageGeometry& geometry, RenderObject* backgroundObject)
1189 LayoutUnit left = 0;
1191 IntSize positioningAreaSize;
1192 IntRect snappedPaintRect = pixelSnappedIntRect(paintRect);
1194 // Determine the background positioning area and set destRect to the background painting area.
1195 // destRect will be adjusted later if the background is non-repeating.
1196 bool fixedAttachment = fillLayer->attachment() == FixedBackgroundAttachment;
1198 #if ENABLE(FAST_MOBILE_SCROLLING)
1199 if (view()->frameView() && view()->frameView()->canBlitOnScroll()) {
1200 // As a side effect of an optimization to blit on scroll, we do not honor the CSS
1201 // property "background-attachment: fixed" because it may result in rendering
1202 // artifacts. Note, these artifacts only appear if we are blitting on scroll of
1203 // a page that has fixed background images.
1204 fixedAttachment = false;
1208 if (!fixedAttachment) {
1209 geometry.setDestRect(snappedPaintRect);
1211 LayoutUnit right = 0;
1212 LayoutUnit bottom = 0;
1213 // Scroll and Local.
1214 if (fillLayer->origin() != BorderFillBox) {
1215 left = borderLeft();
1216 right = borderRight();
1218 bottom = borderBottom();
1219 if (fillLayer->origin() == ContentFillBox) {
1220 left += paddingLeft();
1221 right += paddingRight();
1222 top += paddingTop();
1223 bottom += paddingBottom();
1227 // The background of the box generated by the root element covers the entire canvas including
1228 // its margins. Since those were added in already, we have to factor them out when computing
1229 // the background positioning area.
1231 positioningAreaSize = pixelSnappedIntSize(toRenderBox(this)->size() - LayoutSize(left + right, top + bottom), toRenderBox(this)->location());
1232 left += marginLeft();
1235 positioningAreaSize = pixelSnappedIntSize(paintRect.size() - LayoutSize(left + right, top + bottom), paintRect.location());
1237 IntRect viewportRect = pixelSnappedIntRect(viewRect());
1238 if (fixedBackgroundPaintsInLocalCoordinates())
1239 viewportRect.setLocation(IntPoint());
1240 else if (FrameView* frameView = view()->frameView())
1241 viewportRect.setLocation(IntPoint(frameView->scrollOffsetForFixedPosition()));
1243 geometry.setDestRect(pixelSnappedIntRect(viewportRect));
1244 positioningAreaSize = geometry.destRect().size();
1247 RenderObject* clientForBackgroundImage = backgroundObject ? backgroundObject : this;
1248 IntSize fillTileSize = calculateFillTileSize(fillLayer, positioningAreaSize);
1249 fillLayer->image()->setContainerSizeForRenderer(clientForBackgroundImage, fillTileSize, style()->effectiveZoom());
1250 geometry.setTileSize(fillTileSize);
1252 EFillRepeat backgroundRepeatX = fillLayer->repeatX();
1253 EFillRepeat backgroundRepeatY = fillLayer->repeatY();
1254 RenderView* renderView = view();
1255 int availableWidth = positioningAreaSize.width() - geometry.tileSize().width();
1256 int availableHeight = positioningAreaSize.height() - geometry.tileSize().height();
1258 LayoutUnit computedXPosition = minimumValueForLength(fillLayer->xPosition(), availableWidth, renderView, true);
1259 if (backgroundRepeatX == RepeatFill)
1260 geometry.setPhaseX(geometry.tileSize().width() ? geometry.tileSize().width() - roundToInt(computedXPosition + left) % geometry.tileSize().width() : 0);
1262 int xOffset = fillLayer->backgroundXOrigin() == RightEdge ? availableWidth - computedXPosition : computedXPosition;
1263 geometry.setNoRepeatX(left + xOffset);
1265 LayoutUnit computedYPosition = minimumValueForLength(fillLayer->yPosition(), availableHeight, renderView, true);
1266 if (backgroundRepeatY == RepeatFill)
1267 geometry.setPhaseY(geometry.tileSize().height() ? geometry.tileSize().height() - roundToInt(computedYPosition + top) % geometry.tileSize().height() : 0);
1269 int yOffset = fillLayer->backgroundYOrigin() == BottomEdge ? availableHeight - computedYPosition : computedYPosition;
1270 geometry.setNoRepeatY(top + yOffset);
1273 if (fixedAttachment)
1274 geometry.useFixedAttachment(snappedPaintRect.location());
1276 geometry.clip(snappedPaintRect);
1277 geometry.setDestOrigin(geometry.destRect().location());
1280 static LayoutUnit computeBorderImageSide(Length borderSlice, LayoutUnit borderSide, LayoutUnit imageSide, LayoutUnit boxExtent, RenderView* renderView)
1282 if (borderSlice.isRelative())
1283 return borderSlice.value() * borderSide;
1284 if (borderSlice.isAuto())
1286 return valueForLength(borderSlice, boxExtent, renderView);
1289 bool RenderBoxModelObject::paintNinePieceImage(GraphicsContext* graphicsContext, const LayoutRect& rect, const RenderStyle* style,
1290 const NinePieceImage& ninePieceImage, CompositeOperator op)
1292 StyleImage* styleImage = ninePieceImage.image();
1296 if (!styleImage->isLoaded())
1297 return true; // Never paint a nine-piece image incrementally, but don't paint the fallback borders either.
1299 if (!styleImage->canRender(this, style->effectiveZoom()))
1302 // FIXME: border-image is broken with full page zooming when tiling has to happen, since the tiling function
1303 // doesn't have any understanding of the zoom that is in effect on the tile.
1304 LayoutRect rectWithOutsets = rect;
1305 rectWithOutsets.expand(style->imageOutsets(ninePieceImage));
1306 IntRect borderImageRect = pixelSnappedIntRect(rectWithOutsets);
1308 IntSize imageSize = calculateImageIntrinsicDimensions(styleImage, borderImageRect.size(), DoNotScaleByEffectiveZoom);
1310 // If both values are ‘auto’ then the intrinsic width and/or height of the image should be used, if any.
1311 styleImage->setContainerSizeForRenderer(this, imageSize, style->effectiveZoom());
1313 int imageWidth = imageSize.width();
1314 int imageHeight = imageSize.height();
1315 RenderView* renderView = view();
1317 float imageScaleFactor = styleImage->imageScaleFactor();
1318 int topSlice = min<int>(imageHeight, valueForLength(ninePieceImage.imageSlices().top(), imageHeight, renderView)) * imageScaleFactor;
1319 int rightSlice = min<int>(imageWidth, valueForLength(ninePieceImage.imageSlices().right(), imageWidth, renderView)) * imageScaleFactor;
1320 int bottomSlice = min<int>(imageHeight, valueForLength(ninePieceImage.imageSlices().bottom(), imageHeight, renderView)) * imageScaleFactor;
1321 int leftSlice = min<int>(imageWidth, valueForLength(ninePieceImage.imageSlices().left(), imageWidth, renderView)) * imageScaleFactor;
1323 ENinePieceImageRule hRule = ninePieceImage.horizontalRule();
1324 ENinePieceImageRule vRule = ninePieceImage.verticalRule();
1326 int topWidth = computeBorderImageSide(ninePieceImage.borderSlices().top(), style->borderTopWidth(), topSlice, borderImageRect.height(), renderView);
1327 int rightWidth = computeBorderImageSide(ninePieceImage.borderSlices().right(), style->borderRightWidth(), rightSlice, borderImageRect.width(), renderView);
1328 int bottomWidth = computeBorderImageSide(ninePieceImage.borderSlices().bottom(), style->borderBottomWidth(), bottomSlice, borderImageRect.height(), renderView);
1329 int leftWidth = computeBorderImageSide(ninePieceImage.borderSlices().left(), style->borderLeftWidth(), leftSlice, borderImageRect.width(), renderView);
1331 // Reduce the widths if they're too large.
1332 // The spec says: Given Lwidth as the width of the border image area, Lheight as its height, and Wside as the border image width
1333 // offset for the side, let f = min(Lwidth/(Wleft+Wright), Lheight/(Wtop+Wbottom)). If f < 1, then all W are reduced by
1334 // multiplying them by f.
1335 int borderSideWidth = max(1, leftWidth + rightWidth);
1336 int borderSideHeight = max(1, topWidth + bottomWidth);
1337 float borderSideScaleFactor = min((float)borderImageRect.width() / borderSideWidth, (float)borderImageRect.height() / borderSideHeight);
1338 if (borderSideScaleFactor < 1) {
1339 topWidth *= borderSideScaleFactor;
1340 rightWidth *= borderSideScaleFactor;
1341 bottomWidth *= borderSideScaleFactor;
1342 leftWidth *= borderSideScaleFactor;
1345 bool drawLeft = leftSlice > 0 && leftWidth > 0;
1346 bool drawTop = topSlice > 0 && topWidth > 0;
1347 bool drawRight = rightSlice > 0 && rightWidth > 0;
1348 bool drawBottom = bottomSlice > 0 && bottomWidth > 0;
1349 bool drawMiddle = ninePieceImage.fill() && (imageWidth - leftSlice - rightSlice) > 0 && (borderImageRect.width() - leftWidth - rightWidth) > 0
1350 && (imageHeight - topSlice - bottomSlice) > 0 && (borderImageRect.height() - topWidth - bottomWidth) > 0;
1352 RefPtr<Image> image = styleImage->image(this, imageSize);
1353 ColorSpace colorSpace = style->colorSpace();
1355 float destinationWidth = borderImageRect.width() - leftWidth - rightWidth;
1356 float destinationHeight = borderImageRect.height() - topWidth - bottomWidth;
1358 float sourceWidth = imageWidth - leftSlice - rightSlice;
1359 float sourceHeight = imageHeight - topSlice - bottomSlice;
1361 float leftSideScale = drawLeft ? (float)leftWidth / leftSlice : 1;
1362 float rightSideScale = drawRight ? (float)rightWidth / rightSlice : 1;
1363 float topSideScale = drawTop ? (float)topWidth / topSlice : 1;
1364 float bottomSideScale = drawBottom ? (float)bottomWidth / bottomSlice : 1;
1367 // Paint the top and bottom left corners.
1369 // The top left corner rect is (tx, ty, leftWidth, topWidth)
1370 // The rect to use from within the image is obtained from our slice, and is (0, 0, leftSlice, topSlice)
1372 graphicsContext->drawImage(image.get(), colorSpace, IntRect(borderImageRect.location(), IntSize(leftWidth, topWidth)),
1373 LayoutRect(0, 0, leftSlice, topSlice), op);
1375 // The bottom left corner rect is (tx, ty + h - bottomWidth, leftWidth, bottomWidth)
1376 // The rect to use from within the image is (0, imageHeight - bottomSlice, leftSlice, botomSlice)
1378 graphicsContext->drawImage(image.get(), colorSpace, IntRect(borderImageRect.x(), borderImageRect.maxY() - bottomWidth, leftWidth, bottomWidth),
1379 LayoutRect(0, imageHeight - bottomSlice, leftSlice, bottomSlice), op);
1381 // Paint the left edge.
1382 // Have to scale and tile into the border rect.
1383 if (sourceHeight > 0)
1384 graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(borderImageRect.x(), borderImageRect.y() + topWidth, leftWidth,
1386 IntRect(0, topSlice, leftSlice, sourceHeight),
1387 FloatSize(leftSideScale, leftSideScale), Image::StretchTile, (Image::TileRule)vRule, op);
1391 // Paint the top and bottom right corners
1392 // The top right corner rect is (tx + w - rightWidth, ty, rightWidth, topWidth)
1393 // The rect to use from within the image is obtained from our slice, and is (imageWidth - rightSlice, 0, rightSlice, topSlice)
1395 graphicsContext->drawImage(image.get(), colorSpace, IntRect(borderImageRect.maxX() - rightWidth, borderImageRect.y(), rightWidth, topWidth),
1396 LayoutRect(imageWidth - rightSlice, 0, rightSlice, topSlice), op);
1398 // The bottom right corner rect is (tx + w - rightWidth, ty + h - bottomWidth, rightWidth, bottomWidth)
1399 // The rect to use from within the image is (imageWidth - rightSlice, imageHeight - bottomSlice, rightSlice, bottomSlice)
1401 graphicsContext->drawImage(image.get(), colorSpace, IntRect(borderImageRect.maxX() - rightWidth, borderImageRect.maxY() - bottomWidth, rightWidth, bottomWidth),
1402 LayoutRect(imageWidth - rightSlice, imageHeight - bottomSlice, rightSlice, bottomSlice), op);
1404 // Paint the right edge.
1405 if (sourceHeight > 0)
1406 graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(borderImageRect.maxX() - rightWidth, borderImageRect.y() + topWidth, rightWidth,
1408 IntRect(imageWidth - rightSlice, topSlice, rightSlice, sourceHeight),
1409 FloatSize(rightSideScale, rightSideScale),
1410 Image::StretchTile, (Image::TileRule)vRule, op);
1413 // Paint the top edge.
1414 if (drawTop && sourceWidth > 0)
1415 graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(borderImageRect.x() + leftWidth, borderImageRect.y(), destinationWidth, topWidth),
1416 IntRect(leftSlice, 0, sourceWidth, topSlice),
1417 FloatSize(topSideScale, topSideScale), (Image::TileRule)hRule, Image::StretchTile, op);
1419 // Paint the bottom edge.
1420 if (drawBottom && sourceWidth > 0)
1421 graphicsContext->drawTiledImage(image.get(), colorSpace, IntRect(borderImageRect.x() + leftWidth, borderImageRect.maxY() - bottomWidth,
1422 destinationWidth, bottomWidth),
1423 IntRect(leftSlice, imageHeight - bottomSlice, sourceWidth, bottomSlice),
1424 FloatSize(bottomSideScale, bottomSideScale),
1425 (Image::TileRule)hRule, Image::StretchTile, op);
1427 // Paint the middle.
1429 FloatSize middleScaleFactor(1, 1);
1431 middleScaleFactor.setWidth(topSideScale);
1432 else if (drawBottom)
1433 middleScaleFactor.setWidth(bottomSideScale);
1435 middleScaleFactor.setHeight(leftSideScale);
1437 middleScaleFactor.setHeight(rightSideScale);
1439 // For "stretch" rules, just override the scale factor and replace. We only had to do this for the
1440 // center tile, since sides don't even use the scale factor unless they have a rule other than "stretch".
1441 // The middle however can have "stretch" specified in one axis but not the other, so we have to
1442 // correct the scale here.
1443 if (hRule == StretchImageRule)
1444 middleScaleFactor.setWidth(destinationWidth / sourceWidth);
1446 if (vRule == StretchImageRule)
1447 middleScaleFactor.setHeight(destinationHeight / sourceHeight);
1449 graphicsContext->drawTiledImage(image.get(), colorSpace,
1450 IntRect(borderImageRect.x() + leftWidth, borderImageRect.y() + topWidth, destinationWidth, destinationHeight),
1451 IntRect(leftSlice, topSlice, sourceWidth, sourceHeight),
1452 middleScaleFactor, (Image::TileRule)hRule, (Image::TileRule)vRule, op);
1460 BorderEdge(int edgeWidth, const Color& edgeColor, EBorderStyle edgeStyle, bool edgeIsTransparent, bool edgeIsPresent = true)
1464 , isTransparent(edgeIsTransparent)
1465 , isPresent(edgeIsPresent)
1467 if (style == DOUBLE && edgeWidth < 3)
1474 , isTransparent(false)
1479 bool hasVisibleColorAndStyle() const { return style > BHIDDEN && !isTransparent; }
1480 bool shouldRender() const { return isPresent && width && hasVisibleColorAndStyle(); }
1481 bool presentButInvisible() const { return usedWidth() && !hasVisibleColorAndStyle(); }
1482 bool obscuresBackgroundEdge(float scale) const
1484 if (!isPresent || isTransparent || (width * scale) < 2 || color.hasAlpha() || style == BHIDDEN)
1487 if (style == DOTTED || style == DASHED)
1490 if (style == DOUBLE)
1491 return width >= 5 * scale; // The outer band needs to be >= 2px wide at unit scale.
1495 bool obscuresBackground() const
1497 if (!isPresent || isTransparent || color.hasAlpha() || style == BHIDDEN)
1500 if (style == DOTTED || style == DASHED || style == DOUBLE)
1506 int usedWidth() const { return isPresent ? width : 0; }
1508 void getDoubleBorderStripeWidths(int& outerWidth, int& innerWidth) const
1510 int fullWidth = usedWidth();
1511 outerWidth = fullWidth / 3;
1512 innerWidth = fullWidth * 2 / 3;
1514 // We need certain integer rounding results
1515 if (fullWidth % 3 == 2)
1518 if (fullWidth % 3 == 1)
1529 static bool allCornersClippedOut(const RoundedRect& border, const LayoutRect& clipRect)
1531 LayoutRect boundingRect = border.rect();
1532 if (clipRect.contains(boundingRect))
1535 RoundedRect::Radii radii = border.radii();
1537 LayoutRect topLeftRect(boundingRect.location(), radii.topLeft());
1538 if (clipRect.intersects(topLeftRect))
1541 LayoutRect topRightRect(boundingRect.location(), radii.topRight());
1542 topRightRect.setX(boundingRect.maxX() - topRightRect.width());
1543 if (clipRect.intersects(topRightRect))
1546 LayoutRect bottomLeftRect(boundingRect.location(), radii.bottomLeft());
1547 bottomLeftRect.setY(boundingRect.maxY() - bottomLeftRect.height());
1548 if (clipRect.intersects(bottomLeftRect))
1551 LayoutRect bottomRightRect(boundingRect.location(), radii.bottomRight());
1552 bottomRightRect.setX(boundingRect.maxX() - bottomRightRect.width());
1553 bottomRightRect.setY(boundingRect.maxY() - bottomRightRect.height());
1554 if (clipRect.intersects(bottomRightRect))
1560 static bool borderWillArcInnerEdge(const LayoutSize& firstRadius, const FloatSize& secondRadius)
1562 return !firstRadius.isZero() || !secondRadius.isZero();
1565 enum BorderEdgeFlag {
1566 TopBorderEdge = 1 << BSTop,
1567 RightBorderEdge = 1 << BSRight,
1568 BottomBorderEdge = 1 << BSBottom,
1569 LeftBorderEdge = 1 << BSLeft,
1570 AllBorderEdges = TopBorderEdge | BottomBorderEdge | LeftBorderEdge | RightBorderEdge
1573 static inline BorderEdgeFlag edgeFlagForSide(BoxSide side)
1575 return static_cast<BorderEdgeFlag>(1 << side);
1578 static inline bool includesEdge(BorderEdgeFlags flags, BoxSide side)
1580 return flags & edgeFlagForSide(side);
1583 static inline bool includesAdjacentEdges(BorderEdgeFlags flags)
1585 return (flags & (TopBorderEdge | RightBorderEdge)) == (TopBorderEdge | RightBorderEdge)
1586 || (flags & (RightBorderEdge | BottomBorderEdge)) == (RightBorderEdge | BottomBorderEdge)
1587 || (flags & (BottomBorderEdge | LeftBorderEdge)) == (BottomBorderEdge | LeftBorderEdge)
1588 || (flags & (LeftBorderEdge | TopBorderEdge)) == (LeftBorderEdge | TopBorderEdge);
1591 inline bool edgesShareColor(const BorderEdge& firstEdge, const BorderEdge& secondEdge)
1593 return firstEdge.color == secondEdge.color;
1596 inline bool styleRequiresClipPolygon(EBorderStyle style)
1598 return style == DOTTED || style == DASHED; // These are drawn with a stroke, so we have to clip to get corner miters.
1601 static bool borderStyleFillsBorderArea(EBorderStyle style)
1603 return !(style == DOTTED || style == DASHED || style == DOUBLE);
1606 static bool borderStyleHasInnerDetail(EBorderStyle style)
1608 return style == GROOVE || style == RIDGE || style == DOUBLE;
1611 static bool borderStyleIsDottedOrDashed(EBorderStyle style)
1613 return style == DOTTED || style == DASHED;
1616 // OUTSET darkens the bottom and right (and maybe lightens the top and left)
1617 // INSET darkens the top and left (and maybe lightens the bottom and right)
1618 static inline bool borderStyleHasUnmatchedColorsAtCorner(EBorderStyle style, BoxSide side, BoxSide adjacentSide)
1620 // These styles match at the top/left and bottom/right.
1621 if (style == INSET || style == GROOVE || style == RIDGE || style == OUTSET) {
1622 const BorderEdgeFlags topRightFlags = edgeFlagForSide(BSTop) | edgeFlagForSide(BSRight);
1623 const BorderEdgeFlags bottomLeftFlags = edgeFlagForSide(BSBottom) | edgeFlagForSide(BSLeft);
1625 BorderEdgeFlags flags = edgeFlagForSide(side) | edgeFlagForSide(adjacentSide);
1626 return flags == topRightFlags || flags == bottomLeftFlags;
1631 static inline bool colorsMatchAtCorner(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1633 if (edges[side].shouldRender() != edges[adjacentSide].shouldRender())
1636 if (!edgesShareColor(edges[side], edges[adjacentSide]))
1639 return !borderStyleHasUnmatchedColorsAtCorner(edges[side].style, side, adjacentSide);
1643 static inline bool colorNeedsAntiAliasAtCorner(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1645 if (!edges[side].color.hasAlpha())
1648 if (edges[side].shouldRender() != edges[adjacentSide].shouldRender())
1651 if (!edgesShareColor(edges[side], edges[adjacentSide]))
1654 return borderStyleHasUnmatchedColorsAtCorner(edges[side].style, side, adjacentSide);
1657 // This assumes that we draw in order: top, bottom, left, right.
1658 static inline bool willBeOverdrawn(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[])
1663 if (edges[adjacentSide].presentButInvisible())
1666 if (!edgesShareColor(edges[side], edges[adjacentSide]) && edges[adjacentSide].color.hasAlpha())
1669 if (!borderStyleFillsBorderArea(edges[adjacentSide].style))
1676 // These draw last, so are never overdrawn.
1682 static inline bool borderStylesRequireMitre(BoxSide side, BoxSide adjacentSide, EBorderStyle style, EBorderStyle adjacentStyle)
1684 if (style == DOUBLE || adjacentStyle == DOUBLE || adjacentStyle == GROOVE || adjacentStyle == RIDGE)
1687 if (borderStyleIsDottedOrDashed(style) != borderStyleIsDottedOrDashed(adjacentStyle))
1690 if (style != adjacentStyle)
1693 return borderStyleHasUnmatchedColorsAtCorner(style, side, adjacentSide);
1696 static bool joinRequiresMitre(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[], bool allowOverdraw)
1698 if ((edges[side].isTransparent && edges[adjacentSide].isTransparent) || !edges[adjacentSide].isPresent)
1701 if (allowOverdraw && willBeOverdrawn(side, adjacentSide, edges))
1704 if (!edgesShareColor(edges[side], edges[adjacentSide]))
1707 if (borderStylesRequireMitre(side, adjacentSide, edges[side].style, edges[adjacentSide].style))
1713 void RenderBoxModelObject::paintOneBorderSide(GraphicsContext* graphicsContext, const RenderStyle* style, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
1714 const IntRect& sideRect, BoxSide side, BoxSide adjacentSide1, BoxSide adjacentSide2, const BorderEdge edges[], const Path* path,
1715 BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias, const Color* overrideColor)
1717 const BorderEdge& edgeToRender = edges[side];
1718 ASSERT(edgeToRender.width);
1719 const BorderEdge& adjacentEdge1 = edges[adjacentSide1];
1720 const BorderEdge& adjacentEdge2 = edges[adjacentSide2];
1722 bool mitreAdjacentSide1 = joinRequiresMitre(side, adjacentSide1, edges, !antialias);
1723 bool mitreAdjacentSide2 = joinRequiresMitre(side, adjacentSide2, edges, !antialias);
1725 bool adjacentSide1StylesMatch = colorsMatchAtCorner(side, adjacentSide1, edges);
1726 bool adjacentSide2StylesMatch = colorsMatchAtCorner(side, adjacentSide2, edges);
1728 const Color& colorToPaint = overrideColor ? *overrideColor : edgeToRender.color;
1731 GraphicsContextStateSaver stateSaver(*graphicsContext);
1732 if (innerBorder.isRenderable())
1733 clipBorderSidePolygon(graphicsContext, outerBorder, innerBorder, side, adjacentSide1StylesMatch, adjacentSide2StylesMatch);
1735 clipBorderSideForComplexInnerPath(graphicsContext, outerBorder, innerBorder, side, edges);
1736 float thickness = max(max(edgeToRender.width, adjacentEdge1.width), adjacentEdge2.width);
1737 drawBoxSideFromPath(graphicsContext, outerBorder.rect(), *path, edges, edgeToRender.width, thickness, side, style,
1738 colorToPaint, edgeToRender.style, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
1740 bool clipForStyle = styleRequiresClipPolygon(edgeToRender.style) && (mitreAdjacentSide1 || mitreAdjacentSide2);
1741 bool clipAdjacentSide1 = colorNeedsAntiAliasAtCorner(side, adjacentSide1, edges) && mitreAdjacentSide1;
1742 bool clipAdjacentSide2 = colorNeedsAntiAliasAtCorner(side, adjacentSide2, edges) && mitreAdjacentSide2;
1743 bool shouldClip = clipForStyle || clipAdjacentSide1 || clipAdjacentSide2;
1745 GraphicsContextStateSaver clipStateSaver(*graphicsContext, shouldClip);
1747 bool aliasAdjacentSide1 = clipAdjacentSide1 || (clipForStyle && mitreAdjacentSide1);
1748 bool aliasAdjacentSide2 = clipAdjacentSide2 || (clipForStyle && mitreAdjacentSide2);
1749 clipBorderSidePolygon(graphicsContext, outerBorder, innerBorder, side, !aliasAdjacentSide1, !aliasAdjacentSide2);
1750 // Since we clipped, no need to draw with a mitre.
1751 mitreAdjacentSide1 = false;
1752 mitreAdjacentSide2 = false;
1755 drawLineForBoxSide(graphicsContext, sideRect.x(), sideRect.y(), sideRect.maxX(), sideRect.maxY(), side, colorToPaint, edgeToRender.style,
1756 mitreAdjacentSide1 ? adjacentEdge1.width : 0, mitreAdjacentSide2 ? adjacentEdge2.width : 0, antialias);
1760 static IntRect calculateSideRect(const RoundedRect& outerBorder, const BorderEdge edges[], int side)
1762 IntRect sideRect = outerBorder.rect();
1763 int width = edges[side].width;
1766 sideRect.setHeight(width);
1767 else if (side == BSBottom)
1768 sideRect.shiftYEdgeTo(sideRect.maxY() - width);
1769 else if (side == BSLeft)
1770 sideRect.setWidth(width);
1772 sideRect.shiftXEdgeTo(sideRect.maxX() - width);
1777 void RenderBoxModelObject::paintBorderSides(GraphicsContext* graphicsContext, const RenderStyle* style, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
1778 const IntPoint& innerBorderAdjustment, const BorderEdge edges[], BorderEdgeFlags edgeSet, BackgroundBleedAvoidance bleedAvoidance,
1779 bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias, const Color* overrideColor)
1781 bool renderRadii = outerBorder.isRounded();
1785 roundedPath.addRoundedRect(outerBorder);
1787 // The inner border adjustment for bleed avoidance mode BackgroundBleedBackgroundOverBorder
1788 // is only applied to sideRect, which is okay since BackgroundBleedBackgroundOverBorder
1789 // is only to be used for solid borders and the shape of the border painted by drawBoxSideFromPath
1790 // only depends on sideRect when painting solid borders.
1792 if (edges[BSTop].shouldRender() && includesEdge(edgeSet, BSTop)) {
1793 IntRect sideRect = outerBorder.rect();
1794 sideRect.setHeight(edges[BSTop].width + innerBorderAdjustment.y());
1796 bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSTop].style) || borderWillArcInnerEdge(innerBorder.radii().topLeft(), innerBorder.radii().topRight()));
1797 paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSTop, BSLeft, BSRight, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1800 if (edges[BSBottom].shouldRender() && includesEdge(edgeSet, BSBottom)) {
1801 IntRect sideRect = outerBorder.rect();
1802 sideRect.shiftYEdgeTo(sideRect.maxY() - edges[BSBottom].width - innerBorderAdjustment.y());
1804 bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSBottom].style) || borderWillArcInnerEdge(innerBorder.radii().bottomLeft(), innerBorder.radii().bottomRight()));
1805 paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSBottom, BSLeft, BSRight, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1808 if (edges[BSLeft].shouldRender() && includesEdge(edgeSet, BSLeft)) {
1809 IntRect sideRect = outerBorder.rect();
1810 sideRect.setWidth(edges[BSLeft].width + innerBorderAdjustment.x());
1812 bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSLeft].style) || borderWillArcInnerEdge(innerBorder.radii().bottomLeft(), innerBorder.radii().topLeft()));
1813 paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSLeft, BSTop, BSBottom, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1816 if (edges[BSRight].shouldRender() && includesEdge(edgeSet, BSRight)) {
1817 IntRect sideRect = outerBorder.rect();
1818 sideRect.shiftXEdgeTo(sideRect.maxX() - edges[BSRight].width - innerBorderAdjustment.x());
1820 bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSRight].style) || borderWillArcInnerEdge(innerBorder.radii().bottomRight(), innerBorder.radii().topRight()));
1821 paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSRight, BSTop, BSBottom, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor);
1825 void RenderBoxModelObject::paintTranslucentBorderSides(GraphicsContext* graphicsContext, const RenderStyle* style, const RoundedRect& outerBorder, const RoundedRect& innerBorder, const IntPoint& innerBorderAdjustment,
1826 const BorderEdge edges[], BorderEdgeFlags edgesToDraw, BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias)
1828 // willBeOverdrawn assumes that we draw in order: top, bottom, left, right.
1829 // This is different from BoxSide enum order.
1830 static BoxSide paintOrder[] = { BSTop, BSBottom, BSLeft, BSRight };
1832 while (edgesToDraw) {
1833 // Find undrawn edges sharing a color.
1836 BorderEdgeFlags commonColorEdgeSet = 0;
1837 for (size_t i = 0; i < sizeof(paintOrder) / sizeof(paintOrder[0]); ++i) {
1838 BoxSide currSide = paintOrder[i];
1839 if (!includesEdge(edgesToDraw, currSide))
1843 if (!commonColorEdgeSet) {
1844 commonColor = edges[currSide].color;
1847 includeEdge = edges[currSide].color == commonColor;
1850 commonColorEdgeSet |= edgeFlagForSide(currSide);
1853 bool useTransparencyLayer = includesAdjacentEdges(commonColorEdgeSet) && commonColor.hasAlpha();
1854 if (useTransparencyLayer) {
1855 graphicsContext->beginTransparencyLayer(static_cast<float>(commonColor.alpha()) / 255);
1856 commonColor = Color(commonColor.red(), commonColor.green(), commonColor.blue());
1859 paintBorderSides(graphicsContext, style, outerBorder, innerBorder, innerBorderAdjustment, edges, commonColorEdgeSet, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, &commonColor);
1861 if (useTransparencyLayer)
1862 graphicsContext->endTransparencyLayer();
1864 edgesToDraw &= ~commonColorEdgeSet;
1868 void RenderBoxModelObject::paintBorder(const PaintInfo& info, const LayoutRect& rect, const RenderStyle* style,
1869 BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
1871 GraphicsContext* graphicsContext = info.context;
1872 // border-image is not affected by border-radius.
1873 if (paintNinePieceImage(graphicsContext, rect, style, style->borderImage()))
1876 if (graphicsContext->paintingDisabled())
1879 BorderEdge edges[4];
1880 getBorderEdgeInfo(edges, style, includeLogicalLeftEdge, includeLogicalRightEdge);
1881 RoundedRect outerBorder = style->getRoundedBorderFor(rect, view(), includeLogicalLeftEdge, includeLogicalRightEdge);
1882 RoundedRect innerBorder = style->getRoundedInnerBorderFor(borderInnerRectAdjustedForBleedAvoidance(graphicsContext, rect, bleedAvoidance), includeLogicalLeftEdge, includeLogicalRightEdge);
1884 bool haveAlphaColor = false;
1885 bool haveAllSolidEdges = true;
1886 bool haveAllDoubleEdges = true;
1887 int numEdgesVisible = 4;
1888 bool allEdgesShareColor = true;
1889 int firstVisibleEdge = -1;
1890 BorderEdgeFlags edgesToDraw = 0;
1892 for (int i = BSTop; i <= BSLeft; ++i) {
1893 const BorderEdge& currEdge = edges[i];
1895 if (edges[i].shouldRender())
1896 edgesToDraw |= edgeFlagForSide(static_cast<BoxSide>(i));
1898 if (currEdge.presentButInvisible()) {
1900 allEdgesShareColor = false;
1904 if (!currEdge.width) {
1909 if (firstVisibleEdge == -1)
1910 firstVisibleEdge = i;
1911 else if (currEdge.color != edges[firstVisibleEdge].color)
1912 allEdgesShareColor = false;
1914 if (currEdge.color.hasAlpha())
1915 haveAlphaColor = true;
1917 if (currEdge.style != SOLID)
1918 haveAllSolidEdges = false;
1920 if (currEdge.style != DOUBLE)
1921 haveAllDoubleEdges = false;
1924 // If no corner intersects the clip region, we can pretend outerBorder is
1925 // rectangular to improve performance.
1926 if (haveAllSolidEdges && outerBorder.isRounded() && allCornersClippedOut(outerBorder, info.rect))
1927 outerBorder.setRadii(RoundedRect::Radii());
1929 // isRenderable() check avoids issue described in https://bugs.webkit.org/show_bug.cgi?id=38787
1930 if ((haveAllSolidEdges || haveAllDoubleEdges) && allEdgesShareColor && innerBorder.isRenderable()) {
1931 // Fast path for drawing all solid edges and all unrounded double edges
1932 if (numEdgesVisible == 4 && (outerBorder.isRounded() || haveAlphaColor)
1933 && (haveAllSolidEdges || (!outerBorder.isRounded() && !innerBorder.isRounded()))) {
1936 if (outerBorder.isRounded() && bleedAvoidance != BackgroundBleedUseTransparencyLayer)
1937 path.addRoundedRect(outerBorder);
1939 path.addRect(outerBorder.rect());
1941 if (haveAllDoubleEdges) {
1942 IntRect innerThirdRect = outerBorder.rect();
1943 IntRect outerThirdRect = outerBorder.rect();
1944 for (int side = BSTop; side <= BSLeft; ++side) {
1947 edges[side].getDoubleBorderStripeWidths(outerWidth, innerWidth);
1949 if (side == BSTop) {
1950 innerThirdRect.shiftYEdgeTo(innerThirdRect.y() + innerWidth);
1951 outerThirdRect.shiftYEdgeTo(outerThirdRect.y() + outerWidth);
1952 } else if (side == BSBottom) {
1953 innerThirdRect.setHeight(innerThirdRect.height() - innerWidth);
1954 outerThirdRect.setHeight(outerThirdRect.height() - outerWidth);
1955 } else if (side == BSLeft) {
1956 innerThirdRect.shiftXEdgeTo(innerThirdRect.x() + innerWidth);
1957 outerThirdRect.shiftXEdgeTo(outerThirdRect.x() + outerWidth);
1959 innerThirdRect.setWidth(innerThirdRect.width() - innerWidth);
1960 outerThirdRect.setWidth(outerThirdRect.width() - outerWidth);
1964 RoundedRect outerThird = outerBorder;
1965 RoundedRect innerThird = innerBorder;
1966 innerThird.setRect(innerThirdRect);
1967 outerThird.setRect(outerThirdRect);
1969 if (outerThird.isRounded() && bleedAvoidance != BackgroundBleedUseTransparencyLayer)
1970 path.addRoundedRect(outerThird);
1972 path.addRect(outerThird.rect());
1974 if (innerThird.isRounded() && bleedAvoidance != BackgroundBleedUseTransparencyLayer)
1975 path.addRoundedRect(innerThird);
1977 path.addRect(innerThird.rect());
1980 if (innerBorder.isRounded())
1981 path.addRoundedRect(innerBorder);
1983 path.addRect(innerBorder.rect());
1985 graphicsContext->setFillRule(RULE_EVENODD);
1986 graphicsContext->setFillColor(edges[firstVisibleEdge].color, style->colorSpace());
1987 graphicsContext->fillPath(path);
1990 // Avoid creating transparent layers
1991 if (haveAllSolidEdges && numEdgesVisible != 4 && !outerBorder.isRounded() && haveAlphaColor) {
1994 for (int i = BSTop; i <= BSLeft; ++i) {
1995 const BorderEdge& currEdge = edges[i];
1996 if (currEdge.shouldRender()) {
1997 IntRect sideRect = calculateSideRect(outerBorder, edges, i);
1998 path.addRect(sideRect);
2002 graphicsContext->setFillRule(RULE_NONZERO);
2003 graphicsContext->setFillColor(edges[firstVisibleEdge].color, style->colorSpace());
2004 graphicsContext->fillPath(path);
2009 bool clipToOuterBorder = outerBorder.isRounded();
2010 GraphicsContextStateSaver stateSaver(*graphicsContext, clipToOuterBorder);
2011 if (clipToOuterBorder) {
2012 // Clip to the inner and outer radii rects.
2013 if (bleedAvoidance != BackgroundBleedUseTransparencyLayer)
2014 graphicsContext->clipRoundedRect(outerBorder);
2015 // isRenderable() check avoids issue described in https://bugs.webkit.org/show_bug.cgi?id=38787
2016 // The inside will be clipped out later (in clipBorderSideForComplexInnerPath)
2017 if (innerBorder.isRenderable())
2018 graphicsContext->clipOutRoundedRect(innerBorder);
2021 // If only one edge visible antialiasing doesn't create seams
2022 bool antialias = shouldAntialiasLines(graphicsContext) || numEdgesVisible == 1;
2023 RoundedRect unadjustedInnerBorder = (bleedAvoidance == BackgroundBleedBackgroundOverBorder) ? style->getRoundedInnerBorderFor(rect, includeLogicalLeftEdge, includeLogicalRightEdge) : innerBorder;
2024 IntPoint innerBorderAdjustment(innerBorder.rect().x() - unadjustedInnerBorder.rect().x(), innerBorder.rect().y() - unadjustedInnerBorder.rect().y());
2026 paintTranslucentBorderSides(graphicsContext, style, outerBorder, unadjustedInnerBorder, innerBorderAdjustment, edges, edgesToDraw, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias);
2028 paintBorderSides(graphicsContext, style, outerBorder, unadjustedInnerBorder, innerBorderAdjustment, edges, edgesToDraw, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias);
2031 void RenderBoxModelObject::drawBoxSideFromPath(GraphicsContext* graphicsContext, const LayoutRect& borderRect, const Path& borderPath, const BorderEdge edges[],
2032 float thickness, float drawThickness, BoxSide side, const RenderStyle* style,
2033 Color color, EBorderStyle borderStyle, BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
2038 if (borderStyle == DOUBLE && thickness < 3)
2039 borderStyle = SOLID;
2041 switch (borderStyle) {
2047 graphicsContext->setStrokeColor(color, style->colorSpace());
2049 // The stroke is doubled here because the provided path is the
2050 // outside edge of the border so half the stroke is clipped off.
2051 // The extra multiplier is so that the clipping mask can antialias
2052 // the edges to prevent jaggies.
2053 graphicsContext->setStrokeThickness(drawThickness * 2 * 1.1f);
2054 graphicsContext->setStrokeStyle(borderStyle == DASHED ? DashedStroke : DottedStroke);
2056 // If the number of dashes that fit in the path is odd and non-integral then we
2057 // will have an awkwardly-sized dash at the end of the path. To try to avoid that
2058 // here, we simply make the whitespace dashes ever so slightly bigger.
2059 // FIXME: This could be even better if we tried to manipulate the dash offset
2060 // and possibly the gapLength to get the corners dash-symmetrical.
2061 float dashLength = thickness * ((borderStyle == DASHED) ? 3.0f : 1.0f);
2062 float gapLength = dashLength;
2063 float numberOfDashes = borderPath.length() / dashLength;
2064 // Don't try to show dashes if we have less than 2 dashes + 2 gaps.
2065 // FIXME: should do this test per side.
2066 if (numberOfDashes >= 4) {
2067 bool evenNumberOfFullDashes = !((int)numberOfDashes % 2);
2068 bool integralNumberOfDashes = !(numberOfDashes - (int)numberOfDashes);
2069 if (!evenNumberOfFullDashes && !integralNumberOfDashes) {
2070 float numberOfGaps = numberOfDashes / 2;
2071 gapLength += (dashLength / numberOfGaps);
2075 lineDash.append(dashLength);
2076 lineDash.append(gapLength);
2077 graphicsContext->setLineDash(lineDash, dashLength);
2080 // FIXME: stroking the border path causes issues with tight corners:
2081 // https://bugs.webkit.org/show_bug.cgi?id=58711
2082 // Also, to get the best appearance we should stroke a path between the two borders.
2083 graphicsContext->strokePath(borderPath);
2087 // Get the inner border rects for both the outer border line and the inner border line
2088 int outerBorderTopWidth;
2089 int innerBorderTopWidth;
2090 edges[BSTop].getDoubleBorderStripeWidths(outerBorderTopWidth, innerBorderTopWidth);
2092 int outerBorderRightWidth;
2093 int innerBorderRightWidth;
2094 edges[BSRight].getDoubleBorderStripeWidths(outerBorderRightWidth, innerBorderRightWidth);
2096 int outerBorderBottomWidth;
2097 int innerBorderBottomWidth;
2098 edges[BSBottom].getDoubleBorderStripeWidths(outerBorderBottomWidth, innerBorderBottomWidth);
2100 int outerBorderLeftWidth;
2101 int innerBorderLeftWidth;
2102 edges[BSLeft].getDoubleBorderStripeWidths(outerBorderLeftWidth, innerBorderLeftWidth);
2104 // Draw inner border line
2106 GraphicsContextStateSaver stateSaver(*graphicsContext);
2107 RoundedRect innerClip = style->getRoundedInnerBorderFor(borderRect,
2108 innerBorderTopWidth, innerBorderBottomWidth, innerBorderLeftWidth, innerBorderRightWidth,
2109 includeLogicalLeftEdge, includeLogicalRightEdge);
2111 graphicsContext->clipRoundedRect(innerClip);
2112 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, SOLID, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
2115 // Draw outer border line
2117 GraphicsContextStateSaver stateSaver(*graphicsContext);
2118 LayoutRect outerRect = borderRect;
2119 if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) {
2120 outerRect.inflate(1);
2121 ++outerBorderTopWidth;
2122 ++outerBorderBottomWidth;
2123 ++outerBorderLeftWidth;
2124 ++outerBorderRightWidth;
2127 RoundedRect outerClip = style->getRoundedInnerBorderFor(outerRect,
2128 outerBorderTopWidth, outerBorderBottomWidth, outerBorderLeftWidth, outerBorderRightWidth,
2129 includeLogicalLeftEdge, includeLogicalRightEdge);
2130 graphicsContext->clipOutRoundedRect(outerClip);
2131 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, SOLID, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
2140 if (borderStyle == GROOVE) {
2148 // Paint full border
2149 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, s1, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
2152 GraphicsContextStateSaver stateSaver(*graphicsContext);
2153 LayoutUnit topWidth = edges[BSTop].usedWidth() / 2;
2154 LayoutUnit bottomWidth = edges[BSBottom].usedWidth() / 2;
2155 LayoutUnit leftWidth = edges[BSLeft].usedWidth() / 2;
2156 LayoutUnit rightWidth = edges[BSRight].usedWidth() / 2;
2158 RoundedRect clipRect = style->getRoundedInnerBorderFor(borderRect,
2159 topWidth, bottomWidth, leftWidth, rightWidth,
2160 includeLogicalLeftEdge, includeLogicalRightEdge);
2162 graphicsContext->clipRoundedRect(clipRect);
2163 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, s2, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge);
2167 if (side == BSTop || side == BSLeft)
2168 color = color.dark();
2171 if (side == BSBottom || side == BSRight)
2172 color = color.dark();
2178 graphicsContext->setStrokeStyle(NoStroke);
2179 graphicsContext->setFillColor(color, style->colorSpace());
2180 graphicsContext->drawRect(pixelSnappedIntRect(borderRect));
2183 static void findInnerVertex(const FloatPoint& outerCorner, const FloatPoint& innerCorner, const FloatPoint& centerPoint, FloatPoint& result)
2185 // If the line between outer and inner corner is towards the horizontal, intersect with a vertical line through the center,
2186 // otherwise with a horizontal line through the center. The points that form this line are arbitrary (we use 0, 100).
2187 // Note that if findIntersection fails, it will leave result untouched.
2188 float diffInnerOuterX = fabs(innerCorner.x() - outerCorner.x());
2189 float diffInnerOuterY = fabs(innerCorner.y() - outerCorner.y());
2190 float diffCenterOuterX = fabs(centerPoint.x() - outerCorner.x());
2191 float diffCenterOuterY = fabs(centerPoint.y() - outerCorner.y());
2192 if (diffInnerOuterY * diffCenterOuterX < diffCenterOuterY * diffInnerOuterX)
2193 findIntersection(outerCorner, innerCorner, FloatPoint(centerPoint.x(), 0), FloatPoint(centerPoint.x(), 100), result);
2195 findIntersection(outerCorner, innerCorner, FloatPoint(0, centerPoint.y()), FloatPoint(100, centerPoint.y()), result);
2198 void RenderBoxModelObject::clipBorderSidePolygon(GraphicsContext* graphicsContext, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
2199 BoxSide side, bool firstEdgeMatches, bool secondEdgeMatches)
2203 const LayoutRect& outerRect = outerBorder.rect();
2204 const LayoutRect& innerRect = innerBorder.rect();
2206 FloatPoint centerPoint(innerRect.location().x() + static_cast<float>(innerRect.width()) / 2, innerRect.location().y() + static_cast<float>(innerRect.height()) / 2);
2208 // For each side, create a quad that encompasses all parts of that side that may draw,
2209 // including areas inside the innerBorder.
2211 // 0----------------3
2213 // |\ 1----------- 2 /|
2218 // |/ 1------------2 \|
2220 // 0----------------3
2224 quad[0] = outerRect.minXMinYCorner();
2225 quad[1] = innerRect.minXMinYCorner();
2226 quad[2] = innerRect.maxXMinYCorner();
2227 quad[3] = outerRect.maxXMinYCorner();
2229 if (!innerBorder.radii().topLeft().isZero())
2230 findInnerVertex(outerRect.minXMinYCorner(), innerRect.minXMinYCorner(), centerPoint, quad[1]);
2232 if (!innerBorder.radii().topRight().isZero())
2233 findInnerVertex(outerRect.maxXMinYCorner(), innerRect.maxXMinYCorner(), centerPoint, quad[2]);
2237 quad[0] = outerRect.minXMinYCorner();
2238 quad[1] = innerRect.minXMinYCorner();
2239 quad[2] = innerRect.minXMaxYCorner();
2240 quad[3] = outerRect.minXMaxYCorner();
2242 if (!innerBorder.radii().topLeft().isZero())
2243 findInnerVertex(outerRect.minXMinYCorner(), innerRect.minXMinYCorner(), centerPoint, quad[1]);
2245 if (!innerBorder.radii().bottomLeft().isZero())
2246 findInnerVertex(outerRect.minXMaxYCorner(), innerRect.minXMaxYCorner(), centerPoint, quad[2]);
2250 quad[0] = outerRect.minXMaxYCorner();
2251 quad[1] = innerRect.minXMaxYCorner();
2252 quad[2] = innerRect.maxXMaxYCorner();
2253 quad[3] = outerRect.maxXMaxYCorner();
2255 if (!innerBorder.radii().bottomLeft().isZero())
2256 findInnerVertex(outerRect.minXMaxYCorner(), innerRect.minXMaxYCorner(), centerPoint, quad[1]);
2258 if (!innerBorder.radii().bottomRight().isZero())
2259 findInnerVertex(outerRect.maxXMaxYCorner(), innerRect.maxXMaxYCorner(), centerPoint, quad[2]);
2263 quad[0] = outerRect.maxXMinYCorner();
2264 quad[1] = innerRect.maxXMinYCorner();
2265 quad[2] = innerRect.maxXMaxYCorner();
2266 quad[3] = outerRect.maxXMaxYCorner();
2268 if (!innerBorder.radii().topRight().isZero())
2269 findInnerVertex(outerRect.maxXMinYCorner(), innerRect.maxXMinYCorner(), centerPoint, quad[1]);
2271 if (!innerBorder.radii().bottomRight().isZero())
2272 findInnerVertex(outerRect.maxXMaxYCorner(), innerRect.maxXMaxYCorner(), centerPoint, quad[2]);
2276 // If the border matches both of its adjacent sides, don't anti-alias the clip, and
2277 // if neither side matches, anti-alias the clip.
2278 if (firstEdgeMatches == secondEdgeMatches) {
2279 graphicsContext->clipConvexPolygon(4, quad, !firstEdgeMatches);
2283 // Square off the end which shouldn't be affected by antialiasing, and clip.
2284 FloatPoint firstQuad[4];
2285 firstQuad[0] = quad[0];
2286 firstQuad[1] = quad[1];
2287 firstQuad[2] = side == BSTop || side == BSBottom ? FloatPoint(quad[3].x(), quad[2].y())
2288 : FloatPoint(quad[2].x(), quad[3].y());
2289 firstQuad[3] = quad[3];
2290 graphicsContext->clipConvexPolygon(4, firstQuad, !firstEdgeMatches);
2292 FloatPoint secondQuad[4];
2293 secondQuad[0] = quad[0];
2294 secondQuad[1] = side == BSTop || side == BSBottom ? FloatPoint(quad[0].x(), quad[1].y())
2295 : FloatPoint(quad[1].x(), quad[0].y());
2296 secondQuad[2] = quad[2];
2297 secondQuad[3] = quad[3];
2298 // Antialiasing affects the second side.
2299 graphicsContext->clipConvexPolygon(4, secondQuad, !secondEdgeMatches);
2302 static IntRect calculateSideRectIncludingInner(const RoundedRect& outerBorder, const BorderEdge edges[], BoxSide side)
2304 IntRect sideRect = outerBorder.rect();
2309 width = sideRect.height() - edges[BSBottom].width;
2310 sideRect.setHeight(width);
2313 width = sideRect.height() - edges[BSTop].width;
2314 sideRect.shiftYEdgeTo(sideRect.maxY() - width);
2317 width = sideRect.width() - edges[BSRight].width;
2318 sideRect.setWidth(width);
2321 width = sideRect.width() - edges[BSLeft].width;
2322 sideRect.shiftXEdgeTo(sideRect.maxX() - width);
2329 static RoundedRect calculateAdjustedInnerBorder(const RoundedRect&innerBorder, BoxSide side)
2331 // Expand the inner border as necessary to make it a rounded rect (i.e. radii contained within each edge).
2332 // This function relies on the fact we only get radii not contained within each edge if one of the radii
2333 // for an edge is zero, so we can shift the arc towards the zero radius corner.
2334 RoundedRect::Radii newRadii = innerBorder.radii();
2335 IntRect newRect = innerBorder.rect();
2342 overshoot = newRadii.topLeft().width() + newRadii.topRight().width() - newRect.width();
2343 if (overshoot > 0) {
2344 ASSERT(!(newRadii.topLeft().width() && newRadii.topRight().width()));
2345 newRect.setWidth(newRect.width() + overshoot);
2346 if (!newRadii.topLeft().width())
2347 newRect.move(-overshoot, 0);
2349 newRadii.setBottomLeft(IntSize(0, 0));
2350 newRadii.setBottomRight(IntSize(0, 0));
2351 maxRadii = max(newRadii.topLeft().height(), newRadii.topRight().height());
2352 if (maxRadii > newRect.height())
2353 newRect.setHeight(maxRadii);
2357 overshoot = newRadii.bottomLeft().width() + newRadii.bottomRight().width() - newRect.width();
2358 if (overshoot > 0) {
2359 ASSERT(!(newRadii.bottomLeft().width() && newRadii.bottomRight().width()));
2360 newRect.setWidth(newRect.width() + overshoot);
2361 if (!newRadii.bottomLeft().width())
2362 newRect.move(-overshoot, 0);
2364 newRadii.setTopLeft(IntSize(0, 0));
2365 newRadii.setTopRight(IntSize(0, 0));
2366 maxRadii = max(newRadii.bottomLeft().height(), newRadii.bottomRight().height());
2367 if (maxRadii > newRect.height()) {
2368 newRect.move(0, newRect.height() - maxRadii);
2369 newRect.setHeight(maxRadii);
2374 overshoot = newRadii.topLeft().height() + newRadii.bottomLeft().height() - newRect.height();
2375 if (overshoot > 0) {
2376 ASSERT(!(newRadii.topLeft().height() && newRadii.bottomLeft().height()));
2377 newRect.setHeight(newRect.height() + overshoot);
2378 if (!newRadii.topLeft().height())
2379 newRect.move(0, -overshoot);
2381 newRadii.setTopRight(IntSize(0, 0));
2382 newRadii.setBottomRight(IntSize(0, 0));
2383 maxRadii = max(newRadii.topLeft().width(), newRadii.bottomLeft().width());
2384 if (maxRadii > newRect.width())
2385 newRect.setWidth(maxRadii);
2389 overshoot = newRadii.topRight().height() + newRadii.bottomRight().height() - newRect.height();
2390 if (overshoot > 0) {
2391 ASSERT(!(newRadii.topRight().height() && newRadii.bottomRight().height()));
2392 newRect.setHeight(newRect.height() + overshoot);
2393 if (!newRadii.topRight().height())
2394 newRect.move(0, -overshoot);
2396 newRadii.setTopLeft(IntSize(0, 0));
2397 newRadii.setBottomLeft(IntSize(0, 0));
2398 maxRadii = max(newRadii.topRight().width(), newRadii.bottomRight().width());
2399 if (maxRadii > newRect.width()) {
2400 newRect.move(newRect.width() - maxRadii, 0);
2401 newRect.setWidth(maxRadii);
2406 return RoundedRect(newRect, newRadii);
2409 void RenderBoxModelObject::clipBorderSideForComplexInnerPath(GraphicsContext* graphicsContext, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
2410 BoxSide side, const class BorderEdge edges[])
2412 graphicsContext->clip(calculateSideRectIncludingInner(outerBorder, edges, side));
2413 graphicsContext->clipOutRoundedRect(calculateAdjustedInnerBorder(innerBorder, side));
2416 void RenderBoxModelObject::getBorderEdgeInfo(BorderEdge edges[], const RenderStyle* style, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
2418 bool horizontal = style->isHorizontalWritingMode();
2420 edges[BSTop] = BorderEdge(style->borderTopWidth(),
2421 style->visitedDependentColor(CSSPropertyBorderTopColor),
2422 style->borderTopStyle(),
2423 style->borderTopIsTransparent(),
2424 horizontal || includeLogicalLeftEdge);
2426 edges[BSRight] = BorderEdge(style->borderRightWidth(),
2427 style->visitedDependentColor(CSSPropertyBorderRightColor),
2428 style->borderRightStyle(),
2429 style->borderRightIsTransparent(),
2430 !horizontal || includeLogicalRightEdge);
2432 edges[BSBottom] = BorderEdge(style->borderBottomWidth(),
2433 style->visitedDependentColor(CSSPropertyBorderBottomColor),
2434 style->borderBottomStyle(),
2435 style->borderBottomIsTransparent(),
2436 horizontal || includeLogicalRightEdge);
2438 edges[BSLeft] = BorderEdge(style->borderLeftWidth(),
2439 style->visitedDependentColor(CSSPropertyBorderLeftColor),
2440 style->borderLeftStyle(),
2441 style->borderLeftIsTransparent(),
2442 !horizontal || includeLogicalLeftEdge);
2445 bool RenderBoxModelObject::borderObscuresBackgroundEdge(const FloatSize& contextScale) const
2447 BorderEdge edges[4];
2448 getBorderEdgeInfo(edges, style());
2450 for (int i = BSTop; i <= BSLeft; ++i) {
2451 const BorderEdge& currEdge = edges[i];
2452 // FIXME: for vertical text
2453 float axisScale = (i == BSTop || i == BSBottom) ? contextScale.height() : contextScale.width();
2454 if (!currEdge.obscuresBackgroundEdge(axisScale))
2461 bool RenderBoxModelObject::borderObscuresBackground() const
2463 if (!style()->hasBorder())
2466 // Bail if we have any border-image for now. We could look at the image alpha to improve this.
2467 if (style()->borderImage().image())
2470 BorderEdge edges[4];
2471 getBorderEdgeInfo(edges, style());
2473 for (int i = BSTop; i <= BSLeft; ++i) {
2474 const BorderEdge& currEdge = edges[i];
2475 if (!currEdge.obscuresBackground())
2482 bool RenderBoxModelObject::boxShadowShouldBeAppliedToBackground(BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* inlineFlowBox) const
2484 if (bleedAvoidance != BackgroundBleedNone)
2487 if (style()->hasAppearance())
2490 bool hasOneNormalBoxShadow = false;
2491 for (const ShadowData* currentShadow = style()->boxShadow(); currentShadow; currentShadow = currentShadow->next()) {
2492 if (currentShadow->style() != Normal)
2495 if (hasOneNormalBoxShadow)
2497 hasOneNormalBoxShadow = true;
2499 if (currentShadow->spread())
2503 if (!hasOneNormalBoxShadow)
2506 Color backgroundColor = style()->visitedDependentColor(CSSPropertyBackgroundColor);
2507 if (!backgroundColor.isValid() || backgroundColor.hasAlpha())
2510 const FillLayer* lastBackgroundLayer = style()->backgroundLayers();
2511 for (const FillLayer* next = lastBackgroundLayer->next(); next; next = lastBackgroundLayer->next())
2512 lastBackgroundLayer = next;
2514 if (lastBackgroundLayer->clip() != BorderFillBox)
2517 if (lastBackgroundLayer->image() && style()->hasBorderRadius())
2520 if (inlineFlowBox && !inlineFlowBox->boxShadowCanBeAppliedToBackground(*lastBackgroundLayer))
2523 if (hasOverflowClip() && lastBackgroundLayer->attachment() == LocalBackgroundAttachment)
2529 static inline IntRect areaCastingShadowInHole(const IntRect& holeRect, int shadowExtent, int shadowSpread, const IntSize& shadowOffset)
2531 IntRect bounds(holeRect);
2533 bounds.inflate(shadowExtent);
2535 if (shadowSpread < 0)
2536 bounds.inflate(-shadowSpread);
2538 IntRect offsetBounds = bounds;
2539 offsetBounds.move(-shadowOffset);
2540 return unionRect(bounds, offsetBounds);
2543 void RenderBoxModelObject::paintBoxShadow(const PaintInfo& info, const LayoutRect& paintRect, const RenderStyle* s, ShadowStyle shadowStyle, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
2545 // FIXME: Deal with border-image. Would be great to use border-image as a mask.
2546 GraphicsContext* context = info.context;
2547 if (context->paintingDisabled() || !s->boxShadow())
2550 RoundedRect border = (shadowStyle == Inset) ? s->getRoundedInnerBorderFor(paintRect, includeLogicalLeftEdge, includeLogicalRightEdge)
2551 : s->getRoundedBorderFor(paintRect, view(), includeLogicalLeftEdge, includeLogicalRightEdge);
2553 bool hasBorderRadius = s->hasBorderRadius();
2554 bool isHorizontal = s->isHorizontalWritingMode();
2556 bool hasOpaqueBackground = s->visitedDependentColor(CSSPropertyBackgroundColor).isValid() && s->visitedDependentColor(CSSPropertyBackgroundColor).alpha() == 255;
2557 for (const ShadowData* shadow = s->boxShadow(); shadow; shadow = shadow->next()) {
2558 if (shadow->style() != shadowStyle)
2561 IntSize shadowOffset(shadow->x(), shadow->y());
2562 int shadowRadius = shadow->radius();
2563 int shadowPaintingExtent = shadow->paintingExtent();
2564 int shadowSpread = shadow->spread();
2566 if (shadowOffset.isZero() && !shadowRadius && !shadowSpread)
2569 const Color& shadowColor = shadow->color();
2571 if (shadow->style() == Normal) {
2572 RoundedRect fillRect = border;
2573 fillRect.inflate(shadowSpread);
2574 if (fillRect.isEmpty())
2577 IntRect shadowRect(border.rect());
2578 shadowRect.inflate(shadowPaintingExtent + shadowSpread);
2579 shadowRect.move(shadowOffset);
2581 GraphicsContextStateSaver stateSaver(*context);
2582 context->clip(shadowRect);
2584 // Move the fill just outside the clip, adding 1 pixel separation so that the fill does not
2585 // bleed in (due to antialiasing) if the context is transformed.
2586 IntSize extraOffset(paintRect.pixelSnappedWidth() + max(0, shadowOffset.width()) + shadowPaintingExtent + 2 * shadowSpread + 1, 0);
2587 shadowOffset -= extraOffset;
2588 fillRect.move(extraOffset);
2590 if (shadow->isWebkitBoxShadow())
2591 context->setLegacyShadow(shadowOffset, shadowRadius, shadowColor, s->colorSpace());
2593 context->setShadow(shadowOffset, shadowRadius, shadowColor, s->colorSpace());
2595 if (hasBorderRadius) {
2596 RoundedRect rectToClipOut = border;
2598 // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
2599 // when painting the shadow. On the other hand, it introduces subpixel gaps along the
2600 // corners. Those are avoided by insetting the clipping path by one pixel.
2601 if (hasOpaqueBackground) {
2602 rectToClipOut.inflateWithRadii(-1);
2605 if (!rectToClipOut.isEmpty())
2606 context->clipOutRoundedRect(rectToClipOut);
2608 RoundedRect influenceRect(shadowRect, border.radii());
2609 influenceRect.expandRadii(2 * shadowPaintingExtent + shadowSpread);
2610 if (allCornersClippedOut(influenceRect, info.rect))
2611 context->fillRect(fillRect.rect(), Color::black, s->colorSpace());
2613 fillRect.expandRadii(shadowSpread);
2614 if (!fillRect.isRenderable())
2615 fillRect.adjustRadii();
2616 context->fillRoundedRect(fillRect, Color::black, s->colorSpace());
2619 IntRect rectToClipOut = border.rect();
2621 // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
2622 // when painting the shadow. On the other hand, it introduces subpixel gaps along the
2623 // edges if they are not pixel-aligned. Those are avoided by insetting the clipping path
2625 if (hasOpaqueBackground) {
2626 // FIXME: The function to decide on the policy based on the transform should be a named function.
2627 // FIXME: It's not clear if this check is right. What about integral scale factors?
2628 AffineTransform transform = context->getCTM();
2629 if (transform.a() != 1 || (transform.d() != 1 && transform.d() != -1) || transform.b() || transform.c())
2630 rectToClipOut.inflate(-1);
2633 if (!rectToClipOut.isEmpty())
2634 context->clipOut(rectToClipOut);
2635 context->fillRect(fillRect.rect(), Color::black, s->colorSpace());
2639 IntRect holeRect(border.rect());
2640 holeRect.inflate(-shadowSpread);
2642 if (holeRect.isEmpty()) {
2643 if (hasBorderRadius)
2644 context->fillRoundedRect(border, shadowColor, s->colorSpace());
2646 context->fillRect(border.rect(), shadowColor, s->colorSpace());
2650 if (!includeLogicalLeftEdge) {
2652 holeRect.move(-max(shadowOffset.width(), 0) - shadowPaintingExtent, 0);
2653 holeRect.setWidth(holeRect.width() + max(shadowOffset.width(), 0) + shadowPaintingExtent);
2655 holeRect.move(0, -max(shadowOffset.height(), 0) - shadowPaintingExtent);
2656 holeRect.setHeight(holeRect.height() + max(shadowOffset.height(), 0) + shadowPaintingExtent);
2659 if (!includeLogicalRightEdge) {
2661 holeRect.setWidth(holeRect.width() - min(shadowOffset.width(), 0) + shadowPaintingExtent);
2663 holeRect.setHeight(holeRect.height() - min(shadowOffset.height(), 0) + shadowPaintingExtent);
2666 Color fillColor(shadowColor.red(), shadowColor.green(), shadowColor.blue(), 255);
2668 IntRect outerRect = areaCastingShadowInHole(border.rect(), shadowPaintingExtent, shadowSpread, shadowOffset);
2669 RoundedRect roundedHole(holeRect, border.radii());
2671 GraphicsContextStateSaver stateSaver(*context);
2672 if (hasBorderRadius) {
2674 path.addRoundedRect(border);
2675 context->clip(path);
2676 roundedHole.shrinkRadii(shadowSpread);
2678 context->clip(border.rect());
2680 IntSize extraOffset(2 * paintRect.pixelSnappedWidth() + max(0, shadowOffset.width()) + shadowPaintingExtent - 2 * shadowSpread + 1, 0);
2681 context->translate(extraOffset.width(), extraOffset.height());
2682 shadowOffset -= extraOffset;
2684 if (shadow->isWebkitBoxShadow())
2685 context->setLegacyShadow(shadowOffset, shadowRadius, shadowColor, s->colorSpace());
2687 context->setShadow(shadowOffset, shadowRadius, shadowColor, s->colorSpace());
2689 context->fillRectWithRoundedHole(outerRect, roundedHole, fillColor, s->colorSpace());
2694 LayoutUnit RenderBoxModelObject::containingBlockLogicalWidthForContent() const
2696 return containingBlock()->availableLogicalWidth();
2699 RenderBoxModelObject* RenderBoxModelObject::continuation() const
2701 if (!continuationMap)
2703 return continuationMap->get(this);
2706 void RenderBoxModelObject::setContinuation(RenderBoxModelObject* continuation)
2709 if (!continuationMap)
2710 continuationMap = new ContinuationMap;
2711 continuationMap->set(this, continuation);
2713 if (continuationMap)
2714 continuationMap->remove(this);
2718 RenderObject* RenderBoxModelObject::firstLetterRemainingText() const
2720 if (!firstLetterRemainingTextMap)
2722 return firstLetterRemainingTextMap->get(this);
2725 void RenderBoxModelObject::setFirstLetterRemainingText(RenderObject* remainingText)
2727 if (remainingText) {
2728 if (!firstLetterRemainingTextMap)
2729 firstLetterRemainingTextMap = new FirstLetterRemainingTextMap;
2730 firstLetterRemainingTextMap->set(this, remainingText);
2731 } else if (firstLetterRemainingTextMap)
2732 firstLetterRemainingTextMap->remove(this);
2735 LayoutRect RenderBoxModelObject::localCaretRectForEmptyElement(LayoutUnit width, LayoutUnit textIndentOffset)
2737 ASSERT(!firstChild());
2739 // FIXME: This does not take into account either :first-line or :first-letter
2740 // However, as soon as some content is entered, the line boxes will be
2741 // constructed and this kludge is not called any more. So only the caret size
2742 // of an empty :first-line'd block is wrong. I think we can live with that.
2743 RenderStyle* currentStyle = firstLineStyle();
2744 LayoutUnit height = lineHeight(true, currentStyle->isHorizontalWritingMode() ? HorizontalLine : VerticalLine);
2746 enum CaretAlignment { alignLeft, alignRight, alignCenter };
2748 CaretAlignment alignment = alignLeft;
2750 switch (currentStyle->textAlign()) {
2756 alignment = alignCenter;
2760 alignment = alignRight;
2764 if (!currentStyle->isLeftToRightDirection())
2765 alignment = alignRight;
2768 if (currentStyle->isLeftToRightDirection())
2769 alignment = alignRight;
2773 LayoutUnit x = borderLeft() + paddingLeft();
2774 LayoutUnit maxX = width - borderRight() - paddingRight();
2776 switch (alignment) {
2778 if (currentStyle->isLeftToRightDirection())
2779 x += textIndentOffset;
2783 if (currentStyle->isLeftToRightDirection())
2784 x += textIndentOffset / 2;
2786 x -= textIndentOffset / 2;
2789 x = maxX - caretWidth;
2790 if (!currentStyle->isLeftToRightDirection())
2791 x -= textIndentOffset;
2794 x = min(x, max<LayoutUnit>(maxX - caretWidth, 0));
2796 LayoutUnit y = paddingTop() + borderTop();
2798 return currentStyle->isHorizontalWritingMode() ? LayoutRect(x, y, caretWidth, height) : LayoutRect(y, x, height, caretWidth);
2801 bool RenderBoxModelObject::shouldAntialiasLines(GraphicsContext* context)
2803 // FIXME: We may want to not antialias when scaled by an integral value,
2804 // and we may want to antialias when translated by a non-integral value.
2805 return !context->getCTM().isIdentityOrTranslationOrFlipped();
2808 void RenderBoxModelObject::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const
2810 RenderObject* o = container();
2814 o->mapAbsoluteToLocalPoint(mode, transformState);
2816 LayoutSize containerOffset = offsetFromContainer(o, LayoutPoint());
2818 if (!style()->hasOutOfFlowPosition() && o->hasColumns()) {
2819 RenderBlock* block = toRenderBlock(o);
2820 LayoutPoint point(roundedLayoutPoint(transformState.mappedPoint()));
2821 point -= containerOffset;
2822 block->adjustForColumnRect(containerOffset, point);
2825 bool preserve3D = mode & UseTransforms && (o->style()->preserves3D() || style()->preserves3D());
2826 if (mode & UseTransforms && shouldUseTransformFromContainer(o)) {
2827 TransformationMatrix t;
2828 getTransformFromContainer(o, containerOffset, t);
2829 transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
2831 transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform);
2834 void RenderBoxModelObject::moveChildTo(RenderBoxModelObject* toBoxModelObject, RenderObject* child, RenderObject* beforeChild, bool fullRemoveInsert)
2836 // We assume that callers have cleared their positioned objects list for child moves (!fullRemoveInsert) so the
2837 // positioned renderer maps don't become stale. It would be too slow to do the map lookup on each call.
2838 ASSERT(!fullRemoveInsert || !isRenderBlock() || !toRenderBlock(this)->hasPositionedObjects());
2840 ASSERT(this == child->parent());
2841 ASSERT(!beforeChild || toBoxModelObject == beforeChild->parent());
2842 if (fullRemoveInsert && (toBoxModelObject->isRenderBlock() || toBoxModelObject->isRenderInline())) {
2843 // Takes care of adding the new child correctly if toBlock and fromBlock
2844 // have different kind of children (block vs inline).
2845 toBoxModelObject->addChild(virtualChildren()->removeChildNode(this, child), beforeChild);
2847 toBoxModelObject->virtualChildren()->insertChildNode(toBoxModelObject, virtualChildren()->removeChildNode(this, child, fullRemoveInsert), beforeChild, fullRemoveInsert);
2850 void RenderBoxModelObject::moveChildrenTo(RenderBoxModelObject* toBoxModelObject, RenderObject* startChild, RenderObject* endChild, RenderObject* beforeChild, bool fullRemoveInsert)
2852 // This condition is rarely hit since this function is usually called on
2853 // anonymous blocks which can no longer carry positioned objects (see r120761)
2854 // or when fullRemoveInsert is false.
2855 if (fullRemoveInsert && isRenderBlock()) {
2856 RenderBlock* block = toRenderBlock(this);
2857 block->removePositionedObjects(0);
2858 block->removeFloatingObjects();
2861 ASSERT(!beforeChild || toBoxModelObject == beforeChild->parent());
2862 for (RenderObject* child = startChild; child && child != endChild; ) {
2863 // Save our next sibling as moveChildTo will clear it.
2864 RenderObject* nextSibling = child->nextSibling();
2865 moveChildTo(toBoxModelObject, child, beforeChild, fullRemoveInsert);
2866 child = nextSibling;
2870 } // namespace WebCore