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/LocalFrame.h"
29 #include "core/rendering/HitTestResult.h"
30 #include "core/rendering/RenderLayer.h"
31 #include "core/rendering/RenderPart.h"
32 #include "core/rendering/RenderView.h"
33 #include "core/rendering/svg/RenderSVGResourceContainer.h"
34 #include "core/rendering/svg/SVGRenderSupport.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"
46 RenderSVGRoot::RenderSVGRoot(SVGElement* node)
47 : RenderReplaced(node)
48 , m_objectBoundingBoxValid(false)
49 , m_isLayoutSizeChanged(false)
50 , m_needsBoundariesOrTransformUpdate(true)
51 , m_hasBoxDecorationBackground(false)
55 RenderSVGRoot::~RenderSVGRoot()
59 void RenderSVGRoot::trace(Visitor* visitor)
61 visitor->trace(m_children);
62 RenderReplaced::trace(visitor);
65 void RenderSVGRoot::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio) const
67 // Spec: http://www.w3.org/TR/SVG/coords.html#IntrinsicSizing
68 // SVG needs to specify how to calculate some intrinsic sizing properties to enable inclusion within other languages.
69 // The intrinsic width and height of the viewport of SVG content must be determined from the ‘width’ and ‘height’ attributes.
70 SVGSVGElement* svg = toSVGSVGElement(node());
73 // The intrinsic aspect ratio of the viewport of SVG content is necessary for example, when including SVG from an ‘object’
74 // element in HTML styled with CSS. It is possible (indeed, common) for an SVG graphic to have an intrinsic aspect ratio but
75 // not to have an intrinsic width or height. The intrinsic aspect ratio must be calculated based upon the following rules:
76 // - The aspect ratio is calculated by dividing a width by a height.
77 // - If the ‘width’ and ‘height’ of the rootmost ‘svg’ element are both specified with unit identifiers (in, mm, cm, pt, pc,
78 // px, em, ex) or in user units, then the aspect ratio is calculated from the ‘width’ and ‘height’ attributes after
79 // resolving both values to user units.
80 intrinsicSize.setWidth(floatValueForLength(svg->intrinsicWidth(), 0));
81 intrinsicSize.setHeight(floatValueForLength(svg->intrinsicHeight(), 0));
83 if (!intrinsicSize.isEmpty()) {
84 intrinsicRatio = intrinsicSize.width() / static_cast<double>(intrinsicSize.height());
86 // - If either/both of the ‘width’ and ‘height’ of the rootmost ‘svg’ element are in percentage units (or omitted), the
87 // aspect ratio is calculated from the width and height values of the ‘viewBox’ specified for the current SVG document
88 // fragment. If the ‘viewBox’ is not correctly specified, or set to 'none', the intrinsic aspect ratio cannot be
89 // calculated and is considered unspecified.
90 FloatSize viewBoxSize = svg->viewBox()->currentValue()->value().size();
91 if (!viewBoxSize.isEmpty()) {
92 // The viewBox can only yield an intrinsic ratio, not an intrinsic size.
93 intrinsicRatio = viewBoxSize.width() / static_cast<double>(viewBoxSize.height());
98 bool RenderSVGRoot::isEmbeddedThroughSVGImage() const
100 return SVGImage::isInSVGImage(toSVGSVGElement(node()));
103 bool RenderSVGRoot::isEmbeddedThroughFrameContainingSVGDocument() const
108 LocalFrame* frame = node()->document().frame();
112 // If our frame has an owner renderer, we're embedded through eg. object/embed/iframe,
113 // but we only negotiate if we're in an SVG document inside a embedded object (object/embed).
114 if (!frame->ownerRenderer() || !frame->ownerRenderer()->isEmbeddedObject())
116 return frame->document()->isSVGDocument();
119 static inline LayoutUnit resolveLengthAttributeForSVG(const Length& length, float scale, float maxSize)
121 return static_cast<LayoutUnit>(valueForLength(length, maxSize) * (length.isFixed() ? scale : 1));
124 LayoutUnit RenderSVGRoot::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
126 SVGSVGElement* svg = toSVGSVGElement(node());
129 // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
130 if (!m_containerSize.isEmpty())
131 return m_containerSize.width();
133 if (isEmbeddedThroughFrameContainingSVGDocument())
134 return containingBlock()->availableLogicalWidth();
136 if (style()->logicalWidth().isSpecified() || style()->logicalMaxWidth().isSpecified())
137 return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
139 if (svg->hasIntrinsicWidth())
140 return resolveLengthAttributeForSVG(svg->intrinsicWidth(), style()->effectiveZoom(), containingBlock()->availableLogicalWidth().toFloat());
142 // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
143 return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
146 LayoutUnit RenderSVGRoot::computeReplacedLogicalHeight() const
148 SVGSVGElement* svg = toSVGSVGElement(node());
151 // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
152 if (!m_containerSize.isEmpty())
153 return m_containerSize.height();
155 if (isEmbeddedThroughFrameContainingSVGDocument())
156 return containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding);
158 if (style()->logicalHeight().isSpecified() || style()->logicalMaxHeight().isSpecified())
159 return RenderReplaced::computeReplacedLogicalHeight();
161 if (svg->hasIntrinsicHeight())
162 return resolveLengthAttributeForSVG(svg->intrinsicHeight(), style()->effectiveZoom(), containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding).toFloat());
164 // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
165 return RenderReplaced::computeReplacedLogicalHeight();
168 void RenderSVGRoot::layout()
170 ASSERT(needsLayout());
172 bool needsLayout = selfNeedsLayout();
174 LayoutSize oldSize = size();
175 updateLogicalWidth();
176 updateLogicalHeight();
177 buildLocalToBorderBoxTransform();
179 SVGRenderSupport::layoutResourcesIfNeeded(this);
181 SVGSVGElement* svg = toSVGSVGElement(node());
183 m_isLayoutSizeChanged = needsLayout || (svg->hasRelativeLengths() && oldSize != size());
184 SVGRenderSupport::layoutChildren(this, needsLayout || SVGRenderSupport::filtersForceContainerLayout(this));
186 if (m_needsBoundariesOrTransformUpdate) {
187 updateCachedBoundaries();
188 m_needsBoundariesOrTransformUpdate = false;
192 addVisualEffectOverflow();
194 if (!shouldApplyViewportClip()) {
195 FloatRect contentPaintInvalidationRect = paintInvalidationRectInLocalCoordinates();
196 contentPaintInvalidationRect = m_localToBorderBoxTransform.mapRect(contentPaintInvalidationRect);
197 addVisualOverflow(enclosingLayoutRect(contentPaintInvalidationRect));
200 updateLayerTransformAfterLayout();
201 m_hasBoxDecorationBackground = isDocumentElement() ? calculateHasBoxDecorations() : hasBoxDecorationBackground();
202 invalidateBackgroundObscurationStatus();
207 bool RenderSVGRoot::shouldApplyViewportClip() const
209 // the outermost svg is clipped if auto, and svg document roots are always clipped
210 // When the svg is stand-alone (isDocumentElement() == true) the viewport clipping should always
211 // be applied, noting that the window scrollbars should be hidden if overflow=hidden.
212 return style()->overflowX() == OHIDDEN
213 || style()->overflowX() == OAUTO
214 || style()->overflowX() == OSCROLL
215 || this->isDocumentElement();
218 void RenderSVGRoot::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
220 // An empty viewport disables rendering.
221 if (pixelSnappedBorderBoxRect().isEmpty())
224 // SVG outlines are painted during PaintPhaseForeground.
225 if (paintInfo.phase == PaintPhaseOutline || paintInfo.phase == PaintPhaseSelfOutline)
228 // An empty viewBox also disables rendering.
229 // (http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute)
230 SVGSVGElement* svg = toSVGSVGElement(node());
232 if (svg->hasEmptyViewBox())
235 // Don't paint if we don't have kids, except if we have filters we should paint those.
237 SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(this);
238 if (!resources || !resources->filter())
242 // Make a copy of the PaintInfo because applyTransform will modify the damage rect.
243 PaintInfo childPaintInfo(paintInfo);
244 GraphicsContextStateSaver stateSaver(*childPaintInfo.context);
246 // Apply initial viewport clip
247 if (shouldApplyViewportClip())
248 childPaintInfo.context->clip(pixelSnappedIntRect(overflowClipRect(paintOffset)));
250 // Convert from container offsets (html renderers) to a relative transform (svg renderers).
251 // Transform from our paint container's coordinate system to our local coords.
252 IntPoint adjustedPaintOffset = roundedIntPoint(paintOffset);
253 childPaintInfo.applyTransform(AffineTransform::translation(adjustedPaintOffset.x(), adjustedPaintOffset.y()) * localToBorderBoxTransform());
255 SVGRenderingContext renderingContext;
256 if (childPaintInfo.phase == PaintPhaseForeground) {
257 renderingContext.prepareToRenderSVGContent(this, childPaintInfo);
258 if (!renderingContext.isRenderingPrepared())
262 RenderBox::paint(childPaintInfo, LayoutPoint());
265 void RenderSVGRoot::willBeDestroyed()
267 RenderBlock::removePercentHeightDescendant(const_cast<RenderSVGRoot*>(this));
269 SVGResourcesCache::clientDestroyed(this);
270 RenderReplaced::willBeDestroyed();
273 void RenderSVGRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
275 if (diff.needsFullLayout())
276 setNeedsBoundariesUpdate();
277 if (diff.needsPaintInvalidation()) {
278 // Box decorations may have appeared/disappeared - recompute status.
279 m_hasBoxDecorationBackground = calculateHasBoxDecorations();
282 RenderReplaced::styleDidChange(diff, oldStyle);
283 SVGResourcesCache::clientStyleChanged(this, diff, style());
286 bool RenderSVGRoot::isChildAllowed(RenderObject* child, RenderStyle*) const
288 return child->isSVG() && !(child->isSVGInline() || child->isSVGInlineText());
291 void RenderSVGRoot::addChild(RenderObject* child, RenderObject* beforeChild)
293 RenderReplaced::addChild(child, beforeChild);
294 SVGResourcesCache::clientWasAddedToTree(child, child->style());
297 void RenderSVGRoot::removeChild(RenderObject* child)
299 SVGResourcesCache::clientWillBeRemovedFromTree(child);
300 RenderReplaced::removeChild(child);
303 void RenderSVGRoot::insertedIntoTree()
305 RenderReplaced::insertedIntoTree();
306 SVGResourcesCache::clientWasAddedToTree(this, style());
309 void RenderSVGRoot::willBeRemovedFromTree()
311 SVGResourcesCache::clientWillBeRemovedFromTree(this);
312 RenderReplaced::willBeRemovedFromTree();
315 // RenderBox methods will expect coordinates w/o any transforms in coordinates
316 // relative to our borderBox origin. This method gives us exactly that.
317 void RenderSVGRoot::buildLocalToBorderBoxTransform()
319 SVGSVGElement* svg = toSVGSVGElement(node());
321 float scale = style()->effectiveZoom();
322 FloatPoint translate = svg->currentTranslate();
323 LayoutSize borderAndPadding(borderLeft() + paddingLeft(), borderTop() + paddingTop());
324 m_localToBorderBoxTransform = svg->viewBoxToViewTransform(contentWidth() / scale, contentHeight() / scale);
325 AffineTransform viewToBorderBoxTransform(scale, 0, 0, scale, borderAndPadding.width() + translate.x(), borderAndPadding.height() + translate.y());
326 if (viewToBorderBoxTransform.isIdentity())
328 m_localToBorderBoxTransform = viewToBorderBoxTransform * m_localToBorderBoxTransform;
331 const AffineTransform& RenderSVGRoot::localToParentTransform() const
333 // Slightly optimized version of m_localToParentTransform = AffineTransform::translation(x(), y()) * m_localToBorderBoxTransform;
334 m_localToParentTransform = m_localToBorderBoxTransform;
336 m_localToParentTransform.setE(m_localToParentTransform.e() + roundToInt(x()));
338 m_localToParentTransform.setF(m_localToParentTransform.f() + roundToInt(y()));
339 return m_localToParentTransform;
342 LayoutRect RenderSVGRoot::clippedOverflowRectForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer, const PaintInvalidationState* paintInvalidationState) const
344 // This is an open-coded aggregate of SVGRenderSupport::clippedOverflowRectForPaintInvalidation,
345 // RenderSVGRoot::computeFloatRectForPaintInvalidation and RenderReplaced::clippedOverflowRectForPaintInvalidation.
346 // The reason for this is to optimize/minimize the paint invalidation rect when the box is not "decorated"
347 // (does not have background/border/etc.)
349 // Return early for any cases where we don't actually paint.
350 if (style()->visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent())
353 // Compute the paint invalidation rect of the content of the SVG in the border-box coordinate space.
354 FloatRect contentPaintInvalidationRect = paintInvalidationRectInLocalCoordinates();
355 contentPaintInvalidationRect = m_localToBorderBoxTransform.mapRect(contentPaintInvalidationRect);
357 // Apply initial viewport clip, overflow:visible content is added to visualOverflow
358 // but the most common case is that overflow is hidden, so always intersect.
359 contentPaintInvalidationRect.intersect(pixelSnappedBorderBoxRect());
361 LayoutRect paintInvalidationRect = enclosingLayoutRect(contentPaintInvalidationRect);
362 // If the box is decorated or is overflowing, extend it to include the border-box and overflow.
363 if (m_hasBoxDecorationBackground || hasRenderOverflow()) {
364 // The selectionRect can project outside of the overflowRect, so take their union
365 // for paint invalidation to avoid selection painting glitches.
366 LayoutRect decoratedPaintInvalidationRect = unionRect(localSelectionRect(false), visualOverflowRect());
367 paintInvalidationRect.unite(decoratedPaintInvalidationRect);
370 // Compute the paint invalidation rect in the parent coordinate space.
371 LayoutRect rect = enclosingIntRect(paintInvalidationRect);
372 RenderReplaced::mapRectToPaintInvalidationBacking(paintInvalidationContainer, rect, paintInvalidationState);
376 void RenderSVGRoot::computeFloatRectForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer, FloatRect& paintInvalidationRect, const PaintInvalidationState* paintInvalidationState) const
378 // Apply our local transforms (except for x/y translation), then our shadow,
379 // and then call RenderBox's method to handle all the normal CSS Box model bits
380 paintInvalidationRect = m_localToBorderBoxTransform.mapRect(paintInvalidationRect);
382 // Apply initial viewport clip
383 if (shouldApplyViewportClip())
384 paintInvalidationRect.intersect(pixelSnappedBorderBoxRect());
386 LayoutRect rect = enclosingIntRect(paintInvalidationRect);
387 RenderReplaced::mapRectToPaintInvalidationBacking(paintInvalidationContainer, rect, paintInvalidationState);
388 paintInvalidationRect = rect;
391 // This method expects local CSS box coordinates.
392 // Callers with local SVG viewport coordinates should first apply the localToBorderBoxTransform
393 // to convert from SVG viewport coordinates to local CSS box coordinates.
394 void RenderSVGRoot::mapLocalToContainer(const RenderLayerModelObject* paintInvalidationContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed, const PaintInvalidationState* paintInvalidationState) const
396 ASSERT(mode & ~IsFixed); // We should have no fixed content in the SVG rendering tree.
397 // We used to have this ASSERT here, but we removed it when enabling layer squashing.
398 // See http://crbug.com/364901
399 // ASSERT(mode & UseTransforms); // mapping a point through SVG w/o respecting trasnforms is useless.
401 RenderReplaced::mapLocalToContainer(paintInvalidationContainer, transformState, mode | ApplyContainerFlip, wasFixed, paintInvalidationState);
404 const RenderObject* RenderSVGRoot::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
406 return RenderReplaced::pushMappingToContainer(ancestorToStopAt, geometryMap);
409 void RenderSVGRoot::updateCachedBoundaries()
411 SVGRenderSupport::computeContainerBoundingBoxes(this, m_objectBoundingBox, m_objectBoundingBoxValid, m_strokeBoundingBox, m_paintInvalidationBoundingBox);
412 SVGRenderSupport::intersectPaintInvalidationRectWithResources(this, m_paintInvalidationBoundingBox);
415 bool RenderSVGRoot::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
417 LayoutPoint pointInParent = locationInContainer.point() - toLayoutSize(accumulatedOffset);
418 LayoutPoint pointInBorderBox = pointInParent - toLayoutSize(location());
420 // Only test SVG content if the point is in our content box, or in case we
421 // don't clip to the viewport, the visual overflow rect.
422 // FIXME: This should be an intersection when rect-based hit tests are supported by nodeAtFloatPoint.
423 if (contentBoxRect().contains(pointInBorderBox) || (!shouldApplyViewportClip() && visualOverflowRect().contains(pointInBorderBox))) {
424 const AffineTransform& localToParentTransform = this->localToParentTransform();
425 if (localToParentTransform.isInvertible()) {
426 FloatPoint localPoint = localToParentTransform.inverse().mapPoint(FloatPoint(pointInParent));
428 for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
429 // FIXME: nodeAtFloatPoint() doesn't handle rect-based hit tests yet.
430 if (child->nodeAtFloatPoint(request, result, localPoint, hitTestAction)) {
431 updateHitTestResult(result, pointInBorderBox);
432 if (!result.addNodeToRectBasedTestResult(child->node(), request, locationInContainer))
439 // 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.
440 if ((hitTestAction == HitTestBlockBackground || hitTestAction == HitTestChildBlockBackground) && visibleToHitTestRequest(request)) {
441 // Only return true here, if the last hit testing phase 'BlockBackground' (or 'ChildBlockBackground' - depending on context) is executed.
442 // If we'd return true in the 'Foreground' phase, hit testing would stop immediately. For SVG only trees this doesn't matter.
443 // Though when we have a <foreignObject> subtree we need to be able to detect hits on the background of a <div> element.
444 // If we'd return true here in the 'Foreground' phase, we are not able to detect these hits anymore.
445 LayoutRect boundsRect(accumulatedOffset + location(), size());
446 if (locationInContainer.intersects(boundsRect)) {
447 updateHitTestResult(result, pointInBorderBox);
448 if (!result.addNodeToRectBasedTestResult(node(), request, locationInContainer, boundsRect))