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/page/Chrome.h"
29 #include "core/page/ChromeClient.h"
30 #include "core/frame/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 #include "core/svg/graphics/SVGImage.h"
49 RenderSVGRoot::RenderSVGRoot(SVGElement* node)
50 : RenderReplaced(node)
51 , m_objectBoundingBoxValid(false)
52 , m_isLayoutSizeChanged(false)
53 , m_needsBoundariesOrTransformUpdate(true)
57 RenderSVGRoot::~RenderSVGRoot()
61 void RenderSVGRoot::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio, bool& isPercentageIntrinsicSize) const
63 // Spec: http://www.w3.org/TR/SVG/coords.html#IntrinsicSizing
64 // SVG needs to specify how to calculate some intrinsic sizing properties to enable inclusion within other languages.
65 // The intrinsic width and height of the viewport of SVG content must be determined from the ‘width’ and ‘height’ attributes.
66 // If either of these are not specified, a value of '100%' must be assumed. Note: the ‘width’ and ‘height’ attributes are not
67 // the same as the CSS width and height properties. Specifically, percentage values do not provide an intrinsic width or height,
68 // and do not indicate a percentage of the containing block. Rather, once the viewport is established, they indicate the portion
69 // of the viewport that is actually covered by image data.
70 SVGSVGElement* svg = toSVGSVGElement(node());
72 Length intrinsicWidthAttribute = svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties);
73 Length intrinsicHeightAttribute = svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties);
75 // The intrinsic aspect ratio of the viewport of SVG content is necessary for example, when including SVG from an ‘object’
76 // element in HTML styled with CSS. It is possible (indeed, common) for an SVG graphic to have an intrinsic aspect ratio but
77 // not to have an intrinsic width or height. The intrinsic aspect ratio must be calculated based upon the following rules:
78 // - The aspect ratio is calculated by dividing a width by a height.
79 // - If the ‘width’ and ‘height’ of the rootmost ‘svg’ element are both specified with unit identifiers (in, mm, cm, pt, pc,
80 // px, em, ex) or in user units, then the aspect ratio is calculated from the ‘width’ and ‘height’ attributes after
81 // resolving both values to user units.
82 if (intrinsicWidthAttribute.isFixed() || intrinsicHeightAttribute.isFixed()) {
83 if (intrinsicWidthAttribute.isFixed())
84 intrinsicSize.setWidth(floatValueForLength(intrinsicWidthAttribute, 0, 0));
85 if (intrinsicHeightAttribute.isFixed())
86 intrinsicSize.setHeight(floatValueForLength(intrinsicHeightAttribute, 0, 0));
87 if (!intrinsicSize.isEmpty())
88 intrinsicRatio = intrinsicSize.width() / static_cast<double>(intrinsicSize.height());
92 // - If either/both of the ‘width’ and ‘height’ of the rootmost ‘svg’ element are in percentage units (or omitted), the
93 // aspect ratio is calculated from the width and height values of the ‘viewBox’ specified for the current SVG document
94 // fragment. If the ‘viewBox’ is not correctly specified, or set to 'none', the intrinsic aspect ratio cannot be
95 // calculated and is considered unspecified.
96 intrinsicSize = svg->viewBoxCurrentValue().size();
97 if (!intrinsicSize.isEmpty()) {
98 // The viewBox can only yield an intrinsic ratio, not an intrinsic size.
99 intrinsicRatio = intrinsicSize.width() / static_cast<double>(intrinsicSize.height());
100 intrinsicSize = FloatSize();
104 // If our intrinsic size is in percentage units, return those to the caller through the intrinsicSize. Notify the caller
105 // about the special situation, by setting isPercentageIntrinsicSize=true, so it knows how to interpret the return values.
106 if (intrinsicWidthAttribute.isPercent() && intrinsicHeightAttribute.isPercent()) {
107 isPercentageIntrinsicSize = true;
108 intrinsicSize = FloatSize(intrinsicWidthAttribute.percent(), intrinsicHeightAttribute.percent());
112 bool RenderSVGRoot::isEmbeddedThroughSVGImage() const
114 return SVGImage::isInSVGImage(toSVGSVGElement(node()));
117 bool RenderSVGRoot::isEmbeddedThroughFrameContainingSVGDocument() const
122 Frame* frame = node()->document().frame();
126 // If our frame has an owner renderer, we're embedded through eg. object/embed/iframe,
127 // but we only negotiate if we're in an SVG document.
128 if (!frame->ownerRenderer())
130 return frame->document()->isSVGDocument();
133 static inline LayoutUnit resolveLengthAttributeForSVG(const Length& length, float scale, float maxSize, RenderView* renderView)
135 return static_cast<LayoutUnit>(valueForLength(length, maxSize, renderView) * (length.isFixed() ? scale : 1));
138 LayoutUnit RenderSVGRoot::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
140 SVGSVGElement* svg = toSVGSVGElement(node());
143 // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
144 if (!m_containerSize.isEmpty())
145 return m_containerSize.width();
147 if (style()->logicalWidth().isSpecified() || style()->logicalMaxWidth().isSpecified())
148 return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
150 if (svg->widthAttributeEstablishesViewport())
151 return resolveLengthAttributeForSVG(svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties), style()->effectiveZoom(), containingBlock()->availableLogicalWidth(), view());
153 // SVG embedded through object/embed/iframe.
154 if (isEmbeddedThroughFrameContainingSVGDocument())
155 return document().frame()->ownerRenderer()->availableLogicalWidth();
157 // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
158 return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
161 LayoutUnit RenderSVGRoot::computeReplacedLogicalHeight() const
163 SVGSVGElement* svg = toSVGSVGElement(node());
166 // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
167 if (!m_containerSize.isEmpty())
168 return m_containerSize.height();
170 if (style()->logicalHeight().isSpecified() || style()->logicalMaxHeight().isSpecified())
171 return RenderReplaced::computeReplacedLogicalHeight();
173 if (svg->heightAttributeEstablishesViewport()) {
174 Length height = svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties);
175 if (height.isPercent()) {
176 RenderBlock* cb = containingBlock();
178 while (cb->isAnonymous()) {
179 cb = cb->containingBlock();
180 cb->addPercentHeightDescendant(const_cast<RenderSVGRoot*>(this));
183 RenderBlock::removePercentHeightDescendant(const_cast<RenderSVGRoot*>(this));
185 return resolveLengthAttributeForSVG(height, style()->effectiveZoom(), containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding), view());
188 // SVG embedded through object/embed/iframe.
189 if (isEmbeddedThroughFrameContainingSVGDocument())
190 return document().frame()->ownerRenderer()->availableLogicalHeight(IncludeMarginBorderPadding);
192 // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
193 return RenderReplaced::computeReplacedLogicalHeight();
196 void RenderSVGRoot::layout()
198 ASSERT(needsLayout());
200 // Arbitrary affine transforms are incompatible with LayoutState.
201 LayoutStateDisabler layoutStateDisabler(view());
203 bool needsLayout = selfNeedsLayout();
204 LayoutRepainter repainter(*this, checkForRepaintDuringLayout() && needsLayout);
206 LayoutSize oldSize = size();
207 updateLogicalWidth();
208 updateLogicalHeight();
209 buildLocalToBorderBoxTransform();
211 SVGRenderSupport::layoutResourcesIfNeeded(this);
213 SVGSVGElement* svg = toSVGSVGElement(node());
215 m_isLayoutSizeChanged = needsLayout || (svg->hasRelativeLengths() && oldSize != size());
216 SVGRenderSupport::layoutChildren(this, needsLayout || SVGRenderSupport::filtersForceContainerLayout(this));
218 // At this point LayoutRepainter already grabbed the old bounds,
219 // recalculate them now so repaintAfterLayout() uses the new bounds.
220 if (m_needsBoundariesOrTransformUpdate) {
221 updateCachedBoundaries();
222 m_needsBoundariesOrTransformUpdate = false;
225 updateLayerTransform();
227 repainter.repaintAfterLayout();
232 void RenderSVGRoot::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
234 // An empty viewport disables rendering.
235 if (pixelSnappedBorderBoxRect().isEmpty())
238 // Don't paint, if the context explicitly disabled it.
239 if (paintInfo.context->paintingDisabled())
242 // An empty viewBox also disables rendering.
243 // (http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute)
244 SVGSVGElement* svg = toSVGSVGElement(node());
246 if (svg->hasEmptyViewBox())
249 // Don't paint if we don't have kids, except if we have filters we should paint those.
251 SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(this);
252 if (!resources || !resources->filter())
256 // Make a copy of the PaintInfo because applyTransform will modify the damage rect.
257 PaintInfo childPaintInfo(paintInfo);
258 childPaintInfo.context->save();
260 // Apply initial viewport clip - not affected by overflow handling
261 childPaintInfo.context->clip(pixelSnappedIntRect(overflowClipRect(paintOffset, paintInfo.renderRegion)));
263 // Convert from container offsets (html renderers) to a relative transform (svg renderers).
264 // Transform from our paint container's coordinate system to our local coords.
265 IntPoint adjustedPaintOffset = roundedIntPoint(paintOffset);
266 childPaintInfo.applyTransform(AffineTransform::translation(adjustedPaintOffset.x(), adjustedPaintOffset.y()) * localToBorderBoxTransform());
268 // SVGRenderingContext must be destroyed before we restore the childPaintInfo.context, because a filter may have
269 // changed the context and it is only reverted when the SVGRenderingContext destructor finishes applying the filter.
271 SVGRenderingContext renderingContext;
272 bool continueRendering = true;
273 if (childPaintInfo.phase == PaintPhaseForeground) {
274 renderingContext.prepareToRenderSVGContent(this, childPaintInfo);
275 continueRendering = renderingContext.isRenderingPrepared();
278 if (continueRendering)
279 RenderBox::paint(childPaintInfo, LayoutPoint());
282 childPaintInfo.context->restore();
285 void RenderSVGRoot::willBeDestroyed()
287 RenderBlock::removePercentHeightDescendant(const_cast<RenderSVGRoot*>(this));
289 SVGResourcesCache::clientDestroyed(this);
290 RenderReplaced::willBeDestroyed();
293 void RenderSVGRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
295 if (diff == StyleDifferenceLayout)
296 setNeedsBoundariesUpdate();
298 RenderReplaced::styleDidChange(diff, oldStyle);
299 SVGResourcesCache::clientStyleChanged(this, diff, style());
302 void RenderSVGRoot::addChild(RenderObject* child, RenderObject* beforeChild)
304 RenderReplaced::addChild(child, beforeChild);
305 SVGResourcesCache::clientWasAddedToTree(child, child->style());
308 void RenderSVGRoot::removeChild(RenderObject* child)
310 SVGResourcesCache::clientWillBeRemovedFromTree(child);
311 RenderReplaced::removeChild(child);
314 void RenderSVGRoot::insertedIntoTree()
316 RenderReplaced::insertedIntoTree();
317 SVGResourcesCache::clientWasAddedToTree(this, style());
320 void RenderSVGRoot::willBeRemovedFromTree()
322 SVGResourcesCache::clientWillBeRemovedFromTree(this);
323 RenderReplaced::willBeRemovedFromTree();
326 // RenderBox methods will expect coordinates w/o any transforms in coordinates
327 // relative to our borderBox origin. This method gives us exactly that.
328 void RenderSVGRoot::buildLocalToBorderBoxTransform()
330 SVGSVGElement* svg = toSVGSVGElement(node());
332 float scale = style()->effectiveZoom();
333 SVGPoint translate = svg->currentTranslate();
334 LayoutSize borderAndPadding(borderLeft() + paddingLeft(), borderTop() + paddingTop());
335 m_localToBorderBoxTransform = svg->viewBoxToViewTransform(contentWidth() / scale, contentHeight() / scale);
336 if (borderAndPadding.isEmpty() && scale == 1 && translate == SVGPoint::zero())
338 m_localToBorderBoxTransform = AffineTransform(scale, 0, 0, scale, borderAndPadding.width() + translate.x(), borderAndPadding.height() + translate.y()) * m_localToBorderBoxTransform;
341 const AffineTransform& RenderSVGRoot::localToParentTransform() const
343 // Slightly optimized version of m_localToParentTransform = AffineTransform::translation(x(), y()) * m_localToBorderBoxTransform;
344 m_localToParentTransform = m_localToBorderBoxTransform;
346 m_localToParentTransform.setE(m_localToParentTransform.e() + roundToInt(x()));
348 m_localToParentTransform.setF(m_localToParentTransform.f() + roundToInt(y()));
349 return m_localToParentTransform;
352 LayoutRect RenderSVGRoot::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
354 return SVGRenderSupport::clippedOverflowRectForRepaint(this, repaintContainer);
357 void RenderSVGRoot::computeFloatRectForRepaint(const RenderLayerModelObject* repaintContainer, FloatRect& repaintRect, bool fixed) const
359 // Apply our local transforms (except for x/y translation), then our shadow,
360 // and then call RenderBox's method to handle all the normal CSS Box model bits
361 repaintRect = m_localToBorderBoxTransform.mapRect(repaintRect);
363 // Apply initial viewport clip - not affected by overflow settings
364 repaintRect.intersect(pixelSnappedBorderBoxRect());
366 LayoutRect rect = enclosingIntRect(repaintRect);
367 RenderReplaced::computeRectForRepaint(repaintContainer, rect, fixed);
371 // This method expects local CSS box coordinates.
372 // Callers with local SVG viewport coordinates should first apply the localToBorderBoxTransform
373 // to convert from SVG viewport coordinates to local CSS box coordinates.
374 void RenderSVGRoot::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
376 ASSERT(mode & ~IsFixed); // We should have no fixed content in the SVG rendering tree.
377 ASSERT(mode & UseTransforms); // mapping a point through SVG w/o respecting trasnforms is useless.
379 RenderReplaced::mapLocalToContainer(repaintContainer, transformState, mode | ApplyContainerFlip, wasFixed);
382 const RenderObject* RenderSVGRoot::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
384 return RenderReplaced::pushMappingToContainer(ancestorToStopAt, geometryMap);
387 void RenderSVGRoot::updateCachedBoundaries()
389 SVGRenderSupport::computeContainerBoundingBoxes(this, m_objectBoundingBox, m_objectBoundingBoxValid, m_strokeBoundingBox, m_repaintBoundingBox);
390 SVGRenderSupport::intersectRepaintRectWithResources(this, m_repaintBoundingBox);
391 m_repaintBoundingBox.inflate(borderAndPaddingWidth());
394 bool RenderSVGRoot::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
396 LayoutPoint pointInParent = locationInContainer.point() - toLayoutSize(accumulatedOffset);
397 LayoutPoint pointInBorderBox = pointInParent - toLayoutSize(location());
399 // Only test SVG content if the point is in our content box.
400 // FIXME: This should be an intersection when rect-based hit tests are supported by nodeAtFloatPoint.
401 if (contentBoxRect().contains(pointInBorderBox)) {
402 FloatPoint localPoint = localToParentTransform().inverse().mapPoint(FloatPoint(pointInParent));
404 for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
405 // FIXME: nodeAtFloatPoint() doesn't handle rect-based hit tests yet.
406 if (child->nodeAtFloatPoint(request, result, localPoint, hitTestAction)) {
407 updateHitTestResult(result, pointInBorderBox);
408 if (!result.addNodeToRectBasedTestResult(child->node(), request, locationInContainer))
414 // 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.
415 if (hitTestAction == HitTestBlockBackground && visibleToHitTestRequest(request)) {
416 // Only return true here, if the last hit testing phase 'BlockBackground' is executed. If we'd return true in the 'Foreground' phase,
417 // hit testing would stop immediately. For SVG only trees this doesn't matter. Though when we have a <foreignObject> subtree we need
418 // 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
419 // to detect these hits anymore.
420 LayoutRect boundsRect(accumulatedOffset + location(), size());
421 if (locationInContainer.intersects(boundsRect)) {
422 updateHitTestResult(result, pointInBorderBox);
423 if (!result.addNodeToRectBasedTestResult(node(), request, locationInContainer, boundsRect))
431 bool RenderSVGRoot::hasRelativeDimensions() const
433 SVGSVGElement* svg = toSVGSVGElement(node());
436 return svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties).isPercent() || svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties).isPercent();
439 bool RenderSVGRoot::hasRelativeIntrinsicLogicalWidth() const
441 SVGSVGElement* svg = toSVGSVGElement(node());
443 return svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties).isPercent();
446 bool RenderSVGRoot::hasRelativeLogicalHeight() const
448 SVGSVGElement* svg = toSVGSVGElement(node());
451 return svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties).isPercent();