1 /* 2 * Copyright (C) 2004, 2005, 2007 Nikolas Zimmermann <zimmermann (at) kde.org> 3 * Copyright (C) 2004, 2005, 2007, 2008, 2009 Rob Buis <buis (at) kde.org> 4 * Copyright (C) 2007 Eric Seidel <eric (at) webkit.org> 5 * Copyright (C) 2009 Google, Inc. 6 * Copyright (C) Research In Motion Limited 2011. All rights reserved. 7 * 8 * This library is free software; you can redistribute it and/or 9 * modify it under the terms of the GNU Library General Public 10 * License as published by the Free Software Foundation; either 11 * version 2 of the License, or (at your option) any later version. 12 * 13 * This library is distributed in the hope that it will be useful, 14 * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 16 * Library General Public License for more details. 17 * 18 * You should have received a copy of the GNU Library General Public License 19 * along with this library; see the file COPYING.LIB. If not, write to 20 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, 21 * Boston, MA 02110-1301, USA. 22 */ 23 24 #include "config.h" 25 26 #include "core/rendering/svg/RenderSVGRoot.h" 27 28 #include "core/page/Chrome.h" 29 #include "core/page/ChromeClient.h" 30 #include "core/page/Frame.h" 31 #include "core/page/Page.h" 32 #include "core/platform/graphics/GraphicsContext.h" 33 #include "core/rendering/HitTestResult.h" 34 #include "core/rendering/LayoutRepainter.h" 35 #include "core/rendering/RenderPart.h" 36 #include "core/rendering/RenderView.h" 37 #include "core/rendering/svg/RenderSVGResourceContainer.h" 38 #include "core/rendering/svg/SVGRenderingContext.h" 39 #include "core/rendering/svg/SVGResources.h" 40 #include "core/rendering/svg/SVGResourcesCache.h" 41 #include "core/svg/SVGElement.h" 42 #include "core/svg/SVGSVGElement.h" 43 44 using namespace std; 45 46 namespace WebCore { 47 48 RenderSVGRoot::RenderSVGRoot(SVGElement* node) 49 : RenderReplaced(node) 50 , m_objectBoundingBoxValid(false) 51 , m_isLayoutSizeChanged(false) 52 , m_needsBoundariesOrTransformUpdate(true) 53 { 54 } 55 56 RenderSVGRoot::~RenderSVGRoot() 57 { 58 } 59 60 void RenderSVGRoot::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio, bool& isPercentageIntrinsicSize) const 61 { 62 // Spec: http://www.w3.org/TR/SVG/coords.html#IntrinsicSizing 63 // SVG needs to specify how to calculate some intrinsic sizing properties to enable inclusion within other languages. 64 // The intrinsic width and height of the viewport of SVG content must be determined from the width and height attributes. 65 // If either of these are not specified, a value of '100%' must be assumed. Note: the width and height attributes are not 66 // the same as the CSS width and height properties. Specifically, percentage values do not provide an intrinsic width or height, 67 // and do not indicate a percentage of the containing block. Rather, once the viewport is established, they indicate the portion 68 // of the viewport that is actually covered by image data. 69 SVGSVGElement* svg = toSVGSVGElement(node()); 70 ASSERT(svg); 71 Length intrinsicWidthAttribute = svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties); 72 Length intrinsicHeightAttribute = svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties); 73 74 // The intrinsic aspect ratio of the viewport of SVG content is necessary for example, when including SVG from an object 75 // element in HTML styled with CSS. It is possible (indeed, common) for an SVG graphic to have an intrinsic aspect ratio but 76 // not to have an intrinsic width or height. The intrinsic aspect ratio must be calculated based upon the following rules: 77 // - The aspect ratio is calculated by dividing a width by a height. 78 // - If the width and height of the rootmost svg element are both specified with unit identifiers (in, mm, cm, pt, pc, 79 // px, em, ex) or in user units, then the aspect ratio is calculated from the width and height attributes after 80 // resolving both values to user units. 81 if (intrinsicWidthAttribute.isFixed() || intrinsicHeightAttribute.isFixed()) { 82 if (intrinsicWidthAttribute.isFixed()) 83 intrinsicSize.setWidth(floatValueForLength(intrinsicWidthAttribute, 0)); 84 if (intrinsicHeightAttribute.isFixed()) 85 intrinsicSize.setHeight(floatValueForLength(intrinsicHeightAttribute, 0)); 86 if (!intrinsicSize.isEmpty()) 87 intrinsicRatio = intrinsicSize.width() / static_cast<double>(intrinsicSize.height()); 88 return; 89 } 90 91 // - If either/both of the width and height of the rootmost svg element are in percentage units (or omitted), the 92 // aspect ratio is calculated from the width and height values of the viewBox specified for the current SVG document 93 // fragment. If the viewBox is not correctly specified, or set to 'none', the intrinsic aspect ratio cannot be 94 // calculated and is considered unspecified. 95 intrinsicSize = svg->viewBoxCurrentValue().size(); 96 if (!intrinsicSize.isEmpty()) { 97 // The viewBox can only yield an intrinsic ratio, not an intrinsic size. 98 intrinsicRatio = intrinsicSize.width() / static_cast<double>(intrinsicSize.height()); 99 intrinsicSize = FloatSize(); 100 return; 101 } 102 103 // If our intrinsic size is in percentage units, return those to the caller through the intrinsicSize. Notify the caller 104 // about the special situation, by setting isPercentageIntrinsicSize=true, so it knows how to interpret the return values. 105 if (intrinsicWidthAttribute.isPercent() && intrinsicHeightAttribute.isPercent()) { 106 isPercentageIntrinsicSize = true; 107 intrinsicSize = FloatSize(intrinsicWidthAttribute.percent(), intrinsicHeightAttribute.percent()); 108 } 109 } 110 111 bool RenderSVGRoot::isEmbeddedThroughSVGImage() const 112 { 113 if (!node()) 114 return false; 115 116 Frame* frame = node()->document()->frame(); 117 if (!frame) 118 return false; 119 120 // Test whether we're embedded through an img. 121 if (!frame->page()) 122 return false; 123 124 ChromeClient* chromeClient = frame->page()->chrome().client(); 125 if (!chromeClient || !chromeClient->isSVGImageChromeClient()) 126 return false; 127 128 return true; 129 } 130 131 bool RenderSVGRoot::isEmbeddedThroughFrameContainingSVGDocument() const 132 { 133 if (!node()) 134 return false; 135 136 Frame* frame = node()->document()->frame(); 137 if (!frame) 138 return false; 139 140 // If our frame has an owner renderer, we're embedded through eg. object/embed/iframe, 141 // but we only negotiate if we're in an SVG document. 142 if (!frame->ownerRenderer()) 143 return false; 144 return frame->document()->isSVGDocument(); 145 } 146 147 static inline LayoutUnit resolveLengthAttributeForSVG(const Length& length, float scale, float maxSize, RenderView* renderView) 148 { 149 return static_cast<LayoutUnit>(valueForLength(length, maxSize, renderView) * (length.isFixed() ? scale : 1)); 150 } 151 152 LayoutUnit RenderSVGRoot::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const 153 { 154 SVGSVGElement* svg = toSVGSVGElement(node()); 155 ASSERT(svg); 156 157 // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size. 158 if (!m_containerSize.isEmpty()) 159 return m_containerSize.width(); 160 161 if (style()->logicalWidth().isSpecified() || style()->logicalMaxWidth().isSpecified()) 162 return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred); 163 164 if (svg->widthAttributeEstablishesViewport()) 165 return resolveLengthAttributeForSVG(svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties), style()->effectiveZoom(), containingBlock()->availableLogicalWidth(), view()); 166 167 // SVG embedded through object/embed/iframe. 168 if (isEmbeddedThroughFrameContainingSVGDocument()) 169 return document()->frame()->ownerRenderer()->availableLogicalWidth(); 170 171 // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG. 172 return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred); 173 } 174 175 LayoutUnit RenderSVGRoot::computeReplacedLogicalHeight() const 176 { 177 SVGSVGElement* svg = toSVGSVGElement(node()); 178 ASSERT(svg); 179 180 // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size. 181 if (!m_containerSize.isEmpty()) 182 return m_containerSize.height(); 183 184 if (style()->logicalHeight().isSpecified() || style()->logicalMaxHeight().isSpecified()) 185 return RenderReplaced::computeReplacedLogicalHeight(); 186 187 if (svg->heightAttributeEstablishesViewport()) { 188 Length height = svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties); 189 if (height.isPercent()) { 190 RenderBlock* cb = containingBlock(); 191 ASSERT(cb); 192 while (cb->isAnonymous()) { 193 cb = cb->containingBlock(); 194 cb->addPercentHeightDescendant(const_cast<RenderSVGRoot*>(this)); 195 } 196 } else 197 RenderBlock::removePercentHeightDescendant(const_cast<RenderSVGRoot*>(this)); 198 199 return resolveLengthAttributeForSVG(height, style()->effectiveZoom(), containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding), view()); 200 } 201 202 // SVG embedded through object/embed/iframe. 203 if (isEmbeddedThroughFrameContainingSVGDocument()) 204 return document()->frame()->ownerRenderer()->availableLogicalHeight(IncludeMarginBorderPadding); 205 206 // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG. 207 return RenderReplaced::computeReplacedLogicalHeight(); 208 } 209 210 void RenderSVGRoot::layout() 211 { 212 StackStats::LayoutCheckPoint layoutCheckPoint; 213 ASSERT(needsLayout()); 214 215 m_resourcesNeedingToInvalidateClients.clear(); 216 217 // Arbitrary affine transforms are incompatible with LayoutState. 218 LayoutStateDisabler layoutStateDisabler(view()); 219 220 bool needsLayout = selfNeedsLayout(); 221 LayoutRepainter repainter(*this, checkForRepaintDuringLayout() && needsLayout); 222 223 LayoutSize oldSize = size(); 224 updateLogicalWidth(); 225 updateLogicalHeight(); 226 buildLocalToBorderBoxTransform(); 227 228 SVGSVGElement* svg = toSVGSVGElement(node()); 229 ASSERT(svg); 230 m_isLayoutSizeChanged = needsLayout || (svg->hasRelativeLengths() && oldSize != size()); 231 SVGRenderSupport::layoutChildren(this, needsLayout || SVGRenderSupport::filtersForceContainerLayout(this)); 232 233 if (!m_resourcesNeedingToInvalidateClients.isEmpty()) { 234 // Invalidate resource clients, which may mark some nodes for layout. 235 HashSet<RenderSVGResourceContainer*>::iterator end = m_resourcesNeedingToInvalidateClients.end(); 236 for (HashSet<RenderSVGResourceContainer*>::iterator it = m_resourcesNeedingToInvalidateClients.begin(); it != end; ++it) 237 (*it)->removeAllClientsFromCache(); 238 239 m_isLayoutSizeChanged = false; 240 SVGRenderSupport::layoutChildren(this, false); 241 } 242 243 // At this point LayoutRepainter already grabbed the old bounds, 244 // recalculate them now so repaintAfterLayout() uses the new bounds. 245 if (m_needsBoundariesOrTransformUpdate) { 246 updateCachedBoundaries(); 247 m_needsBoundariesOrTransformUpdate = false; 248 } 249 250 updateLayerTransform(); 251 252 repainter.repaintAfterLayout(); 253 254 clearNeedsLayout(); 255 } 256 257 void RenderSVGRoot::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset) 258 { 259 // An empty viewport disables rendering. 260 if (pixelSnappedBorderBoxRect().isEmpty()) 261 return; 262 263 // Don't paint, if the context explicitly disabled it. 264 if (paintInfo.context->paintingDisabled()) 265 return; 266 267 // An empty viewBox also disables rendering. 268 // (http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute) 269 SVGSVGElement* svg = toSVGSVGElement(node()); 270 ASSERT(svg); 271 if (svg->hasEmptyViewBox()) 272 return; 273 274 Page* page = 0; 275 if (Frame* frame = this->frame()) 276 page = frame->page(); 277 278 // Don't paint if we don't have kids, except if we have filters we should paint those. 279 if (!firstChild()) { 280 SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(this); 281 if (!resources || !resources->filter()) { 282 if (page && paintInfo.phase == PaintPhaseForeground) 283 page->addRelevantUnpaintedObject(this, visualOverflowRect()); 284 return; 285 } 286 } 287 288 if (page && paintInfo.phase == PaintPhaseForeground) 289 page->addRelevantRepaintedObject(this, visualOverflowRect()); 290 291 // Make a copy of the PaintInfo because applyTransform will modify the damage rect. 292 PaintInfo childPaintInfo(paintInfo); 293 childPaintInfo.context->save(); 294 295 // Apply initial viewport clip - not affected by overflow handling 296 childPaintInfo.context->clip(pixelSnappedIntRect(overflowClipRect(paintOffset, paintInfo.renderRegion))); 297 298 // Convert from container offsets (html renderers) to a relative transform (svg renderers). 299 // Transform from our paint container's coordinate system to our local coords. 300 IntPoint adjustedPaintOffset = roundedIntPoint(paintOffset); 301 childPaintInfo.applyTransform(AffineTransform::translation(adjustedPaintOffset.x(), adjustedPaintOffset.y()) * localToBorderBoxTransform()); 302 303 // SVGRenderingContext must be destroyed before we restore the childPaintInfo.context, because a filter may have 304 // changed the context and it is only reverted when the SVGRenderingContext destructor finishes applying the filter. 305 { 306 SVGRenderingContext renderingContext; 307 bool continueRendering = true; 308 if (childPaintInfo.phase == PaintPhaseForeground) { 309 renderingContext.prepareToRenderSVGContent(this, childPaintInfo); 310 continueRendering = renderingContext.isRenderingPrepared(); 311 } 312 313 if (continueRendering) 314 RenderBox::paint(childPaintInfo, LayoutPoint()); 315 } 316 317 childPaintInfo.context->restore(); 318 } 319 320 void RenderSVGRoot::willBeDestroyed() 321 { 322 RenderBlock::removePercentHeightDescendant(const_cast<RenderSVGRoot*>(this)); 323 324 SVGResourcesCache::clientDestroyed(this); 325 RenderReplaced::willBeDestroyed(); 326 } 327 328 void RenderSVGRoot::styleWillChange(StyleDifference diff, const RenderStyle* newStyle) 329 { 330 if (diff == StyleDifferenceLayout) 331 setNeedsBoundariesUpdate(); 332 RenderReplaced::styleWillChange(diff, newStyle); 333 } 334 335 void RenderSVGRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle) 336 { 337 RenderReplaced::styleDidChange(diff, oldStyle); 338 SVGResourcesCache::clientStyleChanged(this, diff, style()); 339 } 340 341 void RenderSVGRoot::addChild(RenderObject* child, RenderObject* beforeChild) 342 { 343 RenderReplaced::addChild(child, beforeChild); 344 SVGResourcesCache::clientWasAddedToTree(child, child->style()); 345 } 346 347 void RenderSVGRoot::removeChild(RenderObject* child) 348 { 349 SVGResourcesCache::clientWillBeRemovedFromTree(child); 350 RenderReplaced::removeChild(child); 351 } 352 353 // RenderBox methods will expect coordinates w/o any transforms in coordinates 354 // relative to our borderBox origin. This method gives us exactly that. 355 void RenderSVGRoot::buildLocalToBorderBoxTransform() 356 { 357 SVGSVGElement* svg = toSVGSVGElement(node()); 358 ASSERT(svg); 359 float scale = style()->effectiveZoom(); 360 SVGPoint translate = svg->currentTranslate(); 361 LayoutSize borderAndPadding(borderLeft() + paddingLeft(), borderTop() + paddingTop()); 362 m_localToBorderBoxTransform = svg->viewBoxToViewTransform(contentWidth() / scale, contentHeight() / scale); 363 if (borderAndPadding.isEmpty() && scale == 1 && translate == SVGPoint::zero()) 364 return; 365 m_localToBorderBoxTransform = AffineTransform(scale, 0, 0, scale, borderAndPadding.width() + translate.x(), borderAndPadding.height() + translate.y()) * m_localToBorderBoxTransform; 366 } 367 368 const AffineTransform& RenderSVGRoot::localToParentTransform() const 369 { 370 // Slightly optimized version of m_localToParentTransform = AffineTransform::translation(x(), y()) * m_localToBorderBoxTransform; 371 m_localToParentTransform = m_localToBorderBoxTransform; 372 if (x()) 373 m_localToParentTransform.setE(m_localToParentTransform.e() + roundToInt(x())); 374 if (y()) 375 m_localToParentTransform.setF(m_localToParentTransform.f() + roundToInt(y())); 376 return m_localToParentTransform; 377 } 378 379 LayoutRect RenderSVGRoot::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const 380 { 381 return SVGRenderSupport::clippedOverflowRectForRepaint(this, repaintContainer); 382 } 383 384 void RenderSVGRoot::computeFloatRectForRepaint(const RenderLayerModelObject* repaintContainer, FloatRect& repaintRect, bool fixed) const 385 { 386 // Apply our local transforms (except for x/y translation), then our shadow, 387 // and then call RenderBox's method to handle all the normal CSS Box model bits 388 repaintRect = m_localToBorderBoxTransform.mapRect(repaintRect); 389 390 // Apply initial viewport clip - not affected by overflow settings 391 repaintRect.intersect(pixelSnappedBorderBoxRect()); 392 393 LayoutRect rect = enclosingIntRect(repaintRect); 394 RenderReplaced::computeRectForRepaint(repaintContainer, rect, fixed); 395 repaintRect = rect; 396 } 397 398 // This method expects local CSS box coordinates. 399 // Callers with local SVG viewport coordinates should first apply the localToBorderBoxTransform 400 // to convert from SVG viewport coordinates to local CSS box coordinates. 401 void RenderSVGRoot::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const 402 { 403 ASSERT(mode & ~IsFixed); // We should have no fixed content in the SVG rendering tree. 404 ASSERT(mode & UseTransforms); // mapping a point through SVG w/o respecting trasnforms is useless. 405 406 RenderReplaced::mapLocalToContainer(repaintContainer, transformState, mode | ApplyContainerFlip, wasFixed); 407 } 408 409 const RenderObject* RenderSVGRoot::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const 410 { 411 return RenderReplaced::pushMappingToContainer(ancestorToStopAt, geometryMap); 412 } 413 414 void RenderSVGRoot::updateCachedBoundaries() 415 { 416 SVGRenderSupport::computeContainerBoundingBoxes(this, m_objectBoundingBox, m_objectBoundingBoxValid, m_strokeBoundingBox, m_repaintBoundingBox); 417 SVGRenderSupport::intersectRepaintRectWithResources(this, m_repaintBoundingBox); 418 m_repaintBoundingBox.inflate(borderAndPaddingWidth()); 419 } 420 421 bool RenderSVGRoot::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction) 422 { 423 LayoutPoint pointInParent = locationInContainer.point() - toLayoutSize(accumulatedOffset); 424 LayoutPoint pointInBorderBox = pointInParent - toLayoutSize(location()); 425 426 // Only test SVG content if the point is in our content box. 427 // FIXME: This should be an intersection when rect-based hit tests are supported by nodeAtFloatPoint. 428 if (contentBoxRect().contains(pointInBorderBox)) { 429 FloatPoint localPoint = localToParentTransform().inverse().mapPoint(FloatPoint(pointInParent)); 430 431 for (RenderObject* child = lastChild(); child; child = child->previousSibling()) { 432 // FIXME: nodeAtFloatPoint() doesn't handle rect-based hit tests yet. 433 if (child->nodeAtFloatPoint(request, result, localPoint, hitTestAction)) { 434 updateHitTestResult(result, pointInBorderBox); 435 if (!result.addNodeToRectBasedTestResult(child->node(), request, locationInContainer)) 436 return true; 437 } 438 } 439 } 440 441 // If we didn't early exit above, we've just hit the container <svg> element. Unlike SVG 1.1, 2nd Edition allows container elements to be hit. 442 if (hitTestAction == HitTestBlockBackground && visibleToHitTestRequest(request)) { 443 // Only return true here, if the last hit testing phase 'BlockBackground' is executed. If we'd return true in the 'Foreground' phase, 444 // hit testing would stop immediately. For SVG only trees this doesn't matter. Though when we have a <foreignObject> subtree we need 445 // to be able to detect hits on the background of a <div> element. If we'd return true here in the 'Foreground' phase, we are not able 446 // to detect these hits anymore. 447 LayoutRect boundsRect(accumulatedOffset + location(), size()); 448 if (locationInContainer.intersects(boundsRect)) { 449 updateHitTestResult(result, pointInBorderBox); 450 if (!result.addNodeToRectBasedTestResult(node(), request, locationInContainer, boundsRect)) 451 return true; 452 } 453 } 454 455 return false; 456 } 457 458 bool RenderSVGRoot::hasRelativeDimensions() const 459 { 460 SVGSVGElement* svg = toSVGSVGElement(node()); 461 ASSERT(svg); 462 463 return svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties).isPercent() || svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties).isPercent(); 464 } 465 466 bool RenderSVGRoot::hasRelativeIntrinsicLogicalWidth() const 467 { 468 SVGSVGElement* svg = toSVGSVGElement(node()); 469 ASSERT(svg); 470 return svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties).isPercent(); 471 } 472 473 bool RenderSVGRoot::hasRelativeLogicalHeight() const 474 { 475 SVGSVGElement* svg = toSVGSVGElement(node()); 476 ASSERT(svg); 477 478 return svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties).isPercent(); 479 } 480 481 void RenderSVGRoot::addResourceForClientInvalidation(RenderSVGResourceContainer* resource) 482 { 483 RenderObject* svgRoot = resource->parent(); 484 while (svgRoot && !svgRoot->isSVGRoot()) 485 svgRoot = svgRoot->parent(); 486 if (!svgRoot) 487 return; 488 toRenderSVGRoot(svgRoot)->m_resourcesNeedingToInvalidateClients.add(resource); 489 } 490 491 } 492