2 * Copyright (C) 2004, 2005, 2007 Nikolas Zimmermann <zimmermann@kde.org>
3 * Copyright (C) 2004, 2005, 2007, 2008, 2009 Rob Buis <buis@kde.org>
4 * Copyright (C) 2007 Eric Seidel <eric@webkit.org>
5 * Copyright (C) 2009 Google, Inc.
6 * Copyright (C) Research In Motion Limited 2011. All rights reserved.
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.
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.
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.
26 #include "core/rendering/svg/RenderSVGRoot.h"
28 #include "core/frame/Frame.h"
29 #include "core/rendering/HitTestResult.h"
30 #include "core/rendering/LayoutRectRecorder.h"
31 #include "core/rendering/LayoutRepainter.h"
32 #include "core/rendering/RenderPart.h"
33 #include "core/rendering/RenderView.h"
34 #include "core/rendering/svg/RenderSVGResourceContainer.h"
35 #include "core/rendering/svg/SVGRenderingContext.h"
36 #include "core/rendering/svg/SVGResources.h"
37 #include "core/rendering/svg/SVGResourcesCache.h"
38 #include "core/svg/SVGElement.h"
39 #include "core/svg/SVGSVGElement.h"
40 #include "core/svg/graphics/SVGImage.h"
41 #include "platform/LengthFunctions.h"
42 #include "platform/graphics/GraphicsContext.h"
48 RenderSVGRoot::RenderSVGRoot(SVGElement* node)
49 : RenderReplaced(node)
50 , m_objectBoundingBoxValid(false)
51 , m_isLayoutSizeChanged(false)
52 , m_needsBoundariesOrTransformUpdate(true)
56 RenderSVGRoot::~RenderSVGRoot()
60 void RenderSVGRoot::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio, bool& isPercentageIntrinsicSize) const
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());
71 Length intrinsicWidthAttribute = svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties);
72 Length intrinsicHeightAttribute = svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties);
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());
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->viewBox()->currentValue()->value().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();
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());
111 bool RenderSVGRoot::isEmbeddedThroughSVGImage() const
113 return SVGImage::isInSVGImage(toSVGSVGElement(node()));
116 bool RenderSVGRoot::isEmbeddedThroughFrameContainingSVGDocument() const
121 Frame* frame = node()->document().frame();
125 // If our frame has an owner renderer, we're embedded through eg. object/embed/iframe,
126 // but we only negotiate if we're in an SVG document.
127 if (!frame->ownerRenderer())
129 return frame->document()->isSVGDocument();
132 static inline LayoutUnit resolveLengthAttributeForSVG(const Length& length, float scale, float maxSize)
134 return static_cast<LayoutUnit>(valueForLength(length, maxSize) * (length.isFixed() ? scale : 1));
137 LayoutUnit RenderSVGRoot::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
139 SVGSVGElement* svg = toSVGSVGElement(node());
142 // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
143 if (!m_containerSize.isEmpty())
144 return m_containerSize.width();
146 if (style()->logicalWidth().isSpecified() || style()->logicalMaxWidth().isSpecified())
147 return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
149 if (svg->widthAttributeEstablishesViewport())
150 return resolveLengthAttributeForSVG(svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties), style()->effectiveZoom(), containingBlock()->availableLogicalWidth());
152 // SVG embedded through object/embed/iframe.
153 if (isEmbeddedThroughFrameContainingSVGDocument())
154 return document().frame()->ownerRenderer()->availableLogicalWidth();
156 // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
157 return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
160 LayoutUnit RenderSVGRoot::computeReplacedLogicalHeight() const
162 SVGSVGElement* svg = toSVGSVGElement(node());
165 // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
166 if (!m_containerSize.isEmpty())
167 return m_containerSize.height();
169 if (style()->logicalHeight().isSpecified() || style()->logicalMaxHeight().isSpecified())
170 return RenderReplaced::computeReplacedLogicalHeight();
172 if (svg->heightAttributeEstablishesViewport()) {
173 Length height = svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties);
174 if (height.isPercent()) {
175 RenderBlock* cb = containingBlock();
177 while (cb->isAnonymous()) {
178 cb = cb->containingBlock();
179 cb->addPercentHeightDescendant(const_cast<RenderSVGRoot*>(this));
182 RenderBlock::removePercentHeightDescendant(const_cast<RenderSVGRoot*>(this));
184 return resolveLengthAttributeForSVG(height, style()->effectiveZoom(), containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding));
187 // SVG embedded through object/embed/iframe.
188 if (isEmbeddedThroughFrameContainingSVGDocument())
189 return document().frame()->ownerRenderer()->availableLogicalHeight(IncludeMarginBorderPadding);
191 // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
192 return RenderReplaced::computeReplacedLogicalHeight();
195 void RenderSVGRoot::layout()
197 ASSERT(needsLayout());
199 LayoutRectRecorder recorder(*this);
201 // Arbitrary affine transforms are incompatible with LayoutState.
202 LayoutStateDisabler layoutStateDisabler(view());
204 bool needsLayout = selfNeedsLayout();
205 LayoutRepainter repainter(*this, checkForRepaintDuringLayout() && needsLayout);
207 LayoutSize oldSize = size();
208 updateLogicalWidth();
209 updateLogicalHeight();
210 buildLocalToBorderBoxTransform();
212 SVGRenderSupport::layoutResourcesIfNeeded(this);
214 SVGSVGElement* svg = toSVGSVGElement(node());
216 m_isLayoutSizeChanged = needsLayout || (svg->hasRelativeLengths() && oldSize != size());
217 SVGRenderSupport::layoutChildren(this, needsLayout || SVGRenderSupport::filtersForceContainerLayout(this));
219 // At this point LayoutRepainter already grabbed the old bounds,
220 // recalculate them now so repaintAfterLayout() uses the new bounds.
221 if (m_needsBoundariesOrTransformUpdate) {
222 updateCachedBoundaries();
223 m_needsBoundariesOrTransformUpdate = false;
226 updateLayerTransform();
228 repainter.repaintAfterLayout();
233 void RenderSVGRoot::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
235 // An empty viewport disables rendering.
236 if (pixelSnappedBorderBoxRect().isEmpty())
239 // Don't paint, if the context explicitly disabled it.
240 if (paintInfo.context->paintingDisabled())
243 // An empty viewBox also disables rendering.
244 // (http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute)
245 SVGSVGElement* svg = toSVGSVGElement(node());
247 if (svg->hasEmptyViewBox())
250 // Don't paint if we don't have kids, except if we have filters we should paint those.
252 SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(this);
253 if (!resources || !resources->filter())
257 // Make a copy of the PaintInfo because applyTransform will modify the damage rect.
258 PaintInfo childPaintInfo(paintInfo);
259 childPaintInfo.context->save();
261 // Apply initial viewport clip - not affected by overflow handling
262 childPaintInfo.context->clip(pixelSnappedIntRect(overflowClipRect(paintOffset)));
264 // Convert from container offsets (html renderers) to a relative transform (svg renderers).
265 // Transform from our paint container's coordinate system to our local coords.
266 IntPoint adjustedPaintOffset = roundedIntPoint(paintOffset);
267 childPaintInfo.applyTransform(AffineTransform::translation(adjustedPaintOffset.x(), adjustedPaintOffset.y()) * localToBorderBoxTransform());
269 // SVGRenderingContext must be destroyed before we restore the childPaintInfo.context, because a filter may have
270 // changed the context and it is only reverted when the SVGRenderingContext destructor finishes applying the filter.
272 SVGRenderingContext renderingContext;
273 bool continueRendering = true;
274 if (childPaintInfo.phase == PaintPhaseForeground) {
275 renderingContext.prepareToRenderSVGContent(this, childPaintInfo);
276 continueRendering = renderingContext.isRenderingPrepared();
279 if (continueRendering)
280 RenderBox::paint(childPaintInfo, LayoutPoint());
283 childPaintInfo.context->restore();
286 void RenderSVGRoot::willBeDestroyed()
288 RenderBlock::removePercentHeightDescendant(const_cast<RenderSVGRoot*>(this));
290 SVGResourcesCache::clientDestroyed(this);
291 RenderReplaced::willBeDestroyed();
294 void RenderSVGRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
296 if (diff == StyleDifferenceLayout)
297 setNeedsBoundariesUpdate();
299 RenderReplaced::styleDidChange(diff, oldStyle);
300 SVGResourcesCache::clientStyleChanged(this, diff, style());
303 bool RenderSVGRoot::isChildAllowed(RenderObject* child, RenderStyle*) const
305 return child->isSVG() && !(child->isSVGInline() || child->isSVGInlineText());
308 void RenderSVGRoot::addChild(RenderObject* child, RenderObject* beforeChild)
310 RenderReplaced::addChild(child, beforeChild);
311 SVGResourcesCache::clientWasAddedToTree(child, child->style());
314 void RenderSVGRoot::removeChild(RenderObject* child)
316 SVGResourcesCache::clientWillBeRemovedFromTree(child);
317 RenderReplaced::removeChild(child);
320 void RenderSVGRoot::insertedIntoTree()
322 RenderReplaced::insertedIntoTree();
323 SVGResourcesCache::clientWasAddedToTree(this, style());
326 void RenderSVGRoot::willBeRemovedFromTree()
328 SVGResourcesCache::clientWillBeRemovedFromTree(this);
329 RenderReplaced::willBeRemovedFromTree();
332 // RenderBox methods will expect coordinates w/o any transforms in coordinates
333 // relative to our borderBox origin. This method gives us exactly that.
334 void RenderSVGRoot::buildLocalToBorderBoxTransform()
336 SVGSVGElement* svg = toSVGSVGElement(node());
338 float scale = style()->effectiveZoom();
339 FloatPoint translate = svg->currentTranslate();
340 LayoutSize borderAndPadding(borderLeft() + paddingLeft(), borderTop() + paddingTop());
341 m_localToBorderBoxTransform = svg->viewBoxToViewTransform(contentWidth() / scale, contentHeight() / scale);
342 if (borderAndPadding.isEmpty() && scale == 1 && translate == FloatPoint::zero())
344 m_localToBorderBoxTransform = AffineTransform(scale, 0, 0, scale, borderAndPadding.width() + translate.x(), borderAndPadding.height() + translate.y()) * m_localToBorderBoxTransform;
347 const AffineTransform& RenderSVGRoot::localToParentTransform() const
349 // Slightly optimized version of m_localToParentTransform = AffineTransform::translation(x(), y()) * m_localToBorderBoxTransform;
350 m_localToParentTransform = m_localToBorderBoxTransform;
352 m_localToParentTransform.setE(m_localToParentTransform.e() + roundToInt(x()));
354 m_localToParentTransform.setF(m_localToParentTransform.f() + roundToInt(y()));
355 return m_localToParentTransform;
358 LayoutRect RenderSVGRoot::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
360 return SVGRenderSupport::clippedOverflowRectForRepaint(this, repaintContainer);
363 void RenderSVGRoot::computeFloatRectForRepaint(const RenderLayerModelObject* repaintContainer, FloatRect& repaintRect, bool fixed) const
365 // Apply our local transforms (except for x/y translation), then our shadow,
366 // and then call RenderBox's method to handle all the normal CSS Box model bits
367 repaintRect = m_localToBorderBoxTransform.mapRect(repaintRect);
369 // Apply initial viewport clip - not affected by overflow settings
370 repaintRect.intersect(pixelSnappedBorderBoxRect());
372 LayoutRect rect = enclosingIntRect(repaintRect);
373 RenderReplaced::computeRectForRepaint(repaintContainer, rect, fixed);
377 // This method expects local CSS box coordinates.
378 // Callers with local SVG viewport coordinates should first apply the localToBorderBoxTransform
379 // to convert from SVG viewport coordinates to local CSS box coordinates.
380 void RenderSVGRoot::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
382 ASSERT(mode & ~IsFixed); // We should have no fixed content in the SVG rendering tree.
383 ASSERT(mode & UseTransforms); // mapping a point through SVG w/o respecting trasnforms is useless.
385 RenderReplaced::mapLocalToContainer(repaintContainer, transformState, mode | ApplyContainerFlip, wasFixed);
388 const RenderObject* RenderSVGRoot::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
390 return RenderReplaced::pushMappingToContainer(ancestorToStopAt, geometryMap);
393 void RenderSVGRoot::updateCachedBoundaries()
395 SVGRenderSupport::computeContainerBoundingBoxes(this, m_objectBoundingBox, m_objectBoundingBoxValid, m_strokeBoundingBox, m_repaintBoundingBox);
396 SVGRenderSupport::intersectRepaintRectWithResources(this, m_repaintBoundingBox);
397 m_repaintBoundingBox.inflate(borderAndPaddingWidth());
400 bool RenderSVGRoot::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
402 LayoutPoint pointInParent = locationInContainer.point() - toLayoutSize(accumulatedOffset);
403 LayoutPoint pointInBorderBox = pointInParent - toLayoutSize(location());
405 // Only test SVG content if the point is in our content box.
406 // FIXME: This should be an intersection when rect-based hit tests are supported by nodeAtFloatPoint.
407 if (contentBoxRect().contains(pointInBorderBox)) {
408 FloatPoint localPoint = localToParentTransform().inverse().mapPoint(FloatPoint(pointInParent));
410 for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
411 // FIXME: nodeAtFloatPoint() doesn't handle rect-based hit tests yet.
412 if (child->nodeAtFloatPoint(request, result, localPoint, hitTestAction)) {
413 updateHitTestResult(result, pointInBorderBox);
414 if (!result.addNodeToRectBasedTestResult(child->node(), request, locationInContainer))
420 // 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.
421 if (hitTestAction == HitTestBlockBackground && visibleToHitTestRequest(request)) {
422 // Only return true here, if the last hit testing phase 'BlockBackground' is executed. If we'd return true in the 'Foreground' phase,
423 // hit testing would stop immediately. For SVG only trees this doesn't matter. Though when we have a <foreignObject> subtree we need
424 // 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
425 // to detect these hits anymore.
426 LayoutRect boundsRect(accumulatedOffset + location(), size());
427 if (locationInContainer.intersects(boundsRect)) {
428 updateHitTestResult(result, pointInBorderBox);
429 if (!result.addNodeToRectBasedTestResult(node(), request, locationInContainer, boundsRect))
437 bool RenderSVGRoot::hasRelativeIntrinsicLogicalWidth() const
439 SVGSVGElement* svg = toSVGSVGElement(node());
441 return svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties).isPercent();
444 bool RenderSVGRoot::hasRelativeLogicalHeight() const
446 SVGSVGElement* svg = toSVGSVGElement(node());
449 return svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties).isPercent();