1/* 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, 2013 Apple Inc. All rights reserved. 7 * Copyright (C) 2010 Google Inc. All rights reserved. 8 * 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. 13 * 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. 18 * 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. 23 * 24 */ 25 26#include "config.h" 27#include "RenderBoxModelObject.h" 28 29#include "BorderEdge.h" 30#include "FloatRoundedRect.h" 31#include "Frame.h" 32#include "FrameView.h" 33#include "GeometryUtilities.h" 34#include "GraphicsContext.h" 35#include "HTMLFrameOwnerElement.h" 36#include "HTMLNames.h" 37#include "ImageBuffer.h" 38#include "ImageQualityController.h" 39#include "Page.h" 40#include "Path.h" 41#include "RenderBlock.h" 42#include "RenderInline.h" 43#include "RenderLayer.h" 44#include "RenderLayerBacking.h" 45#include "RenderLayerCompositor.h" 46#include "RenderMultiColumnFlowThread.h" 47#include "RenderNamedFlowFragment.h" 48#include "RenderNamedFlowThread.h" 49#include "RenderRegion.h" 50#include "RenderTable.h" 51#include "RenderText.h" 52#include "RenderTextFragment.h" 53#include "RenderView.h" 54#include "ScrollingConstraints.h" 55#include "Settings.h" 56#include "TransformState.h" 57 58namespace WebCore { 59 60using namespace HTMLNames; 61 62// The HashMap for storing continuation pointers. 63// An inline can be split with blocks occuring in between the inline content. 64// When this occurs we need a pointer to the next object. We can basically be 65// split into a sequence of inlines and blocks. The continuation will either be 66// an anonymous block (that houses other blocks) or it will be an inline flow. 67// <b><i><p>Hello</p></i></b>. In this example the <i> will have a block as 68// its continuation but the <b> will just have an inline as its continuation. 69typedef HashMap<const RenderBoxModelObject*, RenderBoxModelObject*> ContinuationMap; 70static ContinuationMap* continuationMap = 0; 71 72// This HashMap is similar to the continuation map, but connects first-letter 73// renderers to their remaining text fragments. 74typedef HashMap<const RenderBoxModelObject*, RenderTextFragment*> FirstLetterRemainingTextMap; 75static FirstLetterRemainingTextMap* firstLetterRemainingTextMap = 0; 76 77void RenderBoxModelObject::setSelectionState(SelectionState state) 78{ 79 if (state == SelectionInside && selectionState() != SelectionNone) 80 return; 81 82 if ((state == SelectionStart && selectionState() == SelectionEnd) 83 || (state == SelectionEnd && selectionState() == SelectionStart)) 84 RenderLayerModelObject::setSelectionState(SelectionBoth); 85 else 86 RenderLayerModelObject::setSelectionState(state); 87 88 // FIXME: We should consider whether it is OK propagating to ancestor RenderInlines. 89 // This is a workaround for http://webkit.org/b/32123 90 // The containing block can be null in case of an orphaned tree. 91 RenderBlock* containingBlock = this->containingBlock(); 92 if (containingBlock && !containingBlock->isRenderView()) 93 containingBlock->setSelectionState(state); 94} 95 96void RenderBoxModelObject::contentChanged(ContentChangeType changeType) 97{ 98 if (!hasLayer()) 99 return; 100 101 layer()->contentChanged(changeType); 102} 103 104bool RenderBoxModelObject::hasAcceleratedCompositing() const 105{ 106 return view().compositor().hasAcceleratedCompositing(); 107} 108 109bool RenderBoxModelObject::startTransition(double timeOffset, CSSPropertyID propertyId, const RenderStyle* fromStyle, const RenderStyle* toStyle) 110{ 111 ASSERT(hasLayer()); 112 ASSERT(isComposited()); 113 return layer()->backing()->startTransition(timeOffset, propertyId, fromStyle, toStyle); 114} 115 116void RenderBoxModelObject::transitionPaused(double timeOffset, CSSPropertyID propertyId) 117{ 118 ASSERT(hasLayer()); 119 ASSERT(isComposited()); 120 layer()->backing()->transitionPaused(timeOffset, propertyId); 121} 122 123void RenderBoxModelObject::transitionFinished(CSSPropertyID propertyId) 124{ 125 ASSERT(hasLayer()); 126 ASSERT(isComposited()); 127 layer()->backing()->transitionFinished(propertyId); 128} 129 130bool RenderBoxModelObject::startAnimation(double timeOffset, const Animation* animation, const KeyframeList& keyframes) 131{ 132 ASSERT(hasLayer()); 133 ASSERT(isComposited()); 134 return layer()->backing()->startAnimation(timeOffset, animation, keyframes); 135} 136 137void RenderBoxModelObject::animationPaused(double timeOffset, const String& name) 138{ 139 ASSERT(hasLayer()); 140 ASSERT(isComposited()); 141 layer()->backing()->animationPaused(timeOffset, name); 142} 143 144void RenderBoxModelObject::animationFinished(const String& name) 145{ 146 ASSERT(hasLayer()); 147 ASSERT(isComposited()); 148 layer()->backing()->animationFinished(name); 149} 150 151void RenderBoxModelObject::suspendAnimations(double time) 152{ 153 ASSERT(hasLayer()); 154 ASSERT(isComposited()); 155 layer()->backing()->suspendAnimations(time); 156} 157 158bool RenderBoxModelObject::shouldPaintAtLowQuality(GraphicsContext* context, Image* image, const void* layer, const LayoutSize& size) 159{ 160 return view().imageQualityController().shouldPaintAtLowQuality(context, this, image, layer, size); 161} 162 163RenderBoxModelObject::RenderBoxModelObject(Element& element, PassRef<RenderStyle> style, unsigned baseTypeFlags) 164 : RenderLayerModelObject(element, WTF::move(style), baseTypeFlags | RenderBoxModelObjectFlag) 165{ 166} 167 168RenderBoxModelObject::RenderBoxModelObject(Document& document, PassRef<RenderStyle> style, unsigned baseTypeFlags) 169 : RenderLayerModelObject(document, WTF::move(style), baseTypeFlags | RenderBoxModelObjectFlag) 170{ 171} 172 173RenderBoxModelObject::~RenderBoxModelObject() 174{ 175} 176 177void RenderBoxModelObject::willBeDestroyed() 178{ 179 // A continuation of this RenderObject should be destroyed at subclasses. 180 ASSERT(!continuation()); 181 182 // If this is a first-letter object with a remaining text fragment then the 183 // entry needs to be cleared from the map. 184 if (firstLetterRemainingText()) 185 setFirstLetterRemainingText(0); 186 187 if (!documentBeingDestroyed()) 188 view().imageQualityController().rendererWillBeDestroyed(*this); 189 190 RenderLayerModelObject::willBeDestroyed(); 191} 192 193bool RenderBoxModelObject::hasBoxDecorationStyle() const 194{ 195 return hasBackground() || style().hasBorder() || style().hasAppearance() || style().boxShadow(); 196} 197 198void RenderBoxModelObject::updateFromStyle() 199{ 200 RenderLayerModelObject::updateFromStyle(); 201 202 // Set the appropriate bits for a box model object. Since all bits are cleared in styleWillChange, 203 // we only check for bits that could possibly be set to true. 204 const RenderStyle& styleToUse = style(); 205 setHasBoxDecorations(hasBoxDecorationStyle()); 206 setInline(styleToUse.isDisplayInlineType()); 207 setPositionState(styleToUse.position()); 208 setHorizontalWritingMode(styleToUse.isHorizontalWritingMode()); 209} 210 211static LayoutSize accumulateInFlowPositionOffsets(const RenderObject* child) 212{ 213 if (!child->isAnonymousBlock() || !child->isInFlowPositioned()) 214 return LayoutSize(); 215 LayoutSize offset; 216 RenderElement* p = toRenderBlock(child)->inlineElementContinuation(); 217 while (p && p->isRenderInline()) { 218 if (p->isInFlowPositioned()) { 219 RenderInline* renderInline = toRenderInline(p); 220 offset += renderInline->offsetForInFlowPosition(); 221 } 222 p = p->parent(); 223 } 224 return offset; 225} 226 227bool RenderBoxModelObject::hasAutoHeightOrContainingBlockWithAutoHeight() const 228{ 229 Length logicalHeightLength = style().logicalHeight(); 230 if (logicalHeightLength.isAuto()) 231 return true; 232 233 // For percentage heights: The percentage is calculated with respect to the height of the generated box's 234 // containing block. If the height of the containing block is not specified explicitly (i.e., it depends 235 // on content height), and this element is not absolutely positioned, the value computes to 'auto'. 236 if (!logicalHeightLength.isPercent() || isOutOfFlowPositioned() || document().inQuirksMode()) 237 return false; 238 239 // Anonymous block boxes are ignored when resolving percentage values that would refer to it: 240 // the closest non-anonymous ancestor box is used instead. 241 RenderBlock* cb = containingBlock(); 242 while (cb->isAnonymous() && !cb->isRenderView()) 243 cb = cb->containingBlock(); 244 245 // Matching RenderBox::percentageLogicalHeightIsResolvableFromBlock() by 246 // ignoring table cell's attribute value, where it says that table cells violate 247 // what the CSS spec says to do with heights. Basically we 248 // don't care if the cell specified a height or not. 249 if (cb->isTableCell()) 250 return false; 251 252 // Match RenderBox::availableLogicalHeightUsing by special casing 253 // the render view. The available height is taken from the frame. 254 if (cb->isRenderView()) 255 return false; 256 257 if (cb->isOutOfFlowPositioned() && !cb->style().logicalTop().isAuto() && !cb->style().logicalBottom().isAuto()) 258 return false; 259 260 // If the height of the containing block computes to 'auto', then it hasn't been 'specified explictly'. 261 return cb->hasAutoHeightOrContainingBlockWithAutoHeight(); 262} 263 264LayoutSize RenderBoxModelObject::relativePositionOffset() const 265{ 266 LayoutSize offset = accumulateInFlowPositionOffsets(this); 267 268 RenderBlock* containingBlock = this->containingBlock(); 269 270 // Objects that shrink to avoid floats normally use available line width when computing containing block width. However 271 // in the case of relative positioning using percentages, we can't do this. The offset should always be resolved using the 272 // available width of the containing block. Therefore we don't use containingBlockLogicalWidthForContent() here, but instead explicitly 273 // call availableWidth on our containing block. 274 if (!style().left().isAuto()) { 275 if (!style().right().isAuto() && !containingBlock->style().isLeftToRightDirection()) 276 offset.setWidth(-valueForLength(style().right(), containingBlock->availableWidth())); 277 else 278 offset.expand(valueForLength(style().left(), containingBlock->availableWidth()), 0); 279 } else if (!style().right().isAuto()) { 280 offset.expand(-valueForLength(style().right(), containingBlock->availableWidth()), 0); 281 } 282 283 // If the containing block of a relatively positioned element does not 284 // specify a height, a percentage top or bottom offset should be resolved as 285 // auto. An exception to this is if the containing block has the WinIE quirk 286 // where <html> and <body> assume the size of the viewport. In this case, 287 // calculate the percent offset based on this height. 288 // See <https://bugs.webkit.org/show_bug.cgi?id=26396>. 289 if (!style().top().isAuto() 290 && (!containingBlock->hasAutoHeightOrContainingBlockWithAutoHeight() 291 || !style().top().isPercent() 292 || containingBlock->stretchesToViewport())) 293 offset.expand(0, valueForLength(style().top(), containingBlock->availableHeight())); 294 295 else if (!style().bottom().isAuto() 296 && (!containingBlock->hasAutoHeightOrContainingBlockWithAutoHeight() 297 || !style().bottom().isPercent() 298 || containingBlock->stretchesToViewport())) 299 offset.expand(0, -valueForLength(style().bottom(), containingBlock->availableHeight())); 300 301 return offset; 302} 303 304LayoutPoint RenderBoxModelObject::adjustedPositionRelativeToOffsetParent(const LayoutPoint& startPoint) const 305{ 306 // If the element is the HTML body element or doesn't have a parent 307 // return 0 and stop this algorithm. 308 if (isBody() || !parent()) 309 return LayoutPoint(); 310 311 LayoutPoint referencePoint = startPoint; 312 313 // If the offsetParent of the element is null, or is the HTML body element, 314 // return the distance between the canvas origin and the left border edge 315 // of the element and stop this algorithm. 316 if (const RenderBoxModelObject* offsetParent = this->offsetParent()) { 317 if (offsetParent->isBox() && !offsetParent->isBody() && !offsetParent->isTable()) 318 referencePoint.move(-toRenderBox(offsetParent)->borderLeft(), -toRenderBox(offsetParent)->borderTop()); 319 if (!isOutOfFlowPositioned() || flowThreadContainingBlock()) { 320 if (isRelPositioned()) 321 referencePoint.move(relativePositionOffset()); 322 else if (isStickyPositioned()) 323 referencePoint.move(stickyPositionOffset()); 324 325 // CSS regions specification says that region flows should return the body element as their offsetParent. 326 // Since we will bypass the body’s renderer anyway, just end the loop if we encounter a region flow (named flow thread). 327 // See http://dev.w3.org/csswg/css-regions/#cssomview-offset-attributes 328 auto curr = parent(); 329 while (curr != offsetParent && !curr->isRenderNamedFlowThread()) { 330 // FIXME: What are we supposed to do inside SVG content? 331 332 if (curr->isInFlowRenderFlowThread()) { 333 // We need to apply a translation based off what region we are inside. 334 RenderRegion* region = toRenderMultiColumnFlowThread(curr)->physicalTranslationFromFlowToRegion(referencePoint); 335 if (region) 336 referencePoint.moveBy(region->topLeftLocation()); 337 } else if (!isOutOfFlowPositioned()) { 338 if (curr->isBox() && !curr->isTableRow()) 339 referencePoint.moveBy(toRenderBox(curr)->topLeftLocation()); 340 } 341 342 curr = curr->parent(); 343 } 344 345 // Compute the offset position for elements inside named flow threads for which the offsetParent was the body. 346 // See https://bugs.webkit.org/show_bug.cgi?id=115899 347 if (curr->isRenderNamedFlowThread()) 348 referencePoint = toRenderNamedFlowThread(curr)->adjustedPositionRelativeToOffsetParent(*this, referencePoint); 349 else if (offsetParent->isBox() && offsetParent->isBody() && !offsetParent->isPositioned()) 350 referencePoint.moveBy(toRenderBox(offsetParent)->topLeftLocation()); 351 } 352 } 353 354 return referencePoint; 355} 356 357void RenderBoxModelObject::computeStickyPositionConstraints(StickyPositionViewportConstraints& constraints, const FloatRect& constrainingRect) const 358{ 359 constraints.setConstrainingRectAtLastLayout(constrainingRect); 360 361 RenderBlock* containingBlock = this->containingBlock(); 362 RenderLayer* enclosingClippingLayer = layer()->enclosingOverflowClipLayer(ExcludeSelf); 363 RenderBox& enclosingClippingBox = enclosingClippingLayer ? toRenderBox(enclosingClippingLayer->renderer()) : view(); 364 365 LayoutRect containerContentRect; 366 if (!enclosingClippingLayer || (containingBlock != &enclosingClippingBox)) 367 containerContentRect = containingBlock->contentBoxRect(); 368 else { 369 containerContentRect = containingBlock->layoutOverflowRect(); 370 LayoutPoint containerLocation = containerContentRect.location() + LayoutPoint(containingBlock->borderLeft() + containingBlock->paddingLeft(), 371 containingBlock->borderTop() + containingBlock->paddingTop()); 372 containerContentRect.setLocation(containerLocation); 373 } 374 375 LayoutUnit maxWidth = containingBlock->availableLogicalWidth(); 376 377 // Sticky positioned element ignore any override logical width on the containing block (as they don't call 378 // containingBlockLogicalWidthForContent). It's unclear whether this is totally fine. 379 LayoutBoxExtent minMargin(minimumValueForLength(style().marginTop(), maxWidth), 380 minimumValueForLength(style().marginRight(), maxWidth), 381 minimumValueForLength(style().marginBottom(), maxWidth), 382 minimumValueForLength(style().marginLeft(), maxWidth)); 383 384 // Compute the container-relative area within which the sticky element is allowed to move. 385 containerContentRect.contract(minMargin); 386 387 // Finally compute container rect relative to the scrolling ancestor. 388 FloatRect containerRectRelativeToScrollingAncestor = containingBlock->localToContainerQuad(FloatRect(containerContentRect), &enclosingClippingBox).boundingBox(); 389 if (enclosingClippingLayer) { 390 FloatPoint containerLocationRelativeToScrollingAncestor = containerRectRelativeToScrollingAncestor.location() - 391 FloatSize(enclosingClippingBox.borderLeft() + enclosingClippingBox.paddingLeft(), 392 enclosingClippingBox.borderTop() + enclosingClippingBox.paddingTop()); 393 if (&enclosingClippingBox != containingBlock) 394 containerLocationRelativeToScrollingAncestor += enclosingClippingLayer->scrollOffset(); 395 containerRectRelativeToScrollingAncestor.setLocation(containerLocationRelativeToScrollingAncestor); 396 } 397 constraints.setContainingBlockRect(containerRectRelativeToScrollingAncestor); 398 399 // Now compute the sticky box rect, also relative to the scrolling ancestor. 400 LayoutRect stickyBoxRect = frameRectForStickyPositioning(); 401 LayoutRect flippedStickyBoxRect = stickyBoxRect; 402 containingBlock->flipForWritingMode(flippedStickyBoxRect); 403 FloatRect stickyBoxRelativeToScrollingAnecstor = flippedStickyBoxRect; 404 405 // FIXME: sucks to call localToContainerQuad again, but we can't just offset from the previously computed rect if there are transforms. 406 // Map to the view to avoid including page scale factor. 407 FloatPoint stickyLocationRelativeToScrollingAncestor = flippedStickyBoxRect.location() + containingBlock->localToContainerQuad(FloatRect(FloatPoint(), containingBlock->size()), &enclosingClippingBox).boundingBox().location(); 408 if (enclosingClippingLayer) { 409 stickyLocationRelativeToScrollingAncestor -= FloatSize(enclosingClippingBox.borderLeft() + enclosingClippingBox.paddingLeft(), 410 enclosingClippingBox.borderTop() + enclosingClippingBox.paddingTop()); 411 if (&enclosingClippingBox != containingBlock) 412 stickyLocationRelativeToScrollingAncestor += enclosingClippingLayer->scrollOffset(); 413 } 414 // FIXME: For now, assume that |this| is not transformed. 415 stickyBoxRelativeToScrollingAnecstor.setLocation(stickyLocationRelativeToScrollingAncestor); 416 constraints.setStickyBoxRect(stickyBoxRelativeToScrollingAnecstor); 417 418 if (!style().left().isAuto()) { 419 constraints.setLeftOffset(valueForLength(style().left(), constrainingRect.width())); 420 constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeLeft); 421 } 422 423 if (!style().right().isAuto()) { 424 constraints.setRightOffset(valueForLength(style().right(), constrainingRect.width())); 425 constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeRight); 426 } 427 428 if (!style().top().isAuto()) { 429 constraints.setTopOffset(valueForLength(style().top(), constrainingRect.height())); 430 constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeTop); 431 } 432 433 if (!style().bottom().isAuto()) { 434 constraints.setBottomOffset(valueForLength(style().bottom(), constrainingRect.height())); 435 constraints.addAnchorEdge(ViewportConstraints::AnchorEdgeBottom); 436 } 437} 438 439FloatRect RenderBoxModelObject::constrainingRectForStickyPosition() const 440{ 441 RenderLayer* enclosingClippingLayer = layer()->enclosingOverflowClipLayer(ExcludeSelf); 442 if (enclosingClippingLayer) { 443 RenderBox& enclosingClippingBox = toRenderBox(enclosingClippingLayer->renderer()); 444 LayoutRect clipRect = enclosingClippingBox.overflowClipRect(LayoutPoint(), 0); // FIXME: make this work in regions. 445 clipRect.contract(LayoutSize(enclosingClippingBox.paddingLeft() + enclosingClippingBox.paddingRight(), 446 enclosingClippingBox.paddingTop() + enclosingClippingBox.paddingBottom())); 447 448 FloatRect constrainingRect = enclosingClippingBox.localToContainerQuad(FloatRect(clipRect), &view()).boundingBox(); 449 450 FloatPoint scrollOffset = FloatPoint() + enclosingClippingLayer->scrollOffset(); 451 constrainingRect.setLocation(scrollOffset); 452 return constrainingRect; 453 } 454 455 return view().frameView().viewportConstrainedVisibleContentRect(); 456} 457 458LayoutSize RenderBoxModelObject::stickyPositionOffset() const 459{ 460 ASSERT(hasLayer()); 461 462 FloatRect constrainingRect = constrainingRectForStickyPosition(); 463 StickyPositionViewportConstraints constraints; 464 computeStickyPositionConstraints(constraints, constrainingRect); 465 466 // The sticky offset is physical, so we can just return the delta computed in absolute coords (though it may be wrong with transforms). 467 return LayoutSize(constraints.computeStickyOffset(constrainingRect)); 468} 469 470LayoutSize RenderBoxModelObject::offsetForInFlowPosition() const 471{ 472 if (isRelPositioned()) 473 return relativePositionOffset(); 474 475 if (isStickyPositioned()) 476 return stickyPositionOffset(); 477 478 return LayoutSize(); 479} 480 481LayoutUnit RenderBoxModelObject::offsetLeft() const 482{ 483 // Note that RenderInline and RenderBox override this to pass a different 484 // startPoint to adjustedPositionRelativeToOffsetParent. 485 return adjustedPositionRelativeToOffsetParent(LayoutPoint()).x(); 486} 487 488LayoutUnit RenderBoxModelObject::offsetTop() const 489{ 490 // Note that RenderInline and RenderBox override this to pass a different 491 // startPoint to adjustedPositionRelativeToOffsetParent. 492 return adjustedPositionRelativeToOffsetParent(LayoutPoint()).y(); 493} 494 495int RenderBoxModelObject::pixelSnappedOffsetWidth() const 496{ 497 return snapSizeToPixel(offsetWidth(), offsetLeft()); 498} 499 500int RenderBoxModelObject::pixelSnappedOffsetHeight() const 501{ 502 return snapSizeToPixel(offsetHeight(), offsetTop()); 503} 504 505LayoutUnit RenderBoxModelObject::computedCSSPadding(const Length& padding) const 506{ 507 LayoutUnit w = 0; 508 if (padding.isPercent()) 509 w = containingBlockLogicalWidthForContent(); 510 return minimumValueForLength(padding, w); 511} 512 513RoundedRect RenderBoxModelObject::getBackgroundRoundedRect(const LayoutRect& borderRect, InlineFlowBox* box, LayoutUnit inlineBoxWidth, LayoutUnit inlineBoxHeight, 514 bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const 515{ 516 RoundedRect border = style().getRoundedBorderFor(borderRect, includeLogicalLeftEdge, includeLogicalRightEdge); 517 if (box && (box->nextLineBox() || box->prevLineBox())) { 518 RoundedRect segmentBorder = style().getRoundedBorderFor(LayoutRect(0, 0, inlineBoxWidth, inlineBoxHeight), includeLogicalLeftEdge, includeLogicalRightEdge); 519 border.setRadii(segmentBorder.radii()); 520 } 521 return border; 522} 523 524void RenderBoxModelObject::clipRoundedInnerRect(GraphicsContext * context, const FloatRect& rect, const FloatRoundedRect& clipRect) 525{ 526 if (clipRect.isRenderable()) 527 context->clipRoundedRect(clipRect); 528 else { 529 // We create a rounded rect for each of the corners and clip it, while making sure we clip opposing corners together. 530 if (!clipRect.radii().topLeft().isEmpty() || !clipRect.radii().bottomRight().isEmpty()) { 531 FloatRect topCorner(clipRect.rect().x(), clipRect.rect().y(), rect.maxX() - clipRect.rect().x(), rect.maxY() - clipRect.rect().y()); 532 FloatRoundedRect::Radii topCornerRadii; 533 topCornerRadii.setTopLeft(clipRect.radii().topLeft()); 534 context->clipRoundedRect(FloatRoundedRect(topCorner, topCornerRadii)); 535 536 FloatRect bottomCorner(rect.x(), rect.y(), clipRect.rect().maxX() - rect.x(), clipRect.rect().maxY() - rect.y()); 537 FloatRoundedRect::Radii bottomCornerRadii; 538 bottomCornerRadii.setBottomRight(clipRect.radii().bottomRight()); 539 context->clipRoundedRect(FloatRoundedRect(bottomCorner, bottomCornerRadii)); 540 } 541 542 if (!clipRect.radii().topRight().isEmpty() || !clipRect.radii().bottomLeft().isEmpty()) { 543 FloatRect topCorner(rect.x(), clipRect.rect().y(), clipRect.rect().maxX() - rect.x(), rect.maxY() - clipRect.rect().y()); 544 FloatRoundedRect::Radii topCornerRadii; 545 topCornerRadii.setTopRight(clipRect.radii().topRight()); 546 context->clipRoundedRect(FloatRoundedRect(topCorner, topCornerRadii)); 547 548 FloatRect bottomCorner(clipRect.rect().x(), rect.y(), rect.maxX() - clipRect.rect().x(), clipRect.rect().maxY() - rect.y()); 549 FloatRoundedRect::Radii bottomCornerRadii; 550 bottomCornerRadii.setBottomLeft(clipRect.radii().bottomLeft()); 551 context->clipRoundedRect(FloatRoundedRect(bottomCorner, bottomCornerRadii)); 552 } 553 } 554} 555 556static LayoutRect shrinkRectByOneDevicePixel(const GraphicsContext& context, const LayoutRect& rect, float devicePixelRatio) 557{ 558 LayoutRect shrunkRect = rect; 559 AffineTransform transform = context.getCTM(); 560 shrunkRect.inflateX(-ceilToDevicePixel(LayoutUnit::fromPixel(1) / transform.xScale(), devicePixelRatio)); 561 shrunkRect.inflateY(-ceilToDevicePixel(LayoutUnit::fromPixel(1) / transform.yScale(), devicePixelRatio)); 562 return shrunkRect; 563} 564 565LayoutRect RenderBoxModelObject::borderInnerRectAdjustedForBleedAvoidance(const GraphicsContext& context, const LayoutRect& rect, BackgroundBleedAvoidance bleedAvoidance) const 566{ 567 if (bleedAvoidance != BackgroundBleedBackgroundOverBorder) 568 return rect; 569 570 // We shrink the rectangle by one device pixel on each side to make it fully overlap the anti-aliased background border 571 return shrinkRectByOneDevicePixel(context, rect, document().deviceScaleFactor()); 572} 573 574RoundedRect RenderBoxModelObject::backgroundRoundedRectAdjustedForBleedAvoidance(const GraphicsContext& context, const LayoutRect& borderRect, BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* box, const LayoutSize& boxSize, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const 575{ 576 if (bleedAvoidance == BackgroundBleedShrinkBackground) { 577 // We shrink the rectangle by one device pixel on each side because the bleed is one pixel maximum. 578 return getBackgroundRoundedRect(shrinkRectByOneDevicePixel(context, borderRect, document().deviceScaleFactor()), box, boxSize.width(), boxSize.height(), 579 includeLogicalLeftEdge, includeLogicalRightEdge); 580 } 581 if (bleedAvoidance == BackgroundBleedBackgroundOverBorder) 582 return style().getRoundedInnerBorderFor(borderRect, includeLogicalLeftEdge, includeLogicalRightEdge); 583 584 return getBackgroundRoundedRect(borderRect, box, boxSize.width(), boxSize.height(), includeLogicalLeftEdge, includeLogicalRightEdge); 585} 586 587static void applyBoxShadowForBackground(GraphicsContext* context, RenderStyle* style) 588{ 589 const ShadowData* boxShadow = style->boxShadow(); 590 while (boxShadow->style() != Normal) 591 boxShadow = boxShadow->next(); 592 593 FloatSize shadowOffset(boxShadow->x(), boxShadow->y()); 594 if (!boxShadow->isWebkitBoxShadow()) 595 context->setShadow(shadowOffset, boxShadow->radius(), boxShadow->color(), style->colorSpace()); 596 else 597 context->setLegacyShadow(shadowOffset, boxShadow->radius(), boxShadow->color(), style->colorSpace()); 598} 599 600void RenderBoxModelObject::paintMaskForTextFillBox(ImageBuffer* maskImage, const IntRect& maskRect, InlineFlowBox* box, const LayoutRect& scrolledPaintRect) 601{ 602 GraphicsContext* maskImageContext = maskImage->context(); 603 maskImageContext->translate(-maskRect.x(), -maskRect.y()); 604 605 // Now add the text to the clip. We do this by painting using a special paint phase that signals to 606 // InlineTextBoxes that they should just add their contents to the clip. 607 PaintInfo info(maskImageContext, maskRect, PaintPhaseTextClip, PaintBehaviorForceBlackText, 0); 608 if (box) { 609 const RootInlineBox& rootBox = box->root(); 610 box->paint(info, LayoutPoint(scrolledPaintRect.x() - box->x(), scrolledPaintRect.y() - box->y()), rootBox.lineTop(), rootBox.lineBottom()); 611 } else if (isRenderNamedFlowFragmentContainer()) { 612 RenderNamedFlowFragment* region = toRenderBlockFlow(this)->renderNamedFlowFragment(); 613 if (region->isValid()) 614 region->flowThread()->layer()->paintNamedFlowThreadInsideRegion(maskImageContext, region, maskRect, maskRect.location(), PaintBehaviorForceBlackText, RenderLayer::PaintLayerTemporaryClipRects); 615 } else { 616 LayoutSize localOffset = isBox() ? toRenderBox(this)->locationOffset() : LayoutSize(); 617 paint(info, scrolledPaintRect.location() - localOffset); 618 } 619} 620 621void RenderBoxModelObject::paintFillLayerExtended(const PaintInfo& paintInfo, const Color& color, const FillLayer* bgLayer, const LayoutRect& rect, 622 BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* box, const LayoutSize& boxSize, CompositeOperator op, RenderElement* backgroundObject, BaseBackgroundColorUsage baseBgColorUsage) 623{ 624 GraphicsContext* context = paintInfo.context; 625 if (context->paintingDisabled() || rect.isEmpty()) 626 return; 627 628 bool includeLeftEdge = box ? box->includeLogicalLeftEdge() : true; 629 bool includeRightEdge = box ? box->includeLogicalRightEdge() : true; 630 631 bool hasRoundedBorder = style().hasBorderRadius() && (includeLeftEdge || includeRightEdge); 632 bool clippedWithLocalScrolling = hasOverflowClip() && bgLayer->attachment() == LocalBackgroundAttachment; 633 bool isBorderFill = bgLayer->clip() == BorderFillBox; 634 bool isRoot = this->isRoot(); 635 636 Color bgColor = color; 637 StyleImage* bgImage = bgLayer->image(); 638 bool shouldPaintBackgroundImage = bgImage && bgImage->canRender(this, style().effectiveZoom()); 639 640 bool forceBackgroundToWhite = false; 641 if (document().printing()) { 642 if (style().printColorAdjust() == PrintColorAdjustEconomy) 643 forceBackgroundToWhite = true; 644 if (frame().settings().shouldPrintBackgrounds()) 645 forceBackgroundToWhite = false; 646 } 647 648 // When printing backgrounds is disabled or using economy mode, 649 // change existing background colors and images to a solid white background. 650 // If there's no bg color or image, leave it untouched to avoid affecting transparency. 651 // We don't try to avoid loading the background images, because this style flag is only set 652 // when printing, and at that point we've already loaded the background images anyway. (To avoid 653 // loading the background images we'd have to do this check when applying styles rather than 654 // while rendering.) 655 if (forceBackgroundToWhite) { 656 // Note that we can't reuse this variable below because the bgColor might be changed 657 bool shouldPaintBackgroundColor = !bgLayer->next() && bgColor.isValid() && bgColor.alpha(); 658 if (shouldPaintBackgroundImage || shouldPaintBackgroundColor) { 659 bgColor = Color::white; 660 shouldPaintBackgroundImage = false; 661 } 662 } 663 664 bool baseBgColorOnly = (baseBgColorUsage == BaseBackgroundColorOnly); 665 if (baseBgColorOnly && (!isRoot || bgLayer->next() || (bgColor.isValid() && !bgColor.hasAlpha()))) 666 return; 667 668 bool colorVisible = bgColor.isValid() && bgColor.alpha(); 669 float deviceScaleFactor = document().deviceScaleFactor(); 670 FloatRect pixelSnappedRect = pixelSnappedForPainting(rect, deviceScaleFactor); 671 672 // Fast path for drawing simple color backgrounds. 673 if (!isRoot && !clippedWithLocalScrolling && !shouldPaintBackgroundImage && isBorderFill && !bgLayer->next()) { 674 if (!colorVisible) 675 return; 676 677 bool boxShadowShouldBeAppliedToBackground = this->boxShadowShouldBeAppliedToBackground(bleedAvoidance, box); 678 GraphicsContextStateSaver shadowStateSaver(*context, boxShadowShouldBeAppliedToBackground); 679 if (boxShadowShouldBeAppliedToBackground) 680 applyBoxShadowForBackground(context, &style()); 681 682 if (hasRoundedBorder && bleedAvoidance != BackgroundBleedUseTransparencyLayer) { 683 FloatRoundedRect pixelSnappedBorder = backgroundRoundedRectAdjustedForBleedAvoidance(*context, rect, bleedAvoidance, box, boxSize, 684 includeLeftEdge, includeRightEdge).pixelSnappedRoundedRectForPainting(deviceScaleFactor); 685 if (pixelSnappedBorder.isRenderable()) 686 context->fillRoundedRect(pixelSnappedBorder, bgColor, style().colorSpace()); 687 else { 688 context->save(); 689 clipRoundedInnerRect(context, pixelSnappedRect, pixelSnappedBorder); 690 context->fillRect(pixelSnappedBorder.rect(), bgColor, style().colorSpace()); 691 context->restore(); 692 } 693 } else 694 context->fillRect(pixelSnappedRect, bgColor, style().colorSpace()); 695 696 return; 697 } 698 699 // BorderFillBox radius clipping is taken care of by BackgroundBleedUseTransparencyLayer 700 bool clipToBorderRadius = hasRoundedBorder && !(isBorderFill && bleedAvoidance == BackgroundBleedUseTransparencyLayer); 701 GraphicsContextStateSaver clipToBorderStateSaver(*context, clipToBorderRadius); 702 if (clipToBorderRadius) { 703 RoundedRect border = isBorderFill ? backgroundRoundedRectAdjustedForBleedAvoidance(*context, rect, bleedAvoidance, box, boxSize, includeLeftEdge, includeRightEdge) : getBackgroundRoundedRect(rect, box, boxSize.width(), boxSize.height(), includeLeftEdge, includeRightEdge); 704 705 // Clip to the padding or content boxes as necessary. 706 if (bgLayer->clip() == ContentFillBox) { 707 border = style().getRoundedInnerBorderFor(border.rect(), 708 paddingTop() + borderTop(), paddingBottom() + borderBottom(), paddingLeft() + borderLeft(), paddingRight() + borderRight(), includeLeftEdge, includeRightEdge); 709 } else if (bgLayer->clip() == PaddingFillBox) 710 border = style().getRoundedInnerBorderFor(border.rect(), includeLeftEdge, includeRightEdge); 711 712 clipRoundedInnerRect(context, pixelSnappedRect, border.pixelSnappedRoundedRectForPainting(deviceScaleFactor)); 713 } 714 715 LayoutUnit bLeft = includeLeftEdge ? borderLeft() : LayoutUnit::fromPixel(0); 716 LayoutUnit bRight = includeRightEdge ? borderRight() : LayoutUnit::fromPixel(0); 717 LayoutUnit pLeft = includeLeftEdge ? paddingLeft() : LayoutUnit(); 718 LayoutUnit pRight = includeRightEdge ? paddingRight() : LayoutUnit(); 719 720 GraphicsContextStateSaver clipWithScrollingStateSaver(*context, clippedWithLocalScrolling); 721 LayoutRect scrolledPaintRect = rect; 722 if (clippedWithLocalScrolling) { 723 // Clip to the overflow area. 724 RenderBox* thisBox = toRenderBox(this); 725 context->clip(thisBox->overflowClipRect(rect.location(), currentRenderNamedFlowFragment())); 726 727 // Adjust the paint rect to reflect a scrolled content box with borders at the ends. 728 IntSize offset = thisBox->scrolledContentOffset(); 729 scrolledPaintRect.move(-offset); 730 scrolledPaintRect.setWidth(bLeft + layer()->scrollWidth() + bRight); 731 scrolledPaintRect.setHeight(borderTop() + layer()->scrollHeight() + borderBottom()); 732 } 733 734 GraphicsContextStateSaver backgroundClipStateSaver(*context, false); 735 std::unique_ptr<ImageBuffer> maskImage; 736 IntRect maskRect; 737 738 if (bgLayer->clip() == PaddingFillBox || bgLayer->clip() == ContentFillBox) { 739 // Clip to the padding or content boxes as necessary. 740 if (!clipToBorderRadius) { 741 bool includePadding = bgLayer->clip() == ContentFillBox; 742 LayoutRect clipRect = LayoutRect(scrolledPaintRect.x() + bLeft + (includePadding ? pLeft : LayoutUnit()), 743 scrolledPaintRect.y() + borderTop() + (includePadding ? paddingTop() : LayoutUnit()), 744 scrolledPaintRect.width() - bLeft - bRight - (includePadding ? pLeft + pRight : LayoutUnit()), 745 scrolledPaintRect.height() - borderTop() - borderBottom() - (includePadding ? paddingTop() + paddingBottom() : LayoutUnit())); 746 backgroundClipStateSaver.save(); 747 context->clip(clipRect); 748 } 749 } else if (bgLayer->clip() == TextFillBox) { 750 // We have to draw our text into a mask that can then be used to clip background drawing. 751 // First figure out how big the mask has to be. It should be no bigger than what we need 752 // to actually render, so we should intersect the dirty rect with the border box of the background. 753 maskRect = pixelSnappedIntRect(rect); 754 maskRect.intersect(pixelSnappedIntRect(paintInfo.rect)); 755 756 // Now create the mask. 757 maskImage = context->createCompatibleBuffer(maskRect.size()); 758 if (!maskImage) 759 return; 760 paintMaskForTextFillBox(maskImage.get(), maskRect, box, scrolledPaintRect); 761 762 // The mask has been created. Now we just need to clip to it. 763 backgroundClipStateSaver.save(); 764 context->clip(maskRect); 765 context->beginTransparencyLayer(1); 766 } 767 768 // Only fill with a base color (e.g., white) if we're the root document, since iframes/frames with 769 // no background in the child document should show the parent's background. 770 bool isOpaqueRoot = false; 771 if (isRoot) { 772 isOpaqueRoot = true; 773 if (!bgLayer->next() && !(bgColor.isValid() && bgColor.alpha() == 255)) { 774 Element* ownerElement = document().ownerElement(); 775 if (ownerElement) { 776 if (!ownerElement->hasTagName(frameTag)) { 777 // Locate the <body> element using the DOM. This is easier than trying 778 // to crawl around a render tree with potential :before/:after content and 779 // anonymous blocks created by inline <body> tags etc. We can locate the <body> 780 // render object very easily via the DOM. 781 HTMLElement* body = document().body(); 782 if (body) { 783 // Can't scroll a frameset document anyway. 784 isOpaqueRoot = body->hasTagName(framesetTag); 785 } else { 786 // SVG documents and XML documents with SVG root nodes are transparent. 787 isOpaqueRoot = !document().hasSVGRootNode(); 788 } 789 } 790 } else 791 isOpaqueRoot = !view().frameView().isTransparent(); 792 } 793 view().frameView().setContentIsOpaque(isOpaqueRoot); 794 } 795 796 // Paint the color first underneath all images, culled if background image occludes it. 797 // FIXME: In the bgLayer->hasFiniteBounds() case, we could improve the culling test 798 // by verifying whether the background image covers the entire layout rect. 799 if (!bgLayer->next()) { 800 LayoutRect backgroundRect(scrolledPaintRect); 801 bool boxShadowShouldBeAppliedToBackground = this->boxShadowShouldBeAppliedToBackground(bleedAvoidance, box); 802 if (boxShadowShouldBeAppliedToBackground || !shouldPaintBackgroundImage || !bgLayer->hasOpaqueImage(*this) || !bgLayer->hasRepeatXY()) { 803 if (!boxShadowShouldBeAppliedToBackground) 804 backgroundRect.intersect(paintInfo.rect); 805 806 // If we have an alpha and we are painting the root element, go ahead and blend with the base background color. 807 Color baseColor; 808 bool shouldClearBackground = false; 809 if ((baseBgColorUsage != BaseBackgroundColorSkip) && isOpaqueRoot) { 810 baseColor = view().frameView().baseBackgroundColor(); 811 if (!baseColor.alpha()) 812 shouldClearBackground = true; 813 } 814 815 GraphicsContextStateSaver shadowStateSaver(*context, boxShadowShouldBeAppliedToBackground); 816 if (boxShadowShouldBeAppliedToBackground) 817 applyBoxShadowForBackground(context, &style()); 818 819 FloatRect backgroundRectForPainting = pixelSnappedForPainting(backgroundRect, deviceScaleFactor); 820 if (baseColor.alpha()) { 821 if (!baseBgColorOnly && bgColor.alpha()) 822 baseColor = baseColor.blend(bgColor); 823 824 context->fillRect(backgroundRectForPainting, baseColor, style().colorSpace(), CompositeCopy); 825 } else if (!baseBgColorOnly && bgColor.alpha()) { 826 CompositeOperator operation = shouldClearBackground ? CompositeCopy : context->compositeOperation(); 827 context->fillRect(backgroundRectForPainting, bgColor, style().colorSpace(), operation); 828 } else if (shouldClearBackground) 829 context->clearRect(backgroundRectForPainting); 830 } 831 } 832 833 // no progressive loading of the background image 834 if (!baseBgColorOnly && shouldPaintBackgroundImage) { 835 BackgroundImageGeometry geometry; 836 calculateBackgroundImageGeometry(paintInfo.paintContainer, bgLayer, scrolledPaintRect, geometry, backgroundObject); 837 geometry.clip(LayoutRect(pixelSnappedRect)); 838 if (!geometry.destRect().isEmpty()) { 839 CompositeOperator compositeOp = op == CompositeSourceOver ? bgLayer->composite() : op; 840 auto clientForBackgroundImage = backgroundObject ? backgroundObject : this; 841 RefPtr<Image> image = bgImage->image(clientForBackgroundImage, geometry.tileSize()); 842 context->setDrawLuminanceMask(bgLayer->maskSourceType() == MaskLuminance); 843 bool useLowQualityScaling = shouldPaintAtLowQuality(context, image.get(), bgLayer, geometry.tileSize()); 844 if (image.get()) 845 image->setSpaceSize(geometry.spaceSize()); 846 context->drawTiledImage(image.get(), style().colorSpace(), geometry.destRect(), geometry.relativePhase(), geometry.tileSize(), ImagePaintingOptions(compositeOp, bgLayer->blendMode(), ImageOrientationDescription(), useLowQualityScaling)); 847 } 848 } 849 850 if (bgLayer->clip() == TextFillBox) { 851 context->drawImageBuffer(maskImage.get(), ColorSpaceDeviceRGB, maskRect, CompositeDestinationIn); 852 context->endTransparencyLayer(); 853 } 854} 855 856static inline int resolveWidthForRatio(LayoutUnit height, const FloatSize& intrinsicRatio) 857{ 858 return height * intrinsicRatio.width() / intrinsicRatio.height(); 859} 860 861static inline int resolveHeightForRatio(LayoutUnit width, const FloatSize& intrinsicRatio) 862{ 863 return width * intrinsicRatio.height() / intrinsicRatio.width(); 864} 865 866static inline LayoutSize resolveAgainstIntrinsicWidthOrHeightAndRatio(const LayoutSize& size, const FloatSize& intrinsicRatio, LayoutUnit useWidth, LayoutUnit useHeight) 867{ 868 if (intrinsicRatio.isEmpty()) { 869 if (useWidth) 870 return LayoutSize(useWidth, size.height()); 871 return LayoutSize(size.width(), useHeight); 872 } 873 874 if (useWidth) 875 return LayoutSize(useWidth, resolveHeightForRatio(useWidth, intrinsicRatio)); 876 return LayoutSize(resolveWidthForRatio(useHeight, intrinsicRatio), useHeight); 877} 878 879static inline LayoutSize resolveAgainstIntrinsicRatio(const LayoutSize& size, const FloatSize& intrinsicRatio) 880{ 881 // Two possible solutions: (size.width(), solutionHeight) or (solutionWidth, size.height()) 882 // "... must be assumed to be the largest dimensions..." = easiest answer: the rect with the largest surface area. 883 884 LayoutUnit solutionWidth = resolveWidthForRatio(size.height(), intrinsicRatio); 885 LayoutUnit solutionHeight = resolveHeightForRatio(size.width(), intrinsicRatio); 886 if (solutionWidth <= size.width()) { 887 if (solutionHeight <= size.height()) { 888 // If both solutions fit, choose the one covering the larger area. 889 LayoutUnit areaOne = solutionWidth * size.height(); 890 LayoutUnit areaTwo = size.width() * solutionHeight; 891 if (areaOne < areaTwo) 892 return LayoutSize(size.width(), solutionHeight); 893 return LayoutSize(solutionWidth, size.height()); 894 } 895 896 // Only the first solution fits. 897 return LayoutSize(solutionWidth, size.height()); 898 } 899 900 // Only the second solution fits, assert that. 901 ASSERT(solutionHeight <= size.height()); 902 return LayoutSize(size.width(), solutionHeight); 903} 904 905LayoutSize RenderBoxModelObject::calculateImageIntrinsicDimensions(StyleImage* image, const LayoutSize& positioningAreaSize, ScaleByEffectiveZoomOrNot shouldScaleOrNot) const 906{ 907 // A generated image without a fixed size, will always return the container size as intrinsic size. 908 if (image->isGeneratedImage() && image->usesImageContainerSize()) 909 return LayoutSize(positioningAreaSize.width(), positioningAreaSize.height()); 910 911 Length intrinsicWidth; 912 Length intrinsicHeight; 913 FloatSize intrinsicRatio; 914 image->computeIntrinsicDimensions(this, intrinsicWidth, intrinsicHeight, intrinsicRatio); 915 916 ASSERT(!intrinsicWidth.isPercent()); 917 ASSERT(!intrinsicHeight.isPercent()); 918 919 LayoutSize resolvedSize(intrinsicWidth.value(), intrinsicHeight.value()); 920 LayoutSize minimumSize(resolvedSize.width() > 0 ? 1 : 0, resolvedSize.height() > 0 ? 1 : 0); 921 if (shouldScaleOrNot == ScaleByEffectiveZoom) 922 resolvedSize.scale(style().effectiveZoom()); 923 resolvedSize.clampToMinimumSize(minimumSize); 924 925 if (!resolvedSize.isEmpty()) 926 return resolvedSize; 927 928 // If the image has one of either an intrinsic width or an intrinsic height: 929 // * and an intrinsic aspect ratio, then the missing dimension is calculated from the given dimension and the ratio. 930 // * and no intrinsic aspect ratio, then the missing dimension is assumed to be the size of the rectangle that 931 // establishes the coordinate system for the 'background-position' property. 932 if (resolvedSize.width() > 0 || resolvedSize.height() > 0) 933 return resolveAgainstIntrinsicWidthOrHeightAndRatio(positioningAreaSize, intrinsicRatio, resolvedSize.width(), resolvedSize.height()); 934 935 // If the image has no intrinsic dimensions and has an intrinsic ratio the dimensions must be assumed to be the 936 // largest dimensions at that ratio such that neither dimension exceeds the dimensions of the rectangle that 937 // establishes the coordinate system for the 'background-position' property. 938 if (!intrinsicRatio.isEmpty()) 939 return resolveAgainstIntrinsicRatio(positioningAreaSize, intrinsicRatio); 940 941 // If the image has no intrinsic ratio either, then the dimensions must be assumed to be the rectangle that 942 // establishes the coordinate system for the 'background-position' property. 943 return positioningAreaSize; 944} 945 946LayoutSize RenderBoxModelObject::calculateFillTileSize(const FillLayer* fillLayer, const LayoutSize& positioningAreaSize) const 947{ 948 StyleImage* image = fillLayer->image(); 949 EFillSizeType type = fillLayer->size().type; 950 951 LayoutSize imageIntrinsicSize = calculateImageIntrinsicDimensions(image, positioningAreaSize, ScaleByEffectiveZoom); 952 imageIntrinsicSize.scale(1 / image->imageScaleFactor(), 1 / image->imageScaleFactor()); 953 switch (type) { 954 case SizeLength: { 955 LayoutSize tileSize = positioningAreaSize; 956 957 Length layerWidth = fillLayer->size().size.width(); 958 Length layerHeight = fillLayer->size().size.height(); 959 960 if (layerWidth.isFixed()) 961 tileSize.setWidth(layerWidth.value()); 962 else if (layerWidth.isPercent()) 963 tileSize.setWidth(valueForLength(layerWidth, positioningAreaSize.width())); 964 965 if (layerHeight.isFixed()) 966 tileSize.setHeight(layerHeight.value()); 967 else if (layerHeight.isPercent()) 968 tileSize.setHeight(valueForLength(layerHeight, positioningAreaSize.height())); 969 970 // If one of the values is auto we have to use the appropriate 971 // scale to maintain our aspect ratio. 972 if (layerWidth.isAuto() && !layerHeight.isAuto()) { 973 if (imageIntrinsicSize.height()) 974 tileSize.setWidth(imageIntrinsicSize.width() * tileSize.height() / imageIntrinsicSize.height()); 975 } else if (!layerWidth.isAuto() && layerHeight.isAuto()) { 976 if (imageIntrinsicSize.width()) 977 tileSize.setHeight(imageIntrinsicSize.height() * tileSize.width() / imageIntrinsicSize.width()); 978 } else if (layerWidth.isAuto() && layerHeight.isAuto()) { 979 // If both width and height are auto, use the image's intrinsic size. 980 tileSize = imageIntrinsicSize; 981 } 982 983 tileSize.clampNegativeToZero(); 984 return tileSize; 985 } 986 case SizeNone: { 987 // If both values are ‘auto’ then the intrinsic width and/or height of the image should be used, if any. 988 if (!imageIntrinsicSize.isEmpty()) 989 return imageIntrinsicSize; 990 991 // If the image has neither an intrinsic width nor an intrinsic height, its size is determined as for ‘contain’. 992 type = Contain; 993 } 994 FALLTHROUGH; 995 case Contain: 996 case Cover: { 997 // Scale computation needs higher precision than what LayoutUnit can offer. 998 FloatSize localImageIntrinsicSize = imageIntrinsicSize; 999 FloatSize localPositioningAreaSize = positioningAreaSize; 1000 1001 float horizontalScaleFactor = localImageIntrinsicSize.width() ? (localPositioningAreaSize.width() / localImageIntrinsicSize.width()) : 1; 1002 float verticalScaleFactor = localImageIntrinsicSize.height() ? (localPositioningAreaSize.height() / localImageIntrinsicSize.height()) : 1; 1003 float scaleFactor = type == Contain ? std::min(horizontalScaleFactor, verticalScaleFactor) : std::max(horizontalScaleFactor, verticalScaleFactor); 1004 float deviceScaleFactor = document().deviceScaleFactor(); 1005 return LayoutSize(std::max<LayoutUnit>(1 / deviceScaleFactor, localImageIntrinsicSize.width() * scaleFactor), 1006 std::max<LayoutUnit>(1 / deviceScaleFactor, localImageIntrinsicSize.height() * scaleFactor)); 1007 } 1008 } 1009 1010 ASSERT_NOT_REACHED(); 1011 return LayoutSize(); 1012} 1013 1014void RenderBoxModelObject::BackgroundImageGeometry::setNoRepeatX(LayoutUnit xOffset) 1015{ 1016 m_destRect.move(std::max<LayoutUnit>(xOffset, 0), 0); 1017 m_phase.setX(-std::min<LayoutUnit>(xOffset, 0)); 1018 m_destRect.setWidth(m_tileSize.width() + std::min<float>(xOffset, 0)); 1019} 1020void RenderBoxModelObject::BackgroundImageGeometry::setNoRepeatY(LayoutUnit yOffset) 1021{ 1022 m_destRect.move(0, std::max<LayoutUnit>(yOffset, 0)); 1023 m_phase.setY(-std::min<LayoutUnit>(yOffset, 0)); 1024 m_destRect.setHeight(m_tileSize.height() + std::min<float>(yOffset, 0)); 1025} 1026 1027void RenderBoxModelObject::BackgroundImageGeometry::useFixedAttachment(const LayoutPoint& attachmentPoint) 1028{ 1029 FloatPoint alignedPoint = attachmentPoint; 1030 m_phase.move(std::max<LayoutUnit>(alignedPoint.x() - m_destRect.x(), 0), std::max<LayoutUnit>(alignedPoint.y() - m_destRect.y(), 0)); 1031} 1032 1033void RenderBoxModelObject::BackgroundImageGeometry::clip(const LayoutRect& clipRect) 1034{ 1035 m_destRect.intersect(clipRect); 1036} 1037 1038LayoutPoint RenderBoxModelObject::BackgroundImageGeometry::relativePhase() const 1039{ 1040 LayoutPoint phase = m_phase; 1041 phase += m_destRect.location() - m_destOrigin; 1042 return phase; 1043} 1044 1045bool RenderBoxModelObject::fixedBackgroundPaintsInLocalCoordinates() const 1046{ 1047 if (!isRoot()) 1048 return false; 1049 1050 if (view().frameView().paintBehavior() & PaintBehaviorFlattenCompositingLayers) 1051 return false; 1052 1053 RenderLayer* rootLayer = view().layer(); 1054 if (!rootLayer || !rootLayer->isComposited()) 1055 return false; 1056 1057 return rootLayer->backing()->backgroundLayerPaintsFixedRootBackground(); 1058} 1059 1060static inline LayoutUnit getSpace(LayoutUnit areaSize, LayoutUnit tileSize) 1061{ 1062 int numberOfTiles = areaSize / tileSize; 1063 LayoutUnit space = -1; 1064 1065 if (numberOfTiles > 1) 1066 space = (areaSize - numberOfTiles * tileSize) / (numberOfTiles - 1); 1067 1068 return space; 1069} 1070 1071void RenderBoxModelObject::pixelSnapBackgroundImageGeometryForPainting(BackgroundImageGeometry& geometry) const 1072{ 1073 float deviceScaleFactor = document().deviceScaleFactor(); 1074 // FIXME: We need a better rounding strategy to round/space out tiles. 1075 geometry.setTileSize(LayoutSize(pixelSnappedForPainting(LayoutRect(geometry.destRect().location(), geometry.tileSize()), deviceScaleFactor).size())); 1076 geometry.setSpaceSize(LayoutSize(pixelSnappedForPainting(LayoutRect(LayoutPoint(), geometry.spaceSize()), deviceScaleFactor).size())); 1077 geometry.setDestOrigin(LayoutPoint(roundedForPainting(geometry.destOrigin(), deviceScaleFactor))); 1078 geometry.setDestRect(LayoutRect(pixelSnappedForPainting(geometry.destRect(), deviceScaleFactor))); 1079 geometry.setPhase(LayoutPoint(roundedForPainting(geometry.phase(), deviceScaleFactor))); 1080} 1081 1082void RenderBoxModelObject::calculateBackgroundImageGeometry(const RenderLayerModelObject* paintContainer, const FillLayer* fillLayer, const LayoutRect& paintRect, 1083 BackgroundImageGeometry& geometry, RenderElement* backgroundObject) const 1084{ 1085 LayoutUnit left = 0; 1086 LayoutUnit top = 0; 1087 LayoutSize positioningAreaSize; 1088 // Determine the background positioning area and set destRect to the background painting area. 1089 // destRect will be adjusted later if the background is non-repeating. 1090 // FIXME: transforms spec says that fixed backgrounds behave like scroll inside transforms. https://bugs.webkit.org/show_bug.cgi?id=15679 1091 bool fixedAttachment = fillLayer->attachment() == FixedBackgroundAttachment; 1092 if (!fixedAttachment) { 1093 geometry.setDestRect(paintRect); 1094 1095 LayoutUnit right = 0; 1096 LayoutUnit bottom = 0; 1097 // Scroll and Local. 1098 if (fillLayer->origin() != BorderFillBox) { 1099 left = borderLeft(); 1100 right = borderRight(); 1101 top = borderTop(); 1102 bottom = borderBottom(); 1103 if (fillLayer->origin() == ContentFillBox) { 1104 left += paddingLeft(); 1105 right += paddingRight(); 1106 top += paddingTop(); 1107 bottom += paddingBottom(); 1108 } 1109 } 1110 1111 // The background of the box generated by the root element covers the entire canvas including 1112 // its margins. Since those were added in already, we have to factor them out when computing 1113 // the background positioning area. 1114 if (isRoot()) { 1115 positioningAreaSize = toRenderBox(this)->size() - LayoutSize(left + right, top + bottom); 1116 if (view().frameView().hasExtendedBackgroundRectForPainting()) { 1117 LayoutRect extendedBackgroundRect = view().frameView().extendedBackgroundRectForPainting(); 1118 left += (marginLeft() - extendedBackgroundRect.x()); 1119 top += (marginTop() - extendedBackgroundRect.y()); 1120 } 1121 } else 1122 positioningAreaSize = paintRect.size() - LayoutSize(left + right, top + bottom); 1123 } else { 1124 geometry.setHasNonLocalGeometry(); 1125 1126 LayoutRect viewportRect; 1127 if (frame().settings().fixedBackgroundsPaintRelativeToDocument()) 1128 viewportRect = view().unscaledDocumentRect(); 1129 else { 1130 viewportRect.setSize(view().frameView().unscaledVisibleContentSizeIncludingObscuredArea()); 1131 if (fixedBackgroundPaintsInLocalCoordinates()) 1132 viewportRect.setLocation(LayoutPoint()); 1133 else { 1134 viewportRect.setLocation(toLayoutPoint(view().frameView().documentScrollOffsetRelativeToViewOrigin())); 1135 top += view().frameView().topContentInset(ScrollView::TopContentInsetType::WebCoreOrPlatformContentInset); 1136 } 1137 } 1138 1139 if (paintContainer) 1140 viewportRect.moveBy(LayoutPoint(-paintContainer->localToAbsolute(FloatPoint()))); 1141 1142 geometry.setDestRect(viewportRect); 1143 positioningAreaSize = geometry.destRect().size(); 1144 } 1145 1146 auto clientForBackgroundImage = backgroundObject ? backgroundObject : this; 1147 LayoutSize fillTileSize = calculateFillTileSize(fillLayer, positioningAreaSize); 1148 fillLayer->image()->setContainerSizeForRenderer(clientForBackgroundImage, fillTileSize, style().effectiveZoom()); 1149 geometry.setTileSize(fillTileSize); 1150 1151 EFillRepeat backgroundRepeatX = fillLayer->repeatX(); 1152 EFillRepeat backgroundRepeatY = fillLayer->repeatY(); 1153 LayoutUnit availableWidth = positioningAreaSize.width() - geometry.tileSize().width(); 1154 LayoutUnit availableHeight = positioningAreaSize.height() - geometry.tileSize().height(); 1155 1156 LayoutUnit computedXPosition = minimumValueForLength(fillLayer->xPosition(), availableWidth, false); 1157 if (backgroundRepeatX == RoundFill && positioningAreaSize.width() > 0 && fillTileSize.width() > 0) { 1158 int numTiles = std::max(1, roundToInt(positioningAreaSize.width() / fillTileSize.width())); 1159 if (fillLayer->size().size.height().isAuto() && backgroundRepeatY != RoundFill) 1160 fillTileSize.setHeight(fillTileSize.height() * positioningAreaSize.width() / (numTiles * fillTileSize.width())); 1161 1162 fillTileSize.setWidth(positioningAreaSize.width() / numTiles); 1163 geometry.setTileSize(fillTileSize); 1164 geometry.setPhaseX(geometry.tileSize().width() ? geometry.tileSize().width() - fmodf((computedXPosition + left), geometry.tileSize().width()) : 0); 1165 geometry.setSpaceSize(LayoutSize()); 1166 } 1167 1168 LayoutUnit computedYPosition = minimumValueForLength(fillLayer->yPosition(), availableHeight, false); 1169 if (backgroundRepeatY == RoundFill && positioningAreaSize.height() > 0 && fillTileSize.height() > 0) { 1170 int numTiles = std::max(1, roundToInt(positioningAreaSize.height() / fillTileSize.height())); 1171 if (fillLayer->size().size.width().isAuto() && backgroundRepeatX != RoundFill) 1172 fillTileSize.setWidth(fillTileSize.width() * positioningAreaSize.height() / (numTiles * fillTileSize.height())); 1173 1174 fillTileSize.setHeight(positioningAreaSize.height() / numTiles); 1175 geometry.setTileSize(fillTileSize); 1176 geometry.setPhaseY(geometry.tileSize().height() ? geometry.tileSize().height() - fmodf((computedYPosition + top), geometry.tileSize().height()) : 0); 1177 geometry.setSpaceSize(LayoutSize()); 1178 } 1179 1180 if (backgroundRepeatX == RepeatFill) { 1181 geometry.setPhaseX(geometry.tileSize().width() ? geometry.tileSize().width() - fmodf(computedXPosition + left, geometry.tileSize().width()): 0); 1182 geometry.setSpaceSize(LayoutSize(0, geometry.spaceSize().height())); 1183 } else if (backgroundRepeatX == SpaceFill && fillTileSize.width() > 0) { 1184 LayoutUnit space = getSpace(positioningAreaSize.width(), geometry.tileSize().width()); 1185 LayoutUnit actualWidth = geometry.tileSize().width() + space; 1186 1187 if (space >= 0) { 1188 computedXPosition = minimumValueForLength(Length(), availableWidth, false); 1189 geometry.setSpaceSize(LayoutSize(space, 0)); 1190 geometry.setPhaseX(actualWidth ? actualWidth - fmodf((computedXPosition + left), actualWidth) : 0); 1191 } else 1192 backgroundRepeatX = NoRepeatFill; 1193 } 1194 if (backgroundRepeatX == NoRepeatFill) { 1195 LayoutUnit xOffset = fillLayer->backgroundXOrigin() == RightEdge ? availableWidth - computedXPosition : computedXPosition; 1196 geometry.setNoRepeatX(left + xOffset); 1197 geometry.setSpaceSize(LayoutSize(0, geometry.spaceSize().height())); 1198 } 1199 1200 if (backgroundRepeatY == RepeatFill) { 1201 geometry.setPhaseY(geometry.tileSize().height() ? geometry.tileSize().height() - fmodf(computedYPosition + top, geometry.tileSize().height()) : 0); 1202 geometry.setSpaceSize(LayoutSize(geometry.spaceSize().width(), 0)); 1203 } else if (backgroundRepeatY == SpaceFill && fillTileSize.height() > 0) { 1204 LayoutUnit space = getSpace(positioningAreaSize.height(), geometry.tileSize().height()); 1205 LayoutUnit actualHeight = geometry.tileSize().height() + space; 1206 1207 if (space >= 0) { 1208 computedYPosition = minimumValueForLength(Length(), availableHeight, false); 1209 geometry.setSpaceSize(LayoutSize(geometry.spaceSize().width(), space)); 1210 geometry.setPhaseY(actualHeight ? actualHeight - fmodf((computedYPosition + top), actualHeight) : 0); 1211 } else 1212 backgroundRepeatY = NoRepeatFill; 1213 } 1214 if (backgroundRepeatY == NoRepeatFill) { 1215 LayoutUnit yOffset = fillLayer->backgroundYOrigin() == BottomEdge ? availableHeight - computedYPosition : computedYPosition; 1216 geometry.setNoRepeatY(top + yOffset); 1217 geometry.setSpaceSize(LayoutSize(geometry.spaceSize().width(), 0)); 1218 } 1219 1220 if (fixedAttachment) 1221 geometry.useFixedAttachment(paintRect.location()); 1222 1223 geometry.clip(paintRect); 1224 geometry.setDestOrigin(geometry.destRect().location()); 1225 1226 pixelSnapBackgroundImageGeometryForPainting(geometry); 1227} 1228 1229void RenderBoxModelObject::getGeometryForBackgroundImage(const RenderLayerModelObject* paintContainer, FloatRect& destRect, FloatPoint& phase, FloatSize& tileSize) const 1230{ 1231 const FillLayer* backgroundLayer = style().backgroundLayers(); 1232 BackgroundImageGeometry geometry; 1233 LayoutRect paintRect = LayoutRect(destRect); 1234 calculateBackgroundImageGeometry(paintContainer, backgroundLayer, paintRect, geometry); 1235 phase = geometry.phase(); 1236 tileSize = geometry.tileSize(); 1237 destRect = geometry.destRect(); 1238} 1239 1240static LayoutUnit computeBorderImageSide(Length borderSlice, LayoutUnit borderSide, LayoutUnit imageSide, LayoutUnit boxExtent) 1241{ 1242 if (borderSlice.isRelative()) 1243 return borderSlice.value() * borderSide; 1244 if (borderSlice.isAuto()) 1245 return imageSide; 1246 return valueForLength(borderSlice, boxExtent); 1247} 1248 1249bool RenderBoxModelObject::paintNinePieceImage(GraphicsContext* graphicsContext, const LayoutRect& rect, const RenderStyle& style, 1250 const NinePieceImage& ninePieceImage, CompositeOperator op) 1251{ 1252 StyleImage* styleImage = ninePieceImage.image(); 1253 if (!styleImage) 1254 return false; 1255 1256 if (!styleImage->isLoaded()) 1257 return true; // Never paint a nine-piece image incrementally, but don't paint the fallback borders either. 1258 1259 if (!styleImage->canRender(this, style.effectiveZoom())) 1260 return false; 1261 1262 // FIXME: border-image is broken with full page zooming when tiling has to happen, since the tiling function 1263 // doesn't have any understanding of the zoom that is in effect on the tile. 1264 float deviceScaleFactor = document().deviceScaleFactor(); 1265 LayoutRect rectWithOutsets = rect; 1266 rectWithOutsets.expand(style.imageOutsets(ninePieceImage)); 1267 LayoutRect borderImageRect = LayoutRect(pixelSnappedForPainting(rectWithOutsets, deviceScaleFactor)); 1268 1269 LayoutSize imageSize = calculateImageIntrinsicDimensions(styleImage, borderImageRect.size(), DoNotScaleByEffectiveZoom); 1270 1271 // If both values are ‘auto’ then the intrinsic width and/or height of the image should be used, if any. 1272 styleImage->setContainerSizeForRenderer(this, imageSize, style.effectiveZoom()); 1273 1274 LayoutUnit imageWidth = imageSize.width(); 1275 LayoutUnit imageHeight = imageSize.height(); 1276 1277 float imageScaleFactor = styleImage->imageScaleFactor(); 1278 LayoutUnit topSlice = std::min<LayoutUnit>(imageHeight, valueForLength(ninePieceImage.imageSlices().top(), imageHeight)) * imageScaleFactor; 1279 LayoutUnit rightSlice = std::min<LayoutUnit>(imageWidth, valueForLength(ninePieceImage.imageSlices().right(), imageWidth)) * imageScaleFactor; 1280 LayoutUnit bottomSlice = std::min<LayoutUnit>(imageHeight, valueForLength(ninePieceImage.imageSlices().bottom(), imageHeight)) * imageScaleFactor; 1281 LayoutUnit leftSlice = std::min<LayoutUnit>(imageWidth, valueForLength(ninePieceImage.imageSlices().left(), imageWidth)) * imageScaleFactor; 1282 1283 ENinePieceImageRule hRule = ninePieceImage.horizontalRule(); 1284 ENinePieceImageRule vRule = ninePieceImage.verticalRule(); 1285 1286 LayoutUnit topWidth = computeBorderImageSide(ninePieceImage.borderSlices().top(), style.borderTopWidth(), topSlice, borderImageRect.height()); 1287 LayoutUnit rightWidth = computeBorderImageSide(ninePieceImage.borderSlices().right(), style.borderRightWidth(), rightSlice, borderImageRect.width()); 1288 LayoutUnit bottomWidth = computeBorderImageSide(ninePieceImage.borderSlices().bottom(), style.borderBottomWidth(), bottomSlice, borderImageRect.height()); 1289 LayoutUnit leftWidth = computeBorderImageSide(ninePieceImage.borderSlices().left(), style.borderLeftWidth(), leftSlice, borderImageRect.width()); 1290 1291 // Reduce the widths if they're too large. 1292 // The spec says: Given Lwidth as the width of the border image area, Lheight as its height, and Wside as the border image width 1293 // offset for the side, let f = min(Lwidth/(Wleft+Wright), Lheight/(Wtop+Wbottom)). If f < 1, then all W are reduced by 1294 // multiplying them by f. 1295 LayoutUnit borderSideWidth = std::max<LayoutUnit>(1 / deviceScaleFactor, leftWidth + rightWidth); 1296 LayoutUnit borderSideHeight = std::max<LayoutUnit>(1 / deviceScaleFactor, topWidth + bottomWidth); 1297 float borderSideScaleFactor = std::min((float)borderImageRect.width() / borderSideWidth, (float)borderImageRect.height() / borderSideHeight); 1298 if (borderSideScaleFactor < 1) { 1299 topWidth *= borderSideScaleFactor; 1300 rightWidth *= borderSideScaleFactor; 1301 bottomWidth *= borderSideScaleFactor; 1302 leftWidth *= borderSideScaleFactor; 1303 } 1304 1305 bool drawLeft = leftSlice > 0 && leftWidth > 0; 1306 bool drawTop = topSlice > 0 && topWidth > 0; 1307 bool drawRight = rightSlice > 0 && rightWidth > 0; 1308 bool drawBottom = bottomSlice > 0 && bottomWidth > 0; 1309 bool drawMiddle = ninePieceImage.fill() && (imageWidth - leftSlice - rightSlice) > 0 && (borderImageRect.width() - leftWidth - rightWidth) > 0 1310 && (imageHeight - topSlice - bottomSlice) > 0 && (borderImageRect.height() - topWidth - bottomWidth) > 0; 1311 1312 RefPtr<Image> image = styleImage->image(this, imageSize); 1313 ColorSpace colorSpace = style.colorSpace(); 1314 1315 float destinationWidth = borderImageRect.width() - leftWidth - rightWidth; 1316 float destinationHeight = borderImageRect.height() - topWidth - bottomWidth; 1317 1318 float sourceWidth = imageWidth - leftSlice - rightSlice; 1319 float sourceHeight = imageHeight - topSlice - bottomSlice; 1320 1321 float leftSideScale = drawLeft ? (float)leftWidth / leftSlice : 1; 1322 float rightSideScale = drawRight ? (float)rightWidth / rightSlice : 1; 1323 float topSideScale = drawTop ? (float)topWidth / topSlice : 1; 1324 float bottomSideScale = drawBottom ? (float)bottomWidth / bottomSlice : 1; 1325 1326 float x = borderImageRect.location().x(); 1327 float y = borderImageRect.location().y(); 1328 if (drawLeft) { 1329 // Paint the top and bottom left corners. 1330 1331 // The top left corner rect is (tx, ty, leftWidth, topWidth) 1332 // The rect to use from within the image is obtained from our slice, and is (0, 0, leftSlice, topSlice) 1333 if (drawTop) 1334 graphicsContext->drawImage(image.get(), colorSpace, pixelSnappedForPainting(x, y, leftWidth, topWidth, deviceScaleFactor), 1335 pixelSnappedForPainting(0, 0, leftSlice, topSlice, deviceScaleFactor), op); 1336 1337 // The bottom left corner rect is (tx, ty + h - bottomWidth, leftWidth, bottomWidth) 1338 // The rect to use from within the image is (0, imageHeight - bottomSlice, leftSlice, botomSlice) 1339 if (drawBottom) 1340 graphicsContext->drawImage(image.get(), colorSpace, pixelSnappedForPainting(x, borderImageRect.maxY() - bottomWidth, leftWidth, bottomWidth, deviceScaleFactor), 1341 pixelSnappedForPainting(0, imageHeight - bottomSlice, leftSlice, bottomSlice, deviceScaleFactor), op); 1342 1343 // Paint the left edge. 1344 // Have to scale and tile into the border rect. 1345 if (sourceHeight > 0) 1346 graphicsContext->drawTiledImage(image.get(), colorSpace, pixelSnappedForPainting(x, y + topWidth, leftWidth, destinationHeight, deviceScaleFactor), 1347 pixelSnappedForPainting(0, topSlice, leftSlice, sourceHeight, deviceScaleFactor), FloatSize(leftSideScale, leftSideScale), Image::StretchTile, (Image::TileRule)vRule, op); 1348 } 1349 1350 if (drawRight) { 1351 // Paint the top and bottom right corners 1352 // The top right corner rect is (tx + w - rightWidth, ty, rightWidth, topWidth) 1353 // The rect to use from within the image is obtained from our slice, and is (imageWidth - rightSlice, 0, rightSlice, topSlice) 1354 if (drawTop) 1355 graphicsContext->drawImage(image.get(), colorSpace, pixelSnappedForPainting(borderImageRect.maxX() - rightWidth, y, rightWidth, topWidth, deviceScaleFactor), 1356 pixelSnappedForPainting(imageWidth - rightSlice, 0, rightSlice, topSlice, deviceScaleFactor), op); 1357 1358 // The bottom right corner rect is (tx + w - rightWidth, ty + h - bottomWidth, rightWidth, bottomWidth) 1359 // The rect to use from within the image is (imageWidth - rightSlice, imageHeight - bottomSlice, rightSlice, bottomSlice) 1360 if (drawBottom) 1361 graphicsContext->drawImage(image.get(), colorSpace, pixelSnappedForPainting(borderImageRect.maxX() - rightWidth, borderImageRect.maxY() - bottomWidth, 1362 rightWidth, bottomWidth, deviceScaleFactor), pixelSnappedForPainting(imageWidth - rightSlice, imageHeight - bottomSlice, rightSlice, bottomSlice, deviceScaleFactor), 1363 op); 1364 1365 // Paint the right edge. 1366 if (sourceHeight > 0) 1367 graphicsContext->drawTiledImage(image.get(), colorSpace, pixelSnappedForPainting(borderImageRect.maxX() - rightWidth, y + topWidth, rightWidth, destinationHeight, deviceScaleFactor), 1368 pixelSnappedForPainting(imageWidth - rightSlice, topSlice, rightSlice, sourceHeight, deviceScaleFactor), FloatSize(rightSideScale, rightSideScale), 1369 Image::StretchTile, (Image::TileRule)vRule, op); 1370 } 1371 1372 // Paint the top edge. 1373 if (drawTop && sourceWidth > 0) 1374 graphicsContext->drawTiledImage(image.get(), colorSpace, pixelSnappedForPainting(x + leftWidth, y, destinationWidth, topWidth, deviceScaleFactor), 1375 pixelSnappedForPainting(leftSlice, 0, sourceWidth, topSlice, deviceScaleFactor), FloatSize(topSideScale, topSideScale), (Image::TileRule)hRule, Image::StretchTile, op); 1376 1377 // Paint the bottom edge. 1378 if (drawBottom && sourceWidth > 0) 1379 graphicsContext->drawTiledImage(image.get(), colorSpace, pixelSnappedForPainting(x + leftWidth, borderImageRect.maxY() - bottomWidth, destinationWidth, bottomWidth, deviceScaleFactor), 1380 pixelSnappedForPainting(leftSlice, imageHeight - bottomSlice, sourceWidth, bottomSlice, deviceScaleFactor), FloatSize(bottomSideScale, bottomSideScale), 1381 (Image::TileRule)hRule, Image::StretchTile, op); 1382 1383 // Paint the middle. 1384 if (drawMiddle) { 1385 FloatSize middleScaleFactor(1, 1); 1386 if (drawTop) 1387 middleScaleFactor.setWidth(topSideScale); 1388 else if (drawBottom) 1389 middleScaleFactor.setWidth(bottomSideScale); 1390 if (drawLeft) 1391 middleScaleFactor.setHeight(leftSideScale); 1392 else if (drawRight) 1393 middleScaleFactor.setHeight(rightSideScale); 1394 1395 // For "stretch" rules, just override the scale factor and replace. We only had to do this for the 1396 // center tile, since sides don't even use the scale factor unless they have a rule other than "stretch". 1397 // The middle however can have "stretch" specified in one axis but not the other, so we have to 1398 // correct the scale here. 1399 if (hRule == StretchImageRule) 1400 middleScaleFactor.setWidth(destinationWidth / sourceWidth); 1401 1402 if (vRule == StretchImageRule) 1403 middleScaleFactor.setHeight(destinationHeight / sourceHeight); 1404 1405 graphicsContext->drawTiledImage(image.get(), colorSpace, 1406 pixelSnappedForPainting(x + leftWidth, y + topWidth, destinationWidth, destinationHeight, deviceScaleFactor), 1407 pixelSnappedForPainting(leftSlice, topSlice, sourceWidth, sourceHeight, deviceScaleFactor), 1408 middleScaleFactor, (Image::TileRule)hRule, (Image::TileRule)vRule, op); 1409 } 1410 1411 return true; 1412} 1413 1414static bool allCornersClippedOut(const RoundedRect& border, const LayoutRect& clipRect) 1415{ 1416 LayoutRect boundingRect = border.rect(); 1417 if (clipRect.contains(boundingRect)) 1418 return false; 1419 1420 RoundedRect::Radii radii = border.radii(); 1421 1422 LayoutRect topLeftRect(boundingRect.location(), radii.topLeft()); 1423 if (clipRect.intersects(topLeftRect)) 1424 return false; 1425 1426 LayoutRect topRightRect(boundingRect.location(), radii.topRight()); 1427 topRightRect.setX(boundingRect.maxX() - topRightRect.width()); 1428 if (clipRect.intersects(topRightRect)) 1429 return false; 1430 1431 LayoutRect bottomLeftRect(boundingRect.location(), radii.bottomLeft()); 1432 bottomLeftRect.setY(boundingRect.maxY() - bottomLeftRect.height()); 1433 if (clipRect.intersects(bottomLeftRect)) 1434 return false; 1435 1436 LayoutRect bottomRightRect(boundingRect.location(), radii.bottomRight()); 1437 bottomRightRect.setX(boundingRect.maxX() - bottomRightRect.width()); 1438 bottomRightRect.setY(boundingRect.maxY() - bottomRightRect.height()); 1439 if (clipRect.intersects(bottomRightRect)) 1440 return false; 1441 1442 return true; 1443} 1444 1445static bool borderWillArcInnerEdge(const LayoutSize& firstRadius, const FloatSize& secondRadius) 1446{ 1447 return !firstRadius.isZero() || !secondRadius.isZero(); 1448} 1449 1450inline bool styleRequiresClipPolygon(EBorderStyle style) 1451{ 1452 return style == DOTTED || style == DASHED; // These are drawn with a stroke, so we have to clip to get corner miters. 1453} 1454 1455static bool borderStyleFillsBorderArea(EBorderStyle style) 1456{ 1457 return !(style == DOTTED || style == DASHED || style == DOUBLE); 1458} 1459 1460static bool borderStyleHasInnerDetail(EBorderStyle style) 1461{ 1462 return style == GROOVE || style == RIDGE || style == DOUBLE; 1463} 1464 1465static bool borderStyleIsDottedOrDashed(EBorderStyle style) 1466{ 1467 return style == DOTTED || style == DASHED; 1468} 1469 1470// OUTSET darkens the bottom and right (and maybe lightens the top and left) 1471// INSET darkens the top and left (and maybe lightens the bottom and right) 1472static inline bool borderStyleHasUnmatchedColorsAtCorner(EBorderStyle style, BoxSide side, BoxSide adjacentSide) 1473{ 1474 // These styles match at the top/left and bottom/right. 1475 if (style == INSET || style == GROOVE || style == RIDGE || style == OUTSET) { 1476 const BorderEdgeFlags topRightFlags = edgeFlagForSide(BSTop) | edgeFlagForSide(BSRight); 1477 const BorderEdgeFlags bottomLeftFlags = edgeFlagForSide(BSBottom) | edgeFlagForSide(BSLeft); 1478 1479 BorderEdgeFlags flags = edgeFlagForSide(side) | edgeFlagForSide(adjacentSide); 1480 return flags == topRightFlags || flags == bottomLeftFlags; 1481 } 1482 return false; 1483} 1484 1485static inline bool colorsMatchAtCorner(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[]) 1486{ 1487 if (edges[side].shouldRender() != edges[adjacentSide].shouldRender()) 1488 return false; 1489 1490 if (!edgesShareColor(edges[side], edges[adjacentSide])) 1491 return false; 1492 1493 return !borderStyleHasUnmatchedColorsAtCorner(edges[side].style(), side, adjacentSide); 1494} 1495 1496 1497static inline bool colorNeedsAntiAliasAtCorner(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[]) 1498{ 1499 if (!edges[side].color().hasAlpha()) 1500 return false; 1501 1502 if (edges[side].shouldRender() != edges[adjacentSide].shouldRender()) 1503 return false; 1504 1505 if (!edgesShareColor(edges[side], edges[adjacentSide])) 1506 return true; 1507 1508 return borderStyleHasUnmatchedColorsAtCorner(edges[side].style(), side, adjacentSide); 1509} 1510 1511// This assumes that we draw in order: top, bottom, left, right. 1512static inline bool willBeOverdrawn(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[]) 1513{ 1514 switch (side) { 1515 case BSTop: 1516 case BSBottom: 1517 if (edges[adjacentSide].presentButInvisible()) 1518 return false; 1519 1520 if (!edgesShareColor(edges[side], edges[adjacentSide]) && edges[adjacentSide].color().hasAlpha()) 1521 return false; 1522 1523 if (!borderStyleFillsBorderArea(edges[adjacentSide].style())) 1524 return false; 1525 1526 return true; 1527 1528 case BSLeft: 1529 case BSRight: 1530 // These draw last, so are never overdrawn. 1531 return false; 1532 } 1533 return false; 1534} 1535 1536static inline bool borderStylesRequireMitre(BoxSide side, BoxSide adjacentSide, EBorderStyle style, EBorderStyle adjacentStyle) 1537{ 1538 if (style == DOUBLE || adjacentStyle == DOUBLE || adjacentStyle == GROOVE || adjacentStyle == RIDGE) 1539 return true; 1540 1541 if (borderStyleIsDottedOrDashed(style) != borderStyleIsDottedOrDashed(adjacentStyle)) 1542 return true; 1543 1544 if (style != adjacentStyle) 1545 return true; 1546 1547 return borderStyleHasUnmatchedColorsAtCorner(style, side, adjacentSide); 1548} 1549 1550static bool joinRequiresMitre(BoxSide side, BoxSide adjacentSide, const BorderEdge edges[], bool allowOverdraw) 1551{ 1552 if ((edges[side].isTransparent() && edges[adjacentSide].isTransparent()) || !edges[adjacentSide].isPresent()) 1553 return false; 1554 1555 if (allowOverdraw && willBeOverdrawn(side, adjacentSide, edges)) 1556 return false; 1557 1558 if (!edgesShareColor(edges[side], edges[adjacentSide])) 1559 return true; 1560 1561 if (borderStylesRequireMitre(side, adjacentSide, edges[side].style(), edges[adjacentSide].style())) 1562 return true; 1563 1564 return false; 1565} 1566 1567void RenderBoxModelObject::paintOneBorderSide(GraphicsContext* graphicsContext, const RenderStyle& style, const RoundedRect& outerBorder, const RoundedRect& innerBorder, 1568 const LayoutRect& sideRect, BoxSide side, BoxSide adjacentSide1, BoxSide adjacentSide2, const BorderEdge edges[], const Path* path, 1569 BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias, const Color* overrideColor) 1570{ 1571 const BorderEdge& edgeToRender = edges[side]; 1572 ASSERT(edgeToRender.widthForPainting()); 1573 const BorderEdge& adjacentEdge1 = edges[adjacentSide1]; 1574 const BorderEdge& adjacentEdge2 = edges[adjacentSide2]; 1575 1576 bool mitreAdjacentSide1 = joinRequiresMitre(side, adjacentSide1, edges, !antialias); 1577 bool mitreAdjacentSide2 = joinRequiresMitre(side, adjacentSide2, edges, !antialias); 1578 1579 bool adjacentSide1StylesMatch = colorsMatchAtCorner(side, adjacentSide1, edges); 1580 bool adjacentSide2StylesMatch = colorsMatchAtCorner(side, adjacentSide2, edges); 1581 1582 const Color& colorToPaint = overrideColor ? *overrideColor : edgeToRender.color(); 1583 1584 if (path) { 1585 GraphicsContextStateSaver stateSaver(*graphicsContext); 1586 if (innerBorder.isRenderable()) 1587 clipBorderSidePolygon(graphicsContext, outerBorder, innerBorder, side, adjacentSide1StylesMatch, adjacentSide2StylesMatch); 1588 else 1589 clipBorderSideForComplexInnerPath(graphicsContext, outerBorder, innerBorder, side, edges); 1590 float thickness = std::max(std::max(edgeToRender.widthForPainting(), adjacentEdge1.widthForPainting()), adjacentEdge2.widthForPainting()); 1591 drawBoxSideFromPath(graphicsContext, outerBorder.rect(), *path, edges, edgeToRender.widthForPainting(), thickness, side, style, 1592 colorToPaint, edgeToRender.style(), bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge); 1593 } else { 1594 bool clipForStyle = styleRequiresClipPolygon(edgeToRender.style()) && (mitreAdjacentSide1 || mitreAdjacentSide2); 1595 bool clipAdjacentSide1 = colorNeedsAntiAliasAtCorner(side, adjacentSide1, edges) && mitreAdjacentSide1; 1596 bool clipAdjacentSide2 = colorNeedsAntiAliasAtCorner(side, adjacentSide2, edges) && mitreAdjacentSide2; 1597 bool shouldClip = clipForStyle || clipAdjacentSide1 || clipAdjacentSide2; 1598 1599 GraphicsContextStateSaver clipStateSaver(*graphicsContext, shouldClip); 1600 if (shouldClip) { 1601 bool aliasAdjacentSide1 = clipAdjacentSide1 || (clipForStyle && mitreAdjacentSide1); 1602 bool aliasAdjacentSide2 = clipAdjacentSide2 || (clipForStyle && mitreAdjacentSide2); 1603 clipBorderSidePolygon(graphicsContext, outerBorder, innerBorder, side, !aliasAdjacentSide1, !aliasAdjacentSide2); 1604 // Since we clipped, no need to draw with a mitre. 1605 mitreAdjacentSide1 = false; 1606 mitreAdjacentSide2 = false; 1607 } 1608 1609 drawLineForBoxSide(graphicsContext, sideRect.x(), sideRect.y(), sideRect.maxX(), sideRect.maxY(), side, colorToPaint, edgeToRender.style(), 1610 mitreAdjacentSide1 ? adjacentEdge1.widthForPainting() : 0, mitreAdjacentSide2 ? adjacentEdge2.widthForPainting() : 0, antialias); 1611 } 1612} 1613 1614static LayoutRect calculateSideRect(const RoundedRect& outerBorder, const BorderEdge edges[], int side) 1615{ 1616 LayoutRect sideRect = outerBorder.rect(); 1617 float width = edges[side].widthForPainting(); 1618 1619 if (side == BSTop) 1620 sideRect.setHeight(width); 1621 else if (side == BSBottom) 1622 sideRect.shiftYEdgeTo(sideRect.maxY() - width); 1623 else if (side == BSLeft) 1624 sideRect.setWidth(width); 1625 else 1626 sideRect.shiftXEdgeTo(sideRect.maxX() - width); 1627 1628 return sideRect; 1629} 1630 1631void RenderBoxModelObject::paintBorderSides(GraphicsContext* graphicsContext, const RenderStyle& style, const RoundedRect& outerBorder, const RoundedRect& innerBorder, 1632 const IntPoint& innerBorderAdjustment, const BorderEdge edges[], BorderEdgeFlags edgeSet, BackgroundBleedAvoidance bleedAvoidance, 1633 bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias, const Color* overrideColor) 1634{ 1635 bool renderRadii = outerBorder.isRounded(); 1636 1637 Path roundedPath; 1638 if (renderRadii) 1639 roundedPath.addRoundedRect(outerBorder); 1640 1641 // The inner border adjustment for bleed avoidance mode BackgroundBleedBackgroundOverBorder 1642 // is only applied to sideRect, which is okay since BackgroundBleedBackgroundOverBorder 1643 // is only to be used for solid borders and the shape of the border painted by drawBoxSideFromPath 1644 // only depends on sideRect when painting solid borders. 1645 1646 if (edges[BSTop].shouldRender() && includesEdge(edgeSet, BSTop)) { 1647 LayoutRect sideRect = outerBorder.rect(); 1648 sideRect.setHeight(edges[BSTop].widthForPainting() + innerBorderAdjustment.y()); 1649 1650 bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSTop].style()) || borderWillArcInnerEdge(innerBorder.radii().topLeft(), innerBorder.radii().topRight())); 1651 paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSTop, BSLeft, BSRight, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor); 1652 } 1653 1654 if (edges[BSBottom].shouldRender() && includesEdge(edgeSet, BSBottom)) { 1655 LayoutRect sideRect = outerBorder.rect(); 1656 sideRect.shiftYEdgeTo(sideRect.maxY() - edges[BSBottom].widthForPainting() - innerBorderAdjustment.y()); 1657 1658 bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSBottom].style()) || borderWillArcInnerEdge(innerBorder.radii().bottomLeft(), innerBorder.radii().bottomRight())); 1659 paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSBottom, BSLeft, BSRight, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor); 1660 } 1661 1662 if (edges[BSLeft].shouldRender() && includesEdge(edgeSet, BSLeft)) { 1663 LayoutRect sideRect = outerBorder.rect(); 1664 sideRect.setWidth(edges[BSLeft].widthForPainting() + innerBorderAdjustment.x()); 1665 1666 bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSLeft].style()) || borderWillArcInnerEdge(innerBorder.radii().bottomLeft(), innerBorder.radii().topLeft())); 1667 paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSLeft, BSTop, BSBottom, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor); 1668 } 1669 1670 if (edges[BSRight].shouldRender() && includesEdge(edgeSet, BSRight)) { 1671 LayoutRect sideRect = outerBorder.rect(); 1672 sideRect.shiftXEdgeTo(sideRect.maxX() - edges[BSRight].widthForPainting() - innerBorderAdjustment.x()); 1673 1674 bool usePath = renderRadii && (borderStyleHasInnerDetail(edges[BSRight].style()) || borderWillArcInnerEdge(innerBorder.radii().bottomRight(), innerBorder.radii().topRight())); 1675 paintOneBorderSide(graphicsContext, style, outerBorder, innerBorder, sideRect, BSRight, BSTop, BSBottom, edges, usePath ? &roundedPath : 0, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, overrideColor); 1676 } 1677} 1678 1679void RenderBoxModelObject::paintTranslucentBorderSides(GraphicsContext* graphicsContext, const RenderStyle& style, const RoundedRect& outerBorder, const RoundedRect& innerBorder, const IntPoint& innerBorderAdjustment, 1680 const BorderEdge edges[], BorderEdgeFlags edgesToDraw, BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge, bool antialias) 1681{ 1682 // willBeOverdrawn assumes that we draw in order: top, bottom, left, right. 1683 // This is different from BoxSide enum order. 1684 static BoxSide paintOrder[] = { BSTop, BSBottom, BSLeft, BSRight }; 1685 1686 while (edgesToDraw) { 1687 // Find undrawn edges sharing a color. 1688 Color commonColor; 1689 1690 BorderEdgeFlags commonColorEdgeSet = 0; 1691 for (size_t i = 0; i < sizeof(paintOrder) / sizeof(paintOrder[0]); ++i) { 1692 BoxSide currSide = paintOrder[i]; 1693 if (!includesEdge(edgesToDraw, currSide)) 1694 continue; 1695 1696 bool includeEdge; 1697 if (!commonColorEdgeSet) { 1698 commonColor = edges[currSide].color(); 1699 includeEdge = true; 1700 } else 1701 includeEdge = edges[currSide].color() == commonColor; 1702 1703 if (includeEdge) 1704 commonColorEdgeSet |= edgeFlagForSide(currSide); 1705 } 1706 1707 bool useTransparencyLayer = includesAdjacentEdges(commonColorEdgeSet) && commonColor.hasAlpha(); 1708 if (useTransparencyLayer) { 1709 graphicsContext->beginTransparencyLayer(static_cast<float>(commonColor.alpha()) / 255); 1710 commonColor = Color(commonColor.red(), commonColor.green(), commonColor.blue()); 1711 } 1712 1713 paintBorderSides(graphicsContext, style, outerBorder, innerBorder, innerBorderAdjustment, edges, commonColorEdgeSet, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias, &commonColor); 1714 1715 if (useTransparencyLayer) 1716 graphicsContext->endTransparencyLayer(); 1717 1718 edgesToDraw &= ~commonColorEdgeSet; 1719 } 1720} 1721 1722void RenderBoxModelObject::paintBorder(const PaintInfo& info, const LayoutRect& rect, const RenderStyle& style, 1723 BackgroundBleedAvoidance bleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) 1724{ 1725 GraphicsContext* graphicsContext = info.context; 1726 1727 if (graphicsContext->paintingDisabled()) 1728 return; 1729 1730 if (rect.isEmpty()) 1731 return; 1732 1733 // border-image is not affected by border-radius. 1734 if (paintNinePieceImage(graphicsContext, rect, style, style.borderImage())) 1735 return; 1736 1737 BorderEdge edges[4]; 1738 BorderEdge::getBorderEdgeInfo(edges, style, document().deviceScaleFactor(), includeLogicalLeftEdge, includeLogicalRightEdge); 1739 RoundedRect outerBorder = style.getRoundedBorderFor(rect, includeLogicalLeftEdge, includeLogicalRightEdge); 1740 RoundedRect innerBorder = style.getRoundedInnerBorderFor(borderInnerRectAdjustedForBleedAvoidance(*graphicsContext, rect, bleedAvoidance), includeLogicalLeftEdge, includeLogicalRightEdge); 1741 1742 bool haveAlphaColor = false; 1743 bool haveAllSolidEdges = true; 1744 bool haveAllDoubleEdges = true; 1745 int numEdgesVisible = 4; 1746 bool allEdgesShareColor = true; 1747 int firstVisibleEdge = -1; 1748 BorderEdgeFlags edgesToDraw = 0; 1749 1750 for (int i = BSTop; i <= BSLeft; ++i) { 1751 const BorderEdge& currEdge = edges[i]; 1752 1753 if (edges[i].shouldRender()) 1754 edgesToDraw |= edgeFlagForSide(static_cast<BoxSide>(i)); 1755 1756 if (currEdge.presentButInvisible()) { 1757 --numEdgesVisible; 1758 allEdgesShareColor = false; 1759 continue; 1760 } 1761 1762 if (!currEdge.widthForPainting()) { 1763 --numEdgesVisible; 1764 continue; 1765 } 1766 1767 if (firstVisibleEdge == -1) 1768 firstVisibleEdge = i; 1769 else if (currEdge.color() != edges[firstVisibleEdge].color()) 1770 allEdgesShareColor = false; 1771 1772 if (currEdge.color().hasAlpha()) 1773 haveAlphaColor = true; 1774 1775 if (currEdge.style() != SOLID) 1776 haveAllSolidEdges = false; 1777 1778 if (currEdge.style() != DOUBLE) 1779 haveAllDoubleEdges = false; 1780 } 1781 1782 // If no corner intersects the clip region, we can pretend outerBorder is 1783 // rectangular to improve performance. 1784 if (haveAllSolidEdges && outerBorder.isRounded() && allCornersClippedOut(outerBorder, info.rect)) 1785 outerBorder.setRadii(RoundedRect::Radii()); 1786 1787 float deviceScaleFactor = document().deviceScaleFactor(); 1788 // isRenderable() check avoids issue described in https://bugs.webkit.org/show_bug.cgi?id=38787 1789 if ((haveAllSolidEdges || haveAllDoubleEdges) && allEdgesShareColor && innerBorder.isRenderable()) { 1790 // Fast path for drawing all solid edges and all unrounded double edges 1791 if (numEdgesVisible == 4 && (outerBorder.isRounded() || haveAlphaColor) 1792 && (haveAllSolidEdges || (!outerBorder.isRounded() && !innerBorder.isRounded()))) { 1793 Path path; 1794 1795 FloatRoundedRect pixelSnappedOuterBorder = outerBorder.pixelSnappedRoundedRectForPainting(deviceScaleFactor); 1796 if (pixelSnappedOuterBorder.isRounded() && bleedAvoidance != BackgroundBleedUseTransparencyLayer) 1797 path.addRoundedRect(pixelSnappedOuterBorder); 1798 else 1799 path.addRect(pixelSnappedOuterBorder.rect()); 1800 1801 if (haveAllDoubleEdges) { 1802 LayoutRect innerThirdRect = outerBorder.rect(); 1803 LayoutRect outerThirdRect = outerBorder.rect(); 1804 for (int side = BSTop; side <= BSLeft; ++side) { 1805 LayoutUnit outerWidth; 1806 LayoutUnit innerWidth; 1807 edges[side].getDoubleBorderStripeWidths(outerWidth, innerWidth); 1808 1809 if (side == BSTop) { 1810 innerThirdRect.shiftYEdgeTo(innerThirdRect.y() + innerWidth); 1811 outerThirdRect.shiftYEdgeTo(outerThirdRect.y() + outerWidth); 1812 } else if (side == BSBottom) { 1813 innerThirdRect.setHeight(innerThirdRect.height() - innerWidth); 1814 outerThirdRect.setHeight(outerThirdRect.height() - outerWidth); 1815 } else if (side == BSLeft) { 1816 innerThirdRect.shiftXEdgeTo(innerThirdRect.x() + innerWidth); 1817 outerThirdRect.shiftXEdgeTo(outerThirdRect.x() + outerWidth); 1818 } else { 1819 innerThirdRect.setWidth(innerThirdRect.width() - innerWidth); 1820 outerThirdRect.setWidth(outerThirdRect.width() - outerWidth); 1821 } 1822 } 1823 1824 FloatRoundedRect pixelSnappedOuterThird = outerBorder.pixelSnappedRoundedRectForPainting(deviceScaleFactor); 1825 pixelSnappedOuterThird.setRect(pixelSnappedForPainting(outerThirdRect, deviceScaleFactor)); 1826 1827 if (pixelSnappedOuterThird.isRounded() && bleedAvoidance != BackgroundBleedUseTransparencyLayer) 1828 path.addRoundedRect(pixelSnappedOuterThird); 1829 else 1830 path.addRect(pixelSnappedOuterThird.rect()); 1831 1832 FloatRoundedRect pixelSnappedInnerThird = innerBorder.pixelSnappedRoundedRectForPainting(deviceScaleFactor); 1833 pixelSnappedInnerThird.setRect(pixelSnappedForPainting(innerThirdRect, deviceScaleFactor)); 1834 if (pixelSnappedInnerThird.isRounded() && bleedAvoidance != BackgroundBleedUseTransparencyLayer) 1835 path.addRoundedRect(pixelSnappedInnerThird); 1836 else 1837 path.addRect(pixelSnappedInnerThird.rect()); 1838 } 1839 1840 FloatRoundedRect pixelSnappedInnerBorder = innerBorder.pixelSnappedRoundedRectForPainting(deviceScaleFactor); 1841 if (pixelSnappedInnerBorder.isRounded()) 1842 path.addRoundedRect(pixelSnappedInnerBorder); 1843 else 1844 path.addRect(pixelSnappedInnerBorder.rect()); 1845 1846 graphicsContext->setFillRule(RULE_EVENODD); 1847 graphicsContext->setFillColor(edges[firstVisibleEdge].color(), style.colorSpace()); 1848 graphicsContext->fillPath(path); 1849 return; 1850 } 1851 // Avoid creating transparent layers 1852 if (haveAllSolidEdges && numEdgesVisible != 4 && !outerBorder.isRounded() && haveAlphaColor) { 1853 Path path; 1854 1855 for (int i = BSTop; i <= BSLeft; ++i) { 1856 const BorderEdge& currEdge = edges[i]; 1857 if (currEdge.shouldRender()) { 1858 LayoutRect sideRect = calculateSideRect(outerBorder, edges, i); 1859 path.addRect(sideRect); 1860 } 1861 } 1862 1863 graphicsContext->setFillRule(RULE_NONZERO); 1864 graphicsContext->setFillColor(edges[firstVisibleEdge].color(), style.colorSpace()); 1865 graphicsContext->fillPath(path); 1866 return; 1867 } 1868 } 1869 1870 bool clipToOuterBorder = outerBorder.isRounded(); 1871 GraphicsContextStateSaver stateSaver(*graphicsContext, clipToOuterBorder); 1872 if (clipToOuterBorder) { 1873 // Clip to the inner and outer radii rects. 1874 if (bleedAvoidance != BackgroundBleedUseTransparencyLayer) 1875 graphicsContext->clipRoundedRect(outerBorder.pixelSnappedRoundedRectForPainting(deviceScaleFactor)); 1876 // isRenderable() check avoids issue described in https://bugs.webkit.org/show_bug.cgi?id=38787 1877 // The inside will be clipped out later (in clipBorderSideForComplexInnerPath) 1878 if (innerBorder.isRenderable()) 1879 graphicsContext->clipOutRoundedRect(innerBorder.pixelSnappedRoundedRectForPainting(deviceScaleFactor)); 1880 } 1881 1882 // If only one edge visible antialiasing doesn't create seams 1883 bool antialias = shouldAntialiasLines(graphicsContext) || numEdgesVisible == 1; 1884 RoundedRect unadjustedInnerBorder = (bleedAvoidance == BackgroundBleedBackgroundOverBorder) ? style.getRoundedInnerBorderFor(rect, includeLogicalLeftEdge, includeLogicalRightEdge) : innerBorder; 1885 IntPoint innerBorderAdjustment(innerBorder.rect().x() - unadjustedInnerBorder.rect().x(), innerBorder.rect().y() - unadjustedInnerBorder.rect().y()); 1886 if (haveAlphaColor) 1887 paintTranslucentBorderSides(graphicsContext, style, outerBorder, unadjustedInnerBorder, innerBorderAdjustment, edges, edgesToDraw, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias); 1888 else 1889 paintBorderSides(graphicsContext, style, outerBorder, unadjustedInnerBorder, innerBorderAdjustment, edges, edgesToDraw, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge, antialias); 1890} 1891 1892void RenderBoxModelObject::drawBoxSideFromPath(GraphicsContext* graphicsContext, const LayoutRect& borderRect, const Path& borderPath, const BorderEdge edges[], 1893 float thickness, float drawThickness, BoxSide side, const RenderStyle& style, Color color, EBorderStyle borderStyle, BackgroundBleedAvoidance bleedAvoidance, 1894 bool includeLogicalLeftEdge, bool includeLogicalRightEdge) 1895{ 1896 if (thickness <= 0) 1897 return; 1898 1899 if (borderStyle == DOUBLE && thickness < 3) 1900 borderStyle = SOLID; 1901 1902 switch (borderStyle) { 1903 case BNONE: 1904 case BHIDDEN: 1905 return; 1906 case DOTTED: 1907 case DASHED: { 1908 graphicsContext->setStrokeColor(color, style.colorSpace()); 1909 1910 // The stroke is doubled here because the provided path is the 1911 // outside edge of the border so half the stroke is clipped off. 1912 // The extra multiplier is so that the clipping mask can antialias 1913 // the edges to prevent jaggies. 1914 graphicsContext->setStrokeThickness(drawThickness * 2 * 1.1f); 1915 graphicsContext->setStrokeStyle(borderStyle == DASHED ? DashedStroke : DottedStroke); 1916 1917 // If the number of dashes that fit in the path is odd and non-integral then we 1918 // will have an awkwardly-sized dash at the end of the path. To try to avoid that 1919 // here, we simply make the whitespace dashes ever so slightly bigger. 1920 // FIXME: This could be even better if we tried to manipulate the dash offset 1921 // and possibly the gapLength to get the corners dash-symmetrical. 1922 float dashLength = thickness * ((borderStyle == DASHED) ? 3.0f : 1.0f); 1923 float gapLength = dashLength; 1924 float numberOfDashes = borderPath.length() / dashLength; 1925 // Don't try to show dashes if we have less than 2 dashes + 2 gaps. 1926 // FIXME: should do this test per side. 1927 if (numberOfDashes >= 4) { 1928 bool evenNumberOfFullDashes = !((int)numberOfDashes % 2); 1929 bool integralNumberOfDashes = !(numberOfDashes - (int)numberOfDashes); 1930 if (!evenNumberOfFullDashes && !integralNumberOfDashes) { 1931 float numberOfGaps = numberOfDashes / 2; 1932 gapLength += (dashLength / numberOfGaps); 1933 } 1934 1935 DashArray lineDash; 1936 lineDash.append(dashLength); 1937 lineDash.append(gapLength); 1938 graphicsContext->setLineDash(lineDash, dashLength); 1939 } 1940 1941 // FIXME: stroking the border path causes issues with tight corners: 1942 // https://bugs.webkit.org/show_bug.cgi?id=58711 1943 // Also, to get the best appearance we should stroke a path between the two borders. 1944 graphicsContext->strokePath(borderPath); 1945 return; 1946 } 1947 case DOUBLE: { 1948 // Get the inner border rects for both the outer border line and the inner border line 1949 LayoutUnit outerBorderTopWidth; 1950 LayoutUnit innerBorderTopWidth; 1951 edges[BSTop].getDoubleBorderStripeWidths(outerBorderTopWidth, innerBorderTopWidth); 1952 1953 LayoutUnit outerBorderRightWidth; 1954 LayoutUnit innerBorderRightWidth; 1955 edges[BSRight].getDoubleBorderStripeWidths(outerBorderRightWidth, innerBorderRightWidth); 1956 1957 LayoutUnit outerBorderBottomWidth; 1958 LayoutUnit innerBorderBottomWidth; 1959 edges[BSBottom].getDoubleBorderStripeWidths(outerBorderBottomWidth, innerBorderBottomWidth); 1960 1961 LayoutUnit outerBorderLeftWidth; 1962 LayoutUnit innerBorderLeftWidth; 1963 edges[BSLeft].getDoubleBorderStripeWidths(outerBorderLeftWidth, innerBorderLeftWidth); 1964 1965 // Draw inner border line 1966 { 1967 GraphicsContextStateSaver stateSaver(*graphicsContext); 1968 RoundedRect innerClip = style.getRoundedInnerBorderFor(borderRect, 1969 innerBorderTopWidth, innerBorderBottomWidth, innerBorderLeftWidth, innerBorderRightWidth, 1970 includeLogicalLeftEdge, includeLogicalRightEdge); 1971 1972 graphicsContext->clipRoundedRect(FloatRoundedRect(innerClip)); 1973 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, SOLID, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge); 1974 } 1975 1976 // Draw outer border line 1977 { 1978 GraphicsContextStateSaver stateSaver(*graphicsContext); 1979 LayoutRect outerRect = borderRect; 1980 if (bleedAvoidance == BackgroundBleedUseTransparencyLayer) { 1981 outerRect.inflate(1); 1982 ++outerBorderTopWidth; 1983 ++outerBorderBottomWidth; 1984 ++outerBorderLeftWidth; 1985 ++outerBorderRightWidth; 1986 } 1987 1988 RoundedRect outerClip = style.getRoundedInnerBorderFor(outerRect, 1989 outerBorderTopWidth, outerBorderBottomWidth, outerBorderLeftWidth, outerBorderRightWidth, 1990 includeLogicalLeftEdge, includeLogicalRightEdge); 1991 graphicsContext->clipOutRoundedRect(FloatRoundedRect(outerClip)); 1992 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, SOLID, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge); 1993 } 1994 return; 1995 } 1996 case RIDGE: 1997 case GROOVE: 1998 { 1999 EBorderStyle s1; 2000 EBorderStyle s2; 2001 if (borderStyle == GROOVE) { 2002 s1 = INSET; 2003 s2 = OUTSET; 2004 } else { 2005 s1 = OUTSET; 2006 s2 = INSET; 2007 } 2008 2009 // Paint full border 2010 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, s1, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge); 2011 2012 // Paint inner only 2013 GraphicsContextStateSaver stateSaver(*graphicsContext); 2014 LayoutUnit topWidth = edges[BSTop].widthForPainting() / 2; 2015 LayoutUnit bottomWidth = edges[BSBottom].widthForPainting() / 2; 2016 LayoutUnit leftWidth = edges[BSLeft].widthForPainting() / 2; 2017 LayoutUnit rightWidth = edges[BSRight].widthForPainting() / 2; 2018 2019 RoundedRect clipRect = style.getRoundedInnerBorderFor(borderRect, 2020 topWidth, bottomWidth, leftWidth, rightWidth, 2021 includeLogicalLeftEdge, includeLogicalRightEdge); 2022 2023 graphicsContext->clipRoundedRect(FloatRoundedRect(clipRect)); 2024 drawBoxSideFromPath(graphicsContext, borderRect, borderPath, edges, thickness, drawThickness, side, style, color, s2, bleedAvoidance, includeLogicalLeftEdge, includeLogicalRightEdge); 2025 return; 2026 } 2027 case INSET: 2028 if (side == BSTop || side == BSLeft) 2029 color = color.dark(); 2030 break; 2031 case OUTSET: 2032 if (side == BSBottom || side == BSRight) 2033 color = color.dark(); 2034 break; 2035 default: 2036 break; 2037 } 2038 2039 graphicsContext->setStrokeStyle(NoStroke); 2040 graphicsContext->setFillColor(color, style.colorSpace()); 2041 graphicsContext->drawRect(pixelSnappedForPainting(borderRect, document().deviceScaleFactor())); 2042} 2043 2044static void findInnerVertex(const FloatPoint& outerCorner, const FloatPoint& innerCorner, const FloatPoint& centerPoint, FloatPoint& result) 2045{ 2046 // If the line between outer and inner corner is towards the horizontal, intersect with a vertical line through the center, 2047 // otherwise with a horizontal line through the center. The points that form this line are arbitrary (we use 0, 100). 2048 // Note that if findIntersection fails, it will leave result untouched. 2049 float diffInnerOuterX = fabs(innerCorner.x() - outerCorner.x()); 2050 float diffInnerOuterY = fabs(innerCorner.y() - outerCorner.y()); 2051 float diffCenterOuterX = fabs(centerPoint.x() - outerCorner.x()); 2052 float diffCenterOuterY = fabs(centerPoint.y() - outerCorner.y()); 2053 if (diffInnerOuterY * diffCenterOuterX < diffCenterOuterY * diffInnerOuterX) 2054 findIntersection(outerCorner, innerCorner, FloatPoint(centerPoint.x(), 0), FloatPoint(centerPoint.x(), 100), result); 2055 else 2056 findIntersection(outerCorner, innerCorner, FloatPoint(0, centerPoint.y()), FloatPoint(100, centerPoint.y()), result); 2057} 2058 2059void RenderBoxModelObject::clipBorderSidePolygon(GraphicsContext* graphicsContext, const RoundedRect& outerBorder, const RoundedRect& innerBorder, 2060 BoxSide side, bool firstEdgeMatches, bool secondEdgeMatches) 2061{ 2062 FloatPoint quad[4]; 2063 2064 const LayoutRect& outerRect = outerBorder.rect(); 2065 const LayoutRect& innerRect = innerBorder.rect(); 2066 2067 FloatPoint centerPoint(innerRect.location().x() + static_cast<float>(innerRect.width()) / 2, innerRect.location().y() + static_cast<float>(innerRect.height()) / 2); 2068 2069 // For each side, create a quad that encompasses all parts of that side that may draw, 2070 // including areas inside the innerBorder. 2071 // 2072 // 0----------------3 2073 // 0 \ / 0 2074 // |\ 1----------- 2 /| 2075 // | 1 1 | 2076 // | | | | 2077 // | | | | 2078 // | 2 2 | 2079 // |/ 1------------2 \| 2080 // 3 / \ 3 2081 // 0----------------3 2082 // 2083 switch (side) { 2084 case BSTop: 2085 quad[0] = outerRect.minXMinYCorner(); 2086 quad[1] = innerRect.minXMinYCorner(); 2087 quad[2] = innerRect.maxXMinYCorner(); 2088 quad[3] = outerRect.maxXMinYCorner(); 2089 2090 if (!innerBorder.radii().topLeft().isZero()) 2091 findInnerVertex(outerRect.minXMinYCorner(), innerRect.minXMinYCorner(), centerPoint, quad[1]); 2092 2093 if (!innerBorder.radii().topRight().isZero()) 2094 findInnerVertex(outerRect.maxXMinYCorner(), innerRect.maxXMinYCorner(), centerPoint, quad[2]); 2095 break; 2096 2097 case BSLeft: 2098 quad[0] = outerRect.minXMinYCorner(); 2099 quad[1] = innerRect.minXMinYCorner(); 2100 quad[2] = innerRect.minXMaxYCorner(); 2101 quad[3] = outerRect.minXMaxYCorner(); 2102 2103 if (!innerBorder.radii().topLeft().isZero()) 2104 findInnerVertex(outerRect.minXMinYCorner(), innerRect.minXMinYCorner(), centerPoint, quad[1]); 2105 2106 if (!innerBorder.radii().bottomLeft().isZero()) 2107 findInnerVertex(outerRect.minXMaxYCorner(), innerRect.minXMaxYCorner(), centerPoint, quad[2]); 2108 break; 2109 2110 case BSBottom: 2111 quad[0] = outerRect.minXMaxYCorner(); 2112 quad[1] = innerRect.minXMaxYCorner(); 2113 quad[2] = innerRect.maxXMaxYCorner(); 2114 quad[3] = outerRect.maxXMaxYCorner(); 2115 2116 if (!innerBorder.radii().bottomLeft().isZero()) 2117 findInnerVertex(outerRect.minXMaxYCorner(), innerRect.minXMaxYCorner(), centerPoint, quad[1]); 2118 2119 if (!innerBorder.radii().bottomRight().isZero()) 2120 findInnerVertex(outerRect.maxXMaxYCorner(), innerRect.maxXMaxYCorner(), centerPoint, quad[2]); 2121 break; 2122 2123 case BSRight: 2124 quad[0] = outerRect.maxXMinYCorner(); 2125 quad[1] = innerRect.maxXMinYCorner(); 2126 quad[2] = innerRect.maxXMaxYCorner(); 2127 quad[3] = outerRect.maxXMaxYCorner(); 2128 2129 if (!innerBorder.radii().topRight().isZero()) 2130 findInnerVertex(outerRect.maxXMinYCorner(), innerRect.maxXMinYCorner(), centerPoint, quad[1]); 2131 2132 if (!innerBorder.radii().bottomRight().isZero()) 2133 findInnerVertex(outerRect.maxXMaxYCorner(), innerRect.maxXMaxYCorner(), centerPoint, quad[2]); 2134 break; 2135 } 2136 2137 // If the border matches both of its adjacent sides, don't anti-alias the clip, and 2138 // if neither side matches, anti-alias the clip. 2139 if (firstEdgeMatches == secondEdgeMatches) { 2140 graphicsContext->clipConvexPolygon(4, quad, !firstEdgeMatches); 2141 return; 2142 } 2143 2144 // Square off the end which shouldn't be affected by antialiasing, and clip. 2145 FloatPoint firstQuad[4]; 2146 firstQuad[0] = quad[0]; 2147 firstQuad[1] = quad[1]; 2148 firstQuad[2] = side == BSTop || side == BSBottom ? FloatPoint(quad[3].x(), quad[2].y()) : FloatPoint(quad[2].x(), quad[3].y()); 2149 firstQuad[3] = quad[3]; 2150 graphicsContext->clipConvexPolygon(4, firstQuad, !firstEdgeMatches); 2151 2152 FloatPoint secondQuad[4]; 2153 secondQuad[0] = quad[0]; 2154 secondQuad[1] = side == BSTop || side == BSBottom ? FloatPoint(quad[0].x(), quad[1].y()) : FloatPoint(quad[1].x(), quad[0].y()); 2155 secondQuad[2] = quad[2]; 2156 secondQuad[3] = quad[3]; 2157 // Antialiasing affects the second side. 2158 graphicsContext->clipConvexPolygon(4, secondQuad, !secondEdgeMatches); 2159} 2160 2161static LayoutRect calculateSideRectIncludingInner(const RoundedRect& outerBorder, const BorderEdge edges[], BoxSide side) 2162{ 2163 LayoutRect sideRect = outerBorder.rect(); 2164 LayoutUnit width; 2165 2166 switch (side) { 2167 case BSTop: 2168 width = sideRect.height() - edges[BSBottom].widthForPainting(); 2169 sideRect.setHeight(width); 2170 break; 2171 case BSBottom: 2172 width = sideRect.height() - edges[BSTop].widthForPainting(); 2173 sideRect.shiftYEdgeTo(sideRect.maxY() - width); 2174 break; 2175 case BSLeft: 2176 width = sideRect.width() - edges[BSRight].widthForPainting(); 2177 sideRect.setWidth(width); 2178 break; 2179 case BSRight: 2180 width = sideRect.width() - edges[BSLeft].widthForPainting(); 2181 sideRect.shiftXEdgeTo(sideRect.maxX() - width); 2182 break; 2183 } 2184 2185 return sideRect; 2186} 2187 2188static RoundedRect calculateAdjustedInnerBorder(const RoundedRect&innerBorder, BoxSide side) 2189{ 2190 // Expand the inner border as necessary to make it a rounded rect (i.e. radii contained within each edge). 2191 // This function relies on the fact we only get radii not contained within each edge if one of the radii 2192 // for an edge is zero, so we can shift the arc towards the zero radius corner. 2193 RoundedRect::Radii newRadii = innerBorder.radii(); 2194 LayoutRect newRect = innerBorder.rect(); 2195 2196 float overshoot; 2197 float maxRadii; 2198 2199 switch (side) { 2200 case BSTop: 2201 overshoot = newRadii.topLeft().width() + newRadii.topRight().width() - newRect.width(); 2202 if (overshoot > 0) { 2203 ASSERT(!(newRadii.topLeft().width() && newRadii.topRight().width())); 2204 newRect.setWidth(newRect.width() + overshoot); 2205 if (!newRadii.topLeft().width()) 2206 newRect.move(-overshoot, 0); 2207 } 2208 newRadii.setBottomLeft(IntSize(0, 0)); 2209 newRadii.setBottomRight(IntSize(0, 0)); 2210 maxRadii = std::max(newRadii.topLeft().height(), newRadii.topRight().height()); 2211 if (maxRadii > newRect.height()) 2212 newRect.setHeight(maxRadii); 2213 break; 2214 2215 case BSBottom: 2216 overshoot = newRadii.bottomLeft().width() + newRadii.bottomRight().width() - newRect.width(); 2217 if (overshoot > 0) { 2218 ASSERT(!(newRadii.bottomLeft().width() && newRadii.bottomRight().width())); 2219 newRect.setWidth(newRect.width() + overshoot); 2220 if (!newRadii.bottomLeft().width()) 2221 newRect.move(-overshoot, 0); 2222 } 2223 newRadii.setTopLeft(IntSize(0, 0)); 2224 newRadii.setTopRight(IntSize(0, 0)); 2225 maxRadii = std::max(newRadii.bottomLeft().height(), newRadii.bottomRight().height()); 2226 if (maxRadii > newRect.height()) { 2227 newRect.move(0, newRect.height() - maxRadii); 2228 newRect.setHeight(maxRadii); 2229 } 2230 break; 2231 2232 case BSLeft: 2233 overshoot = newRadii.topLeft().height() + newRadii.bottomLeft().height() - newRect.height(); 2234 if (overshoot > 0) { 2235 ASSERT(!(newRadii.topLeft().height() && newRadii.bottomLeft().height())); 2236 newRect.setHeight(newRect.height() + overshoot); 2237 if (!newRadii.topLeft().height()) 2238 newRect.move(0, -overshoot); 2239 } 2240 newRadii.setTopRight(IntSize(0, 0)); 2241 newRadii.setBottomRight(IntSize(0, 0)); 2242 maxRadii = std::max(newRadii.topLeft().width(), newRadii.bottomLeft().width()); 2243 if (maxRadii > newRect.width()) 2244 newRect.setWidth(maxRadii); 2245 break; 2246 2247 case BSRight: 2248 overshoot = newRadii.topRight().height() + newRadii.bottomRight().height() - newRect.height(); 2249 if (overshoot > 0) { 2250 ASSERT(!(newRadii.topRight().height() && newRadii.bottomRight().height())); 2251 newRect.setHeight(newRect.height() + overshoot); 2252 if (!newRadii.topRight().height()) 2253 newRect.move(0, -overshoot); 2254 } 2255 newRadii.setTopLeft(IntSize(0, 0)); 2256 newRadii.setBottomLeft(IntSize(0, 0)); 2257 maxRadii = std::max(newRadii.topRight().width(), newRadii.bottomRight().width()); 2258 if (maxRadii > newRect.width()) { 2259 newRect.move(newRect.width() - maxRadii, 0); 2260 newRect.setWidth(maxRadii); 2261 } 2262 break; 2263 } 2264 2265 return RoundedRect(newRect, newRadii); 2266} 2267 2268void RenderBoxModelObject::clipBorderSideForComplexInnerPath(GraphicsContext* graphicsContext, const RoundedRect& outerBorder, const RoundedRect& innerBorder, 2269 BoxSide side, const class BorderEdge edges[]) 2270{ 2271 graphicsContext->clip(calculateSideRectIncludingInner(outerBorder, edges, side)); 2272 graphicsContext->clipOutRoundedRect(FloatRoundedRect(calculateAdjustedInnerBorder(innerBorder, side))); 2273} 2274 2275bool RenderBoxModelObject::borderObscuresBackgroundEdge(const FloatSize& contextScale) const 2276{ 2277 BorderEdge edges[4]; 2278 BorderEdge::getBorderEdgeInfo(edges, style(), document().deviceScaleFactor()); 2279 2280 for (int i = BSTop; i <= BSLeft; ++i) { 2281 const BorderEdge& currEdge = edges[i]; 2282 // FIXME: for vertical text 2283 float axisScale = (i == BSTop || i == BSBottom) ? contextScale.height() : contextScale.width(); 2284 if (!currEdge.obscuresBackgroundEdge(axisScale)) 2285 return false; 2286 } 2287 2288 return true; 2289} 2290 2291bool RenderBoxModelObject::borderObscuresBackground() const 2292{ 2293 if (!style().hasBorder()) 2294 return false; 2295 2296 // Bail if we have any border-image for now. We could look at the image alpha to improve this. 2297 if (style().borderImage().image()) 2298 return false; 2299 2300 BorderEdge edges[4]; 2301 BorderEdge::getBorderEdgeInfo(edges, style(), document().deviceScaleFactor()); 2302 2303 for (int i = BSTop; i <= BSLeft; ++i) { 2304 const BorderEdge& currEdge = edges[i]; 2305 if (!currEdge.obscuresBackground()) 2306 return false; 2307 } 2308 2309 return true; 2310} 2311 2312bool RenderBoxModelObject::boxShadowShouldBeAppliedToBackground(BackgroundBleedAvoidance bleedAvoidance, InlineFlowBox* inlineFlowBox) const 2313{ 2314 if (bleedAvoidance != BackgroundBleedNone) 2315 return false; 2316 2317 if (style().hasAppearance()) 2318 return false; 2319 2320 bool hasOneNormalBoxShadow = false; 2321 for (const ShadowData* currentShadow = style().boxShadow(); currentShadow; currentShadow = currentShadow->next()) { 2322 if (currentShadow->style() != Normal) 2323 continue; 2324 2325 if (hasOneNormalBoxShadow) 2326 return false; 2327 hasOneNormalBoxShadow = true; 2328 2329 if (currentShadow->spread()) 2330 return false; 2331 } 2332 2333 if (!hasOneNormalBoxShadow) 2334 return false; 2335 2336 Color backgroundColor = style().visitedDependentColor(CSSPropertyBackgroundColor); 2337 if (!backgroundColor.isValid() || backgroundColor.hasAlpha()) 2338 return false; 2339 2340 const FillLayer* lastBackgroundLayer = style().backgroundLayers(); 2341 for (const FillLayer* next = lastBackgroundLayer->next(); next; next = lastBackgroundLayer->next()) 2342 lastBackgroundLayer = next; 2343 2344 if (lastBackgroundLayer->clip() != BorderFillBox) 2345 return false; 2346 2347 if (lastBackgroundLayer->image() && style().hasBorderRadius()) 2348 return false; 2349 2350 if (inlineFlowBox && !inlineFlowBox->boxShadowCanBeAppliedToBackground(*lastBackgroundLayer)) 2351 return false; 2352 2353 if (hasOverflowClip() && lastBackgroundLayer->attachment() == LocalBackgroundAttachment) 2354 return false; 2355 2356 return true; 2357} 2358 2359static inline LayoutRect areaCastingShadowInHole(const LayoutRect& holeRect, int shadowExtent, int shadowSpread, const IntSize& shadowOffset) 2360{ 2361 LayoutRect bounds(holeRect); 2362 2363 bounds.inflate(shadowExtent); 2364 2365 if (shadowSpread < 0) 2366 bounds.inflate(-shadowSpread); 2367 2368 LayoutRect offsetBounds = bounds; 2369 offsetBounds.move(-shadowOffset); 2370 return unionRect(bounds, offsetBounds); 2371} 2372 2373void RenderBoxModelObject::paintBoxShadow(const PaintInfo& info, const LayoutRect& paintRect, const RenderStyle& style, ShadowStyle shadowStyle, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) 2374{ 2375 // FIXME: Deal with border-image. Would be great to use border-image as a mask. 2376 GraphicsContext* context = info.context; 2377 if (context->paintingDisabled() || !style.boxShadow()) 2378 return; 2379 2380 RoundedRect border = (shadowStyle == Inset) ? style.getRoundedInnerBorderFor(paintRect, includeLogicalLeftEdge, includeLogicalRightEdge) 2381 : style.getRoundedBorderFor(paintRect, includeLogicalLeftEdge, includeLogicalRightEdge); 2382 2383 bool hasBorderRadius = style.hasBorderRadius(); 2384 bool isHorizontal = style.isHorizontalWritingMode(); 2385 float deviceScaleFactor = document().deviceScaleFactor(); 2386 2387 bool hasOpaqueBackground = style.visitedDependentColor(CSSPropertyBackgroundColor).isValid() && style.visitedDependentColor(CSSPropertyBackgroundColor).alpha() == 255; 2388 for (const ShadowData* shadow = style.boxShadow(); shadow; shadow = shadow->next()) { 2389 if (shadow->style() != shadowStyle) 2390 continue; 2391 2392 // FIXME: Add subpixel support for the shadow values. Soon after the shadow offset becomes fractional, 2393 // all the early snappings here need to be pushed to the actual painting operations. 2394 IntSize shadowOffset(shadow->x(), shadow->y()); 2395 int shadowRadius = shadow->radius(); 2396 int shadowPaintingExtent = shadow->paintingExtent(); 2397 int shadowSpread = shadow->spread(); 2398 2399 if (shadowOffset.isZero() && !shadowRadius && !shadowSpread) 2400 continue; 2401 2402 const Color& shadowColor = shadow->color(); 2403 2404 if (shadow->style() == Normal) { 2405 RoundedRect fillRect = border; 2406 fillRect.inflate(shadowSpread); 2407 if (fillRect.isEmpty()) 2408 continue; 2409 2410 FloatRect pixelSnappedShadowRect = pixelSnappedForPainting(border.rect(), deviceScaleFactor); 2411 pixelSnappedShadowRect.inflate(shadowPaintingExtent + shadowSpread); 2412 pixelSnappedShadowRect.move(shadowOffset); 2413 2414 GraphicsContextStateSaver stateSaver(*context); 2415 context->clip(pixelSnappedShadowRect); 2416 2417 // Move the fill just outside the clip, adding 1 pixel separation so that the fill does not 2418 // bleed in (due to antialiasing) if the context is transformed. 2419 IntSize extraOffset(roundToInt(paintRect.width()) + std::max(0, shadowOffset.width()) + shadowPaintingExtent + 2 * shadowSpread + 1, 0); 2420 shadowOffset -= extraOffset; 2421 fillRect.move(extraOffset); 2422 2423 if (shadow->isWebkitBoxShadow()) 2424 context->setLegacyShadow(shadowOffset, shadowRadius, shadowColor, style.colorSpace()); 2425 else 2426 context->setShadow(shadowOffset, shadowRadius, shadowColor, style.colorSpace()); 2427 2428 FloatRoundedRect rectToClipOut = border.pixelSnappedRoundedRectForPainting(deviceScaleFactor); 2429 FloatRoundedRect pixelSnappedFillRect = fillRect.pixelSnappedRoundedRectForPainting(deviceScaleFactor); 2430 if (hasBorderRadius) { 2431 // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time 2432 // when painting the shadow. On the other hand, it introduces subpixel gaps along the 2433 // corners. Those are avoided by insetting the clipping path by one pixel. 2434 if (hasOpaqueBackground) 2435 rectToClipOut.inflateWithRadii(LayoutUnit::fromPixel(-1)); 2436 2437 if (!rectToClipOut.isEmpty()) 2438 context->clipOutRoundedRect(rectToClipOut); 2439 2440 RoundedRect influenceRect(LayoutRect(pixelSnappedShadowRect), border.radii()); 2441 influenceRect.expandRadii(2 * shadowPaintingExtent + shadowSpread); 2442 2443 if (allCornersClippedOut(influenceRect, info.rect)) 2444 context->fillRect(pixelSnappedFillRect.rect(), Color::black, style.colorSpace()); 2445 else { 2446 pixelSnappedFillRect.expandRadii(shadowSpread); 2447 if (!pixelSnappedFillRect.isRenderable()) 2448 pixelSnappedFillRect.adjustRadii(); 2449 context->fillRoundedRect(pixelSnappedFillRect, Color::black, style.colorSpace()); 2450 } 2451 } else { 2452 // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time 2453 // when painting the shadow. On the other hand, it introduces subpixel gaps along the 2454 // edges if they are not pixel-aligned. Those are avoided by insetting the clipping path 2455 // by one pixel. 2456 if (hasOpaqueBackground) { 2457 // FIXME: The function to decide on the policy based on the transform should be a named function. 2458 // FIXME: It's not clear if this check is right. What about integral scale factors? 2459 AffineTransform transform = context->getCTM(); 2460 if (transform.a() != 1 || (transform.d() != 1 && transform.d() != -1) || transform.b() || transform.c()) 2461 rectToClipOut.inflate(LayoutUnit::fromPixel(-1).toFloat()); 2462 } 2463 2464 if (!rectToClipOut.isEmpty()) 2465 context->clipOut(rectToClipOut.rect()); 2466 context->fillRect(pixelSnappedFillRect.rect(), Color::black, style.colorSpace()); 2467 } 2468 } else { 2469 // Inset shadow. 2470 FloatRoundedRect pixelSnappedBorderRect = border.pixelSnappedRoundedRectForPainting(deviceScaleFactor); 2471 FloatRect pixelSnappedHoleRect = pixelSnappedBorderRect.rect(); 2472 pixelSnappedHoleRect.inflate(-shadowSpread); 2473 2474 if (pixelSnappedHoleRect.isEmpty()) { 2475 if (hasBorderRadius) 2476 context->fillRoundedRect(pixelSnappedBorderRect, shadowColor, style.colorSpace()); 2477 else 2478 context->fillRect(pixelSnappedBorderRect.rect(), shadowColor, style.colorSpace()); 2479 continue; 2480 } 2481 2482 if (!includeLogicalLeftEdge) { 2483 if (isHorizontal) { 2484 pixelSnappedHoleRect.move(-std::max(shadowOffset.width(), 0) - shadowPaintingExtent, 0); 2485 pixelSnappedHoleRect.setWidth(pixelSnappedHoleRect.width() + std::max(shadowOffset.width(), 0) + shadowPaintingExtent); 2486 } else { 2487 pixelSnappedHoleRect.move(0, -std::max(shadowOffset.height(), 0) - shadowPaintingExtent); 2488 pixelSnappedHoleRect.setHeight(pixelSnappedHoleRect.height() + std::max(shadowOffset.height(), 0) + shadowPaintingExtent); 2489 } 2490 } 2491 if (!includeLogicalRightEdge) { 2492 if (isHorizontal) 2493 pixelSnappedHoleRect.setWidth(pixelSnappedHoleRect.width() - std::min(shadowOffset.width(), 0) + shadowPaintingExtent); 2494 else 2495 pixelSnappedHoleRect.setHeight(pixelSnappedHoleRect.height() - std::min(shadowOffset.height(), 0) + shadowPaintingExtent); 2496 } 2497 2498 Color fillColor(shadowColor.red(), shadowColor.green(), shadowColor.blue(), 255); 2499 2500 FloatRect pixelSnappedOuterRect = pixelSnappedForPainting(areaCastingShadowInHole(LayoutRect(pixelSnappedBorderRect.rect()), shadowPaintingExtent, shadowSpread, shadowOffset), deviceScaleFactor); 2501 FloatRoundedRect pixelSnappedRoundedHole = FloatRoundedRect(pixelSnappedHoleRect, pixelSnappedBorderRect.radii()); 2502 2503 GraphicsContextStateSaver stateSaver(*context); 2504 if (hasBorderRadius) { 2505 Path path; 2506 path.addRoundedRect(pixelSnappedBorderRect); 2507 context->clip(path); 2508 pixelSnappedRoundedHole.shrinkRadii(shadowSpread); 2509 } else 2510 context->clip(pixelSnappedBorderRect.rect()); 2511 2512 IntSize extraOffset(2 * roundToInt(paintRect.width()) + std::max(0, shadowOffset.width()) + shadowPaintingExtent - 2 * shadowSpread + 1, 0); 2513 context->translate(extraOffset.width(), extraOffset.height()); 2514 shadowOffset -= extraOffset; 2515 2516 if (shadow->isWebkitBoxShadow()) 2517 context->setLegacyShadow(shadowOffset, shadowRadius, shadowColor, style.colorSpace()); 2518 else 2519 context->setShadow(shadowOffset, shadowRadius, shadowColor, style.colorSpace()); 2520 2521 context->fillRectWithRoundedHole(pixelSnappedOuterRect, pixelSnappedRoundedHole, fillColor, style.colorSpace()); 2522 } 2523 } 2524} 2525 2526LayoutUnit RenderBoxModelObject::containingBlockLogicalWidthForContent() const 2527{ 2528 return containingBlock()->availableLogicalWidth(); 2529} 2530 2531RenderBoxModelObject* RenderBoxModelObject::continuation() const 2532{ 2533 if (!continuationMap) 2534 return 0; 2535 return continuationMap->get(this); 2536} 2537 2538void RenderBoxModelObject::setContinuation(RenderBoxModelObject* continuation) 2539{ 2540 if (continuation) { 2541 if (!continuationMap) 2542 continuationMap = new ContinuationMap; 2543 continuationMap->set(this, continuation); 2544 } else { 2545 if (continuationMap) 2546 continuationMap->remove(this); 2547 } 2548} 2549 2550RenderTextFragment* RenderBoxModelObject::firstLetterRemainingText() const 2551{ 2552 if (!firstLetterRemainingTextMap) 2553 return 0; 2554 return firstLetterRemainingTextMap->get(this); 2555} 2556 2557void RenderBoxModelObject::setFirstLetterRemainingText(RenderTextFragment* remainingText) 2558{ 2559 if (remainingText) { 2560 if (!firstLetterRemainingTextMap) 2561 firstLetterRemainingTextMap = new FirstLetterRemainingTextMap; 2562 firstLetterRemainingTextMap->set(this, remainingText); 2563 } else if (firstLetterRemainingTextMap) 2564 firstLetterRemainingTextMap->remove(this); 2565} 2566 2567LayoutRect RenderBoxModelObject::localCaretRectForEmptyElement(LayoutUnit width, LayoutUnit textIndentOffset) 2568{ 2569 ASSERT(!firstChild()); 2570 2571 // FIXME: This does not take into account either :first-line or :first-letter 2572 // However, as soon as some content is entered, the line boxes will be 2573 // constructed and this kludge is not called any more. So only the caret size 2574 // of an empty :first-line'd block is wrong. I think we can live with that. 2575 const RenderStyle& currentStyle = firstLineStyle(); 2576 LayoutUnit height = lineHeight(true, currentStyle.isHorizontalWritingMode() ? HorizontalLine : VerticalLine); 2577 2578 enum CaretAlignment { alignLeft, alignRight, alignCenter }; 2579 2580 CaretAlignment alignment = alignLeft; 2581 2582 switch (currentStyle.textAlign()) { 2583 case LEFT: 2584 case WEBKIT_LEFT: 2585 break; 2586 case CENTER: 2587 case WEBKIT_CENTER: 2588 alignment = alignCenter; 2589 break; 2590 case RIGHT: 2591 case WEBKIT_RIGHT: 2592 alignment = alignRight; 2593 break; 2594 case JUSTIFY: 2595 case TASTART: 2596 if (!currentStyle.isLeftToRightDirection()) 2597 alignment = alignRight; 2598 break; 2599 case TAEND: 2600 if (currentStyle.isLeftToRightDirection()) 2601 alignment = alignRight; 2602 break; 2603 } 2604 2605 LayoutUnit x = borderLeft() + paddingLeft(); 2606 LayoutUnit maxX = width - borderRight() - paddingRight(); 2607 2608 switch (alignment) { 2609 case alignLeft: 2610 if (currentStyle.isLeftToRightDirection()) 2611 x += textIndentOffset; 2612 break; 2613 case alignCenter: 2614 x = (x + maxX) / 2; 2615 if (currentStyle.isLeftToRightDirection()) 2616 x += textIndentOffset / 2; 2617 else 2618 x -= textIndentOffset / 2; 2619 break; 2620 case alignRight: 2621 x = maxX - caretWidth; 2622 if (!currentStyle.isLeftToRightDirection()) 2623 x -= textIndentOffset; 2624 break; 2625 } 2626 x = std::min(x, std::max<LayoutUnit>(maxX - caretWidth, 0)); 2627 2628 LayoutUnit y = paddingTop() + borderTop(); 2629 2630 return currentStyle.isHorizontalWritingMode() ? LayoutRect(x, y, caretWidth, height) : LayoutRect(y, x, height, caretWidth); 2631} 2632 2633bool RenderBoxModelObject::shouldAntialiasLines(GraphicsContext* context) 2634{ 2635 // FIXME: We may want to not antialias when scaled by an integral value, 2636 // and we may want to antialias when translated by a non-integral value. 2637 return !context->getCTM().isIdentityOrTranslationOrFlipped(); 2638} 2639 2640void RenderBoxModelObject::mapAbsoluteToLocalPoint(MapCoordinatesFlags mode, TransformState& transformState) const 2641{ 2642 auto o = container(); 2643 if (!o) 2644 return; 2645 2646 // FIXME: This code is wrong for named flow threads since it only works for content in the first region. 2647 // We also don't want to run it for multicolumn flow threads, since we can use our knowledge of column 2648 // geometry to actually get a better result. 2649 // The point inside a box that's inside a region has its coordinates relative to the region, 2650 // not the FlowThread that is its container in the RenderObject tree. 2651 if (isBox() && o->isOutOfFlowRenderFlowThread()) { 2652 RenderRegion* startRegion = nullptr; 2653 RenderRegion* endRegion = nullptr; 2654 if (toRenderFlowThread(o)->getRegionRangeForBox(toRenderBox(this), startRegion, endRegion)) 2655 o = startRegion; 2656 } 2657 2658 o->mapAbsoluteToLocalPoint(mode, transformState); 2659 2660 LayoutSize containerOffset = offsetFromContainer(o, LayoutPoint()); 2661 2662 bool preserve3D = mode & UseTransforms && (o->style().preserves3D() || style().preserves3D()); 2663 if (mode & UseTransforms && shouldUseTransformFromContainer(o)) { 2664 TransformationMatrix t; 2665 getTransformFromContainer(o, containerOffset, t); 2666 transformState.applyTransform(t, preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform); 2667 } else 2668 transformState.move(containerOffset.width(), containerOffset.height(), preserve3D ? TransformState::AccumulateTransform : TransformState::FlattenTransform); 2669} 2670 2671void RenderBoxModelObject::moveChildTo(RenderBoxModelObject* toBoxModelObject, RenderObject* child, RenderObject* beforeChild, bool fullRemoveInsert) 2672{ 2673 // We assume that callers have cleared their positioned objects list for child moves (!fullRemoveInsert) so the 2674 // positioned renderer maps don't become stale. It would be too slow to do the map lookup on each call. 2675 ASSERT(!fullRemoveInsert || !isRenderBlock() || !toRenderBlock(this)->hasPositionedObjects()); 2676 2677 ASSERT(this == child->parent()); 2678 ASSERT(!beforeChild || toBoxModelObject == beforeChild->parent()); 2679 if (fullRemoveInsert && (toBoxModelObject->isRenderBlock() || toBoxModelObject->isRenderInline())) { 2680 // Takes care of adding the new child correctly if toBlock and fromBlock 2681 // have different kind of children (block vs inline). 2682 removeChildInternal(*child, NotifyChildren); 2683 toBoxModelObject->addChild(child, beforeChild); 2684 } else { 2685 NotifyChildrenType notifyType = fullRemoveInsert ? NotifyChildren : DontNotifyChildren; 2686 removeChildInternal(*child, notifyType); 2687 toBoxModelObject->insertChildInternal(child, beforeChild, notifyType); 2688 } 2689} 2690 2691void RenderBoxModelObject::moveChildrenTo(RenderBoxModelObject* toBoxModelObject, RenderObject* startChild, RenderObject* endChild, RenderObject* beforeChild, bool fullRemoveInsert) 2692{ 2693 // This condition is rarely hit since this function is usually called on 2694 // anonymous blocks which can no longer carry positioned objects (see r120761) 2695 // or when fullRemoveInsert is false. 2696 if (fullRemoveInsert && isRenderBlock()) { 2697 toRenderBlock(this)->removePositionedObjects(0); 2698 if (isRenderBlockFlow()) 2699 toRenderBlockFlow(this)->removeFloatingObjects(); 2700 } 2701 2702 ASSERT(!beforeChild || toBoxModelObject == beforeChild->parent()); 2703 for (RenderObject* child = startChild; child && child != endChild; ) { 2704 // Save our next sibling as moveChildTo will clear it. 2705 RenderObject* nextSibling = child->nextSibling(); 2706 2707 // Check to make sure we're not saving the firstLetter as the nextSibling. 2708 // When the |child| object will be moved, its firstLetter will be recreated, 2709 // so saving it now in nextSibling would let us with a destroyed object. 2710 if (child->isText() && toRenderText(child)->isTextFragment() && nextSibling && nextSibling->isText()) { 2711 RenderObject* firstLetterObj = nullptr; 2712 if (RenderBlock* block = toRenderTextFragment(child)->blockForAccompanyingFirstLetter()) { 2713 RenderElement* firstLetterContainer = nullptr; 2714 block->getFirstLetter(firstLetterObj, firstLetterContainer, child); 2715 } 2716 2717 // This is the first letter, skip it. 2718 if (firstLetterObj == nextSibling) 2719 nextSibling = nextSibling->nextSibling(); 2720 } 2721 2722 moveChildTo(toBoxModelObject, child, beforeChild, fullRemoveInsert); 2723 child = nextSibling; 2724 } 2725} 2726 2727} // namespace WebCore 2728