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.
25 #include "RenderSVGRoot.h"
28 #include "ChromeClient.h"
30 #include "GraphicsContext.h"
31 #include "HitTestResult.h"
32 #include "LayoutRepainter.h"
34 #include "RenderIterator.h"
35 #include "RenderLayer.h"
36 #include "RenderNamedFlowFragment.h"
37 #include "RenderSVGResource.h"
38 #include "RenderSVGResourceContainer.h"
39 #include "RenderView.h"
41 #include "SVGLength.h"
42 #include "SVGRenderingContext.h"
43 #include "SVGResources.h"
44 #include "SVGResourcesCache.h"
45 #include "SVGSVGElement.h"
46 #include "SVGViewSpec.h"
47 #include "TransformState.h"
48 #include <wtf/StackStats.h>
51 #include "RenderSVGResourceFilter.h"
56 RenderSVGRoot::RenderSVGRoot(SVGSVGElement& element, PassRef<RenderStyle> style)
57 : RenderReplaced(element, WTF::move(style))
58 , m_objectBoundingBoxValid(false)
59 , m_isLayoutSizeChanged(false)
60 , m_needsBoundariesOrTransformUpdate(true)
61 , m_hasSVGShadow(false)
62 , m_hasBoxDecorations(false)
66 RenderSVGRoot::~RenderSVGRoot()
70 SVGSVGElement& RenderSVGRoot::svgSVGElement() const
72 return toSVGSVGElement(nodeForNonAnonymous());
75 void RenderSVGRoot::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio) const
77 // Spec: http://www.w3.org/TR/SVG/coords.html#IntrinsicSizing
78 // SVG needs to specify how to calculate some intrinsic sizing properties to enable inclusion within other languages.
80 // The intrinsic aspect ratio of the viewport of SVG content is necessary for example, when including SVG from an ‘object’
81 // element in HTML styled with CSS. It is possible (indeed, common) for an SVG graphic to have an intrinsic aspect ratio but
82 // not to have an intrinsic width or height. The intrinsic aspect ratio must be calculated based upon the following rules:
83 // - The aspect ratio is calculated by dividing a width by a height.
84 // - If the ‘width’ and ‘height’ of the rootmost ‘svg’ element are both specified with unit identifiers (in, mm, cm, pt, pc,
85 // px, em, ex) or in user units, then the aspect ratio is calculated from the ‘width’ and ‘height’ attributes after
86 // resolving both values to user units.
87 intrinsicSize.setWidth(floatValueForLength(svgSVGElement().intrinsicWidth(), 0));
88 intrinsicSize.setHeight(floatValueForLength(svgSVGElement().intrinsicHeight(), 0));
91 if (!intrinsicSize.isEmpty())
92 intrinsicRatio = intrinsicSize.width() / static_cast<double>(intrinsicSize.height());
94 // - If either/both of the ‘width’ and ‘height’ of the rootmost ‘svg’ element are in percentage units (or omitted), the
95 // aspect ratio is calculated from the width and height values of the ‘viewBox’ specified for the current SVG document
96 // fragment. If the ‘viewBox’ is not correctly specified, or set to 'none', the intrinsic aspect ratio cannot be
97 // calculated and is considered unspecified.
98 FloatSize viewBoxSize = svgSVGElement().viewBox().size();
99 if (!viewBoxSize.isEmpty()) {
100 // The viewBox can only yield an intrinsic ratio, not an intrinsic size.
101 intrinsicRatio = viewBoxSize.width() / static_cast<double>(viewBoxSize.height());
106 bool RenderSVGRoot::isEmbeddedThroughSVGImage() const
108 return isInSVGImage(&svgSVGElement());
111 bool RenderSVGRoot::isEmbeddedThroughFrameContainingSVGDocument() const
113 // If our frame has an owner renderer, we're embedded through eg. object/embed/iframe,
114 // but we only negotiate if we're in an SVG document.
115 if (!frame().ownerRenderer())
117 return frame().document()->isSVGDocument();
120 static inline LayoutUnit resolveLengthAttributeForSVG(const Length& length, float scale, float maxSize)
122 return valueForLength(length, maxSize) * (length.isFixed() ? scale : 1);
125 LayoutUnit RenderSVGRoot::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
127 // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
128 if (!m_containerSize.isEmpty())
129 return m_containerSize.width();
131 if (isEmbeddedThroughFrameContainingSVGDocument())
132 return containingBlock()->availableLogicalWidth();
134 if (style().logicalWidth().isSpecified() || style().logicalMaxWidth().isSpecified())
135 return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
137 if (svgSVGElement().hasIntrinsicWidth())
138 return resolveLengthAttributeForSVG(svgSVGElement().intrinsicWidth(), style().effectiveZoom(), containingBlock()->availableLogicalWidth());
140 // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
141 return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
144 LayoutUnit RenderSVGRoot::computeReplacedLogicalHeight() const
146 // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
147 if (!m_containerSize.isEmpty())
148 return m_containerSize.height();
150 if (isEmbeddedThroughFrameContainingSVGDocument())
151 return containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding);
153 if (style().logicalHeight().isSpecified() || style().logicalMaxHeight().isSpecified())
154 return RenderReplaced::computeReplacedLogicalHeight();
156 if (svgSVGElement().hasIntrinsicHeight())
157 return resolveLengthAttributeForSVG(svgSVGElement().intrinsicHeight(), style().effectiveZoom(), containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding).toFloat());
159 // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
160 return RenderReplaced::computeReplacedLogicalHeight();
163 void RenderSVGRoot::layout()
165 StackStats::LayoutCheckPoint layoutCheckPoint;
166 ASSERT(needsLayout());
168 m_resourcesNeedingToInvalidateClients.clear();
170 // Arbitrary affine transforms are incompatible with LayoutState.
171 LayoutStateDisabler layoutStateDisabler(&view());
173 bool needsLayout = selfNeedsLayout();
174 LayoutRepainter repainter(*this, checkForRepaintDuringLayout() && needsLayout);
176 LayoutSize oldSize = size();
177 updateLogicalWidth();
178 updateLogicalHeight();
179 buildLocalToBorderBoxTransform();
181 m_isLayoutSizeChanged = needsLayout || (svgSVGElement().hasRelativeLengths() && oldSize != size());
182 SVGRenderSupport::layoutChildren(*this, needsLayout || SVGRenderSupport::filtersForceContainerLayout(*this));
184 if (!m_resourcesNeedingToInvalidateClients.isEmpty()) {
185 // Invalidate resource clients, which may mark some nodes for layout.
186 HashSet<RenderSVGResourceContainer*>::iterator end = m_resourcesNeedingToInvalidateClients.end();
187 for (HashSet<RenderSVGResourceContainer*>::iterator it = m_resourcesNeedingToInvalidateClients.begin(); it != end; ++it)
188 (*it)->removeAllClientsFromCache();
190 m_isLayoutSizeChanged = false;
191 SVGRenderSupport::layoutChildren(*this, false);
194 // At this point LayoutRepainter already grabbed the old bounds,
195 // recalculate them now so repaintAfterLayout() uses the new bounds.
196 if (m_needsBoundariesOrTransformUpdate) {
197 updateCachedBoundaries();
198 m_needsBoundariesOrTransformUpdate = false;
201 if (!shouldApplyViewportClip()) {
202 FloatRect contentRepaintRect = repaintRectInLocalCoordinates();
203 contentRepaintRect = m_localToBorderBoxTransform.mapRect(contentRepaintRect);
204 addVisualOverflow(enclosingLayoutRect(contentRepaintRect));
207 updateLayerTransform();
208 m_hasBoxDecorations = isRoot() ? hasBoxDecorationStyle() : hasBoxDecorations();
209 invalidateBackgroundObscurationStatus();
211 repainter.repaintAfterLayout();
216 bool RenderSVGRoot::shouldApplyViewportClip() const
218 // the outermost svg is clipped if auto, and svg document roots are always clipped
219 // When the svg is stand-alone (isDocumentElement() == true) the viewport clipping should always
220 // be applied, noting that the window scrollbars should be hidden if overflow=hidden.
221 return style().overflowX() == OHIDDEN
222 || style().overflowX() == OAUTO
223 || style().overflowX() == OSCROLL
227 void RenderSVGRoot::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
229 // An empty viewport disables rendering.
230 if (pixelSnappedBorderBoxRect().isEmpty())
233 // Don't paint, if the context explicitly disabled it.
234 if (paintInfo.context->paintingDisabled())
237 // SVG outlines are painted during PaintPhaseForeground.
238 if (paintInfo.phase == PaintPhaseOutline || paintInfo.phase == PaintPhaseSelfOutline)
241 // An empty viewBox also disables rendering.
242 // (http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute)
243 if (svgSVGElement().hasEmptyViewBox())
246 Page* page = frame().page();
248 // Don't paint if we don't have kids, except if we have filters we should paint those.
250 auto* resources = SVGResourcesCache::cachedResourcesForRenderer(*this);
251 if (!resources || !resources->filter()) {
252 if (page && paintInfo.phase == PaintPhaseForeground)
253 page->addRelevantUnpaintedObject(this, visualOverflowRect());
258 if (page && paintInfo.phase == PaintPhaseForeground)
259 page->addRelevantRepaintedObject(this, visualOverflowRect());
261 // Make a copy of the PaintInfo because applyTransform will modify the damage rect.
262 PaintInfo childPaintInfo(paintInfo);
263 childPaintInfo.context->save();
265 // Apply initial viewport clip
266 if (shouldApplyViewportClip())
267 childPaintInfo.context->clip(snappedIntRect(overflowClipRect(paintOffset, currentRenderNamedFlowFragment())));
269 // Convert from container offsets (html renderers) to a relative transform (svg renderers).
270 // Transform from our paint container's coordinate system to our local coords.
271 IntPoint adjustedPaintOffset = roundedIntPoint(paintOffset);
272 childPaintInfo.applyTransform(AffineTransform::translation(adjustedPaintOffset.x(), adjustedPaintOffset.y()) * localToBorderBoxTransform());
274 // SVGRenderingContext must be destroyed before we restore the childPaintInfo.context, because a filter may have
275 // changed the context and it is only reverted when the SVGRenderingContext destructor finishes applying the filter.
277 SVGRenderingContext renderingContext;
278 bool continueRendering = true;
279 if (childPaintInfo.phase == PaintPhaseForeground) {
280 renderingContext.prepareToRenderSVGContent(*this, childPaintInfo);
281 continueRendering = renderingContext.isRenderingPrepared();
284 if (continueRendering) {
285 childPaintInfo.updateSubtreePaintRootForChildren(this);
286 for (auto& child : childrenOfType<RenderElement>(*this))
287 child.paint(childPaintInfo, location());
291 childPaintInfo.context->restore();
294 void RenderSVGRoot::willBeDestroyed()
296 RenderBlock::removePercentHeightDescendant(const_cast<RenderSVGRoot&>(*this));
298 SVGResourcesCache::clientDestroyed(*this);
299 RenderReplaced::willBeDestroyed();
302 void RenderSVGRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
304 if (diff == StyleDifferenceLayout)
305 setNeedsBoundariesUpdate();
306 RenderReplaced::styleDidChange(diff, oldStyle);
307 SVGResourcesCache::clientStyleChanged(*this, diff, style());
310 void RenderSVGRoot::addChild(RenderObject* child, RenderObject* beforeChild)
312 RenderReplaced::addChild(child, beforeChild);
313 SVGResourcesCache::clientWasAddedToTree(*child);
316 RenderObject* RenderSVGRoot::removeChild(RenderObject& child)
318 SVGResourcesCache::clientWillBeRemovedFromTree(child);
319 return RenderReplaced::removeChild(child);
322 // RenderBox methods will expect coordinates w/o any transforms in coordinates
323 // relative to our borderBox origin. This method gives us exactly that.
324 void RenderSVGRoot::buildLocalToBorderBoxTransform()
326 float scale = style().effectiveZoom();
327 SVGPoint translate = svgSVGElement().currentTranslate();
328 LayoutSize borderAndPadding(borderLeft() + paddingLeft(), borderTop() + paddingTop());
329 m_localToBorderBoxTransform = svgSVGElement().viewBoxToViewTransform(contentWidth() / scale, contentHeight() / scale);
330 if (borderAndPadding.isEmpty() && scale == 1 && translate == SVGPoint::zero())
332 m_localToBorderBoxTransform = AffineTransform(scale, 0, 0, scale, borderAndPadding.width() + translate.x(), borderAndPadding.height() + translate.y()) * m_localToBorderBoxTransform;
335 const AffineTransform& RenderSVGRoot::localToParentTransform() const
337 // Slightly optimized version of m_localToParentTransform = AffineTransform::translation(x(), y()) * m_localToBorderBoxTransform;
338 m_localToParentTransform = m_localToBorderBoxTransform;
340 m_localToParentTransform.setE(m_localToParentTransform.e() + roundToInt(x()));
342 m_localToParentTransform.setF(m_localToParentTransform.f() + roundToInt(y()));
343 return m_localToParentTransform;
346 LayoutRect RenderSVGRoot::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
348 return SVGRenderSupport::clippedOverflowRectForRepaint(*this, repaintContainer);
351 void RenderSVGRoot::computeFloatRectForRepaint(const RenderLayerModelObject* repaintContainer, FloatRect& repaintRect, bool fixed) const
353 // Apply our local transforms (except for x/y translation), then our shadow,
354 // and then call RenderBox's method to handle all the normal CSS Box model bits
355 repaintRect = m_localToBorderBoxTransform.mapRect(repaintRect);
357 const SVGRenderStyle& svgStyle = style().svgStyle();
358 if (const ShadowData* shadow = svgStyle.shadow())
359 shadow->adjustRectForShadow(repaintRect);
361 // Apply initial viewport clip
362 if (shouldApplyViewportClip())
363 repaintRect.intersect(pixelSnappedBorderBoxRect());
365 if (m_hasBoxDecorations || hasRenderOverflow()) {
366 // The selectionRect can project outside of the overflowRect, so take their union
367 // for repainting to avoid selection painting glitches.
368 LayoutRect decoratedRepaintRect = unionRect(localSelectionRect(false), visualOverflowRect());
369 repaintRect.unite(decoratedRepaintRect);
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_repaintBoundingBoxExcludingShadow);
396 SVGRenderSupport::intersectRepaintRectWithResources(*this, m_repaintBoundingBoxExcludingShadow);
397 m_repaintBoundingBoxExcludingShadow.inflate(horizontalBorderAndPaddingExtent());
399 m_repaintBoundingBox = m_repaintBoundingBoxExcludingShadow;
400 SVGRenderSupport::intersectRepaintRectWithShadows(*this, m_repaintBoundingBox);
403 bool RenderSVGRoot::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
405 LayoutPoint pointInParent = locationInContainer.point() - toLayoutSize(accumulatedOffset);
406 LayoutPoint pointInBorderBox = pointInParent - toLayoutSize(location());
408 // Only test SVG content if the point is in our content box.
409 // FIXME: This should be an intersection when rect-based hit tests are supported by nodeAtFloatPoint.
410 if (contentBoxRect().contains(pointInBorderBox)) {
411 FloatPoint localPoint = localToParentTransform().inverse().mapPoint(FloatPoint(pointInParent));
413 for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
414 // FIXME: nodeAtFloatPoint() doesn't handle rect-based hit tests yet.
415 if (child->nodeAtFloatPoint(request, result, localPoint, hitTestAction)) {
416 updateHitTestResult(result, pointInBorderBox);
417 if (!result.addNodeToRectBasedTestResult(child->node(), request, locationInContainer))
423 // 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.
424 if (hitTestAction == HitTestBlockBackground && visibleToHitTesting()) {
425 // Only return true here, if the last hit testing phase 'BlockBackground' is executed. If we'd return true in the 'Foreground' phase,
426 // hit testing would stop immediately. For SVG only trees this doesn't matter. Though when we have a <foreignObject> subtree we need
427 // 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
428 // to detect these hits anymore.
429 LayoutRect boundsRect(accumulatedOffset + location(), size());
430 if (locationInContainer.intersects(boundsRect)) {
431 updateHitTestResult(result, pointInBorderBox);
432 if (!result.addNodeToRectBasedTestResult(&svgSVGElement(), request, locationInContainer, boundsRect))
440 bool RenderSVGRoot::hasRelativeDimensions() const
442 return svgSVGElement().intrinsicHeight().isPercent() || svgSVGElement().intrinsicWidth().isPercent();
445 void RenderSVGRoot::addResourceForClientInvalidation(RenderSVGResourceContainer* resource)
447 RenderObject* svgRoot = resource->parent();
448 while (svgRoot && !svgRoot->isSVGRoot())
449 svgRoot = svgRoot->parent();
452 toRenderSVGRoot(svgRoot)->m_resourcesNeedingToInvalidateClients.add(resource);