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 "RenderSVGResourceFilter.h"
40 #include "RenderView.h"
42 #include "SVGLength.h"
43 #include "SVGRenderingContext.h"
44 #include "SVGResources.h"
45 #include "SVGResourcesCache.h"
46 #include "SVGSVGElement.h"
47 #include "SVGViewSpec.h"
48 #include "TransformState.h"
49 #include <wtf/StackStats.h>
53 RenderSVGRoot::RenderSVGRoot(SVGSVGElement& element, Ref<RenderStyle>&& style)
54 : RenderReplaced(element, WTF::move(style))
55 , m_objectBoundingBoxValid(false)
56 , m_isLayoutSizeChanged(false)
57 , m_needsBoundariesOrTransformUpdate(true)
58 , m_hasSVGShadow(false)
59 , m_hasBoxDecorations(false)
63 RenderSVGRoot::~RenderSVGRoot()
67 SVGSVGElement& RenderSVGRoot::svgSVGElement() const
69 return downcast<SVGSVGElement>(nodeForNonAnonymous());
72 void RenderSVGRoot::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio) const
74 // Spec: http://www.w3.org/TR/SVG/coords.html#IntrinsicSizing
75 // SVG needs to specify how to calculate some intrinsic sizing properties to enable inclusion within other languages.
77 // The intrinsic aspect ratio of the viewport of SVG content is necessary for example, when including SVG from an ‘object’
78 // element in HTML styled with CSS. It is possible (indeed, common) for an SVG graphic to have an intrinsic aspect ratio but
79 // not to have an intrinsic width or height. The intrinsic aspect ratio must be calculated based upon the following rules:
80 // - The aspect ratio is calculated by dividing a width by a height.
81 // - If the ‘width’ and ‘height’ of the rootmost ‘svg’ element are both specified with unit identifiers (in, mm, cm, pt, pc,
82 // px, em, ex) or in user units, then the aspect ratio is calculated from the ‘width’ and ‘height’ attributes after
83 // resolving both values to user units.
84 intrinsicSize.setWidth(floatValueForLength(svgSVGElement().intrinsicWidth(), 0));
85 intrinsicSize.setHeight(floatValueForLength(svgSVGElement().intrinsicHeight(), 0));
88 if (!intrinsicSize.isEmpty())
89 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 FloatSize viewBoxSize = svgSVGElement().viewBox().size();
96 if (!viewBoxSize.isEmpty()) {
97 // The viewBox can only yield an intrinsic ratio, not an intrinsic size.
98 intrinsicRatio = viewBoxSize.width() / static_cast<double>(viewBoxSize.height());
103 bool RenderSVGRoot::isEmbeddedThroughSVGImage() const
105 return isInSVGImage(&svgSVGElement());
108 bool RenderSVGRoot::isEmbeddedThroughFrameContainingSVGDocument() const
110 // If our frame has an owner renderer, we're embedded through eg. object/embed/iframe,
111 // but we only negotiate if we're in an SVG document.
112 if (!frame().ownerRenderer())
114 return frame().document()->isSVGDocument();
117 static inline LayoutUnit resolveLengthAttributeForSVG(const Length& length, float scale, float maxSize)
119 return valueForLength(length, maxSize) * (length.isFixed() ? scale : 1);
122 LayoutUnit RenderSVGRoot::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
124 // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
125 if (!m_containerSize.isEmpty())
126 return m_containerSize.width();
128 if (isEmbeddedThroughFrameContainingSVGDocument())
129 return containingBlock()->availableLogicalWidth();
131 if (style().logicalWidth().isSpecified() || style().logicalMaxWidth().isSpecified())
132 return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
134 if (svgSVGElement().hasIntrinsicWidth())
135 return resolveLengthAttributeForSVG(svgSVGElement().intrinsicWidth(), style().effectiveZoom(), containingBlock()->availableLogicalWidth());
137 // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
138 return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
141 LayoutUnit RenderSVGRoot::computeReplacedLogicalHeight() const
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.height();
147 if (isEmbeddedThroughFrameContainingSVGDocument())
148 return containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding);
150 if (style().logicalHeight().isSpecified() || style().logicalMaxHeight().isSpecified())
151 return RenderReplaced::computeReplacedLogicalHeight();
153 if (svgSVGElement().hasIntrinsicHeight())
154 return resolveLengthAttributeForSVG(svgSVGElement().intrinsicHeight(), style().effectiveZoom(), containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding).toFloat());
156 // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
157 return RenderReplaced::computeReplacedLogicalHeight();
160 void RenderSVGRoot::layout()
162 StackStats::LayoutCheckPoint layoutCheckPoint;
163 ASSERT(needsLayout());
165 m_resourcesNeedingToInvalidateClients.clear();
167 // Arbitrary affine transforms are incompatible with LayoutState.
168 LayoutStateDisabler layoutStateDisabler(view());
170 bool needsLayout = selfNeedsLayout();
171 LayoutRepainter repainter(*this, checkForRepaintDuringLayout() && needsLayout);
173 LayoutSize oldSize = size();
174 updateLogicalWidth();
175 updateLogicalHeight();
176 buildLocalToBorderBoxTransform();
178 m_isLayoutSizeChanged = needsLayout || (svgSVGElement().hasRelativeLengths() && oldSize != size());
179 SVGRenderSupport::layoutChildren(*this, needsLayout || SVGRenderSupport::filtersForceContainerLayout(*this));
181 if (!m_resourcesNeedingToInvalidateClients.isEmpty()) {
182 // Invalidate resource clients, which may mark some nodes for layout.
183 HashSet<RenderSVGResourceContainer*>::iterator end = m_resourcesNeedingToInvalidateClients.end();
184 for (HashSet<RenderSVGResourceContainer*>::iterator it = m_resourcesNeedingToInvalidateClients.begin(); it != end; ++it)
185 (*it)->removeAllClientsFromCache();
187 m_isLayoutSizeChanged = false;
188 SVGRenderSupport::layoutChildren(*this, false);
191 // At this point LayoutRepainter already grabbed the old bounds,
192 // recalculate them now so repaintAfterLayout() uses the new bounds.
193 if (m_needsBoundariesOrTransformUpdate) {
194 updateCachedBoundaries();
195 m_needsBoundariesOrTransformUpdate = false;
198 if (!shouldApplyViewportClip()) {
199 FloatRect contentRepaintRect = repaintRectInLocalCoordinates();
200 contentRepaintRect = m_localToBorderBoxTransform.mapRect(contentRepaintRect);
201 addVisualOverflow(enclosingLayoutRect(contentRepaintRect));
204 updateLayerTransform();
205 m_hasBoxDecorations = isRoot() ? hasBoxDecorationStyle() : hasBoxDecorations();
206 invalidateBackgroundObscurationStatus();
208 repainter.repaintAfterLayout();
213 bool RenderSVGRoot::shouldApplyViewportClip() const
215 // the outermost svg is clipped if auto, and svg document roots are always clipped
216 // When the svg is stand-alone (isDocumentElement() == true) the viewport clipping should always
217 // be applied, noting that the window scrollbars should be hidden if overflow=hidden.
218 return style().overflowX() == OHIDDEN
219 || style().overflowX() == OAUTO
220 || style().overflowX() == OSCROLL
224 void RenderSVGRoot::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
226 // An empty viewport disables rendering.
227 if (borderBoxRect().isEmpty())
230 // Don't paint, if the context explicitly disabled it.
231 if (paintInfo.context().paintingDisabled())
234 // SVG outlines are painted during PaintPhaseForeground.
235 if (paintInfo.phase == PaintPhaseOutline || paintInfo.phase == PaintPhaseSelfOutline)
238 // An empty viewBox also disables rendering.
239 // (http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute)
240 if (svgSVGElement().hasEmptyViewBox())
243 Page* page = frame().page();
245 // Don't paint if we don't have kids, except if we have filters we should paint those.
247 auto* resources = SVGResourcesCache::cachedResourcesForRenderer(*this);
248 if (!resources || !resources->filter()) {
249 if (page && paintInfo.phase == PaintPhaseForeground)
250 page->addRelevantUnpaintedObject(this, visualOverflowRect());
255 if (page && paintInfo.phase == PaintPhaseForeground)
256 page->addRelevantRepaintedObject(this, visualOverflowRect());
258 // Make a copy of the PaintInfo because applyTransform will modify the damage rect.
259 PaintInfo childPaintInfo(paintInfo);
260 childPaintInfo.context().save();
262 // Apply initial viewport clip
263 if (shouldApplyViewportClip())
264 childPaintInfo.context().clip(snappedIntRect(overflowClipRect(paintOffset, currentRenderNamedFlowFragment())));
266 // Convert from container offsets (html renderers) to a relative transform (svg renderers).
267 // Transform from our paint container's coordinate system to our local coords.
268 IntPoint adjustedPaintOffset = roundedIntPoint(paintOffset);
269 childPaintInfo.applyTransform(AffineTransform::translation(adjustedPaintOffset.x(), adjustedPaintOffset.y()) * localToBorderBoxTransform());
271 // SVGRenderingContext must be destroyed before we restore the childPaintInfo.context(), because a filter may have
272 // changed the context and it is only reverted when the SVGRenderingContext destructor finishes applying the filter.
274 SVGRenderingContext renderingContext;
275 bool continueRendering = true;
276 if (childPaintInfo.phase == PaintPhaseForeground) {
277 renderingContext.prepareToRenderSVGContent(*this, childPaintInfo);
278 continueRendering = renderingContext.isRenderingPrepared();
281 if (continueRendering) {
282 childPaintInfo.updateSubtreePaintRootForChildren(this);
283 for (auto& child : childrenOfType<RenderElement>(*this))
284 child.paint(childPaintInfo, location());
288 childPaintInfo.context().restore();
291 void RenderSVGRoot::willBeDestroyed()
293 RenderBlock::removePercentHeightDescendant(const_cast<RenderSVGRoot&>(*this));
295 SVGResourcesCache::clientDestroyed(*this);
296 RenderReplaced::willBeDestroyed();
299 void RenderSVGRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
301 if (diff == StyleDifferenceLayout)
302 setNeedsBoundariesUpdate();
304 // Box decorations may have appeared/disappeared - recompute status.
305 if (diff == StyleDifferenceRepaint)
306 m_hasBoxDecorations = hasBoxDecorationStyle();
308 RenderReplaced::styleDidChange(diff, oldStyle);
309 SVGResourcesCache::clientStyleChanged(*this, diff, style());
312 void RenderSVGRoot::addChild(RenderObject* child, RenderObject* beforeChild)
314 RenderReplaced::addChild(child, beforeChild);
315 SVGResourcesCache::clientWasAddedToTree(*child);
318 void RenderSVGRoot::removeChild(RenderObject& child)
320 SVGResourcesCache::clientWillBeRemovedFromTree(child);
321 RenderReplaced::removeChild(child);
324 // RenderBox methods will expect coordinates w/o any transforms in coordinates
325 // relative to our borderBox origin. This method gives us exactly that.
326 void RenderSVGRoot::buildLocalToBorderBoxTransform()
328 float scale = style().effectiveZoom();
329 SVGPoint translate = svgSVGElement().currentTranslate();
330 LayoutSize borderAndPadding(borderLeft() + paddingLeft(), borderTop() + paddingTop());
331 m_localToBorderBoxTransform = svgSVGElement().viewBoxToViewTransform(contentWidth() / scale, contentHeight() / scale);
332 if (borderAndPadding.isEmpty() && scale == 1 && translate == SVGPoint::zero())
334 m_localToBorderBoxTransform = AffineTransform(scale, 0, 0, scale, borderAndPadding.width() + translate.x(), borderAndPadding.height() + translate.y()) * m_localToBorderBoxTransform;
337 const AffineTransform& RenderSVGRoot::localToParentTransform() const
339 // Slightly optimized version of m_localToParentTransform = AffineTransform::translation(x(), y()) * m_localToBorderBoxTransform;
340 m_localToParentTransform = m_localToBorderBoxTransform;
342 m_localToParentTransform.setE(m_localToParentTransform.e() + roundToInt(x()));
344 m_localToParentTransform.setF(m_localToParentTransform.f() + roundToInt(y()));
345 return m_localToParentTransform;
348 LayoutRect RenderSVGRoot::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
350 if (style().visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent())
353 FloatRect contentRepaintRect = m_localToBorderBoxTransform.mapRect(repaintRectInLocalCoordinates());
354 contentRepaintRect.intersect(snappedIntRect(borderBoxRect()));
356 LayoutRect repaintRect = enclosingLayoutRect(contentRepaintRect);
357 if (m_hasBoxDecorations || hasRenderOverflow())
358 repaintRect.unite(unionRect(localSelectionRect(false), visualOverflowRect()));
360 return RenderReplaced::computeRectForRepaint(enclosingIntRect(repaintRect), repaintContainer);
363 FloatRect RenderSVGRoot::computeFloatRectForRepaint(const FloatRect& repaintRect, const RenderLayerModelObject* repaintContainer, 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 FloatRect adjustedRect = m_localToBorderBoxTransform.mapRect(repaintRect);
369 const SVGRenderStyle& svgStyle = style().svgStyle();
370 if (const ShadowData* shadow = svgStyle.shadow())
371 shadow->adjustRectForShadow(adjustedRect);
373 // Apply initial viewport clip
374 if (shouldApplyViewportClip())
375 adjustedRect.intersect(snappedIntRect(borderBoxRect()));
377 if (m_hasBoxDecorations || hasRenderOverflow()) {
378 // The selectionRect can project outside of the overflowRect, so take their union
379 // for repainting to avoid selection painting glitches.
380 LayoutRect decoratedRepaintRect = unionRect(localSelectionRect(false), visualOverflowRect());
381 adjustedRect.unite(decoratedRepaintRect);
383 return RenderReplaced::computeRectForRepaint(enclosingIntRect(adjustedRect), repaintContainer, fixed);
386 // This method expects local CSS box coordinates.
387 // Callers with local SVG viewport coordinates should first apply the localToBorderBoxTransform
388 // to convert from SVG viewport coordinates to local CSS box coordinates.
389 void RenderSVGRoot::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
391 ASSERT(mode & ~IsFixed); // We should have no fixed content in the SVG rendering tree.
392 ASSERT(mode & UseTransforms); // mapping a point through SVG w/o respecting trasnforms is useless.
394 RenderReplaced::mapLocalToContainer(repaintContainer, transformState, mode | ApplyContainerFlip, wasFixed);
397 const RenderObject* RenderSVGRoot::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
399 return RenderReplaced::pushMappingToContainer(ancestorToStopAt, geometryMap);
402 void RenderSVGRoot::updateCachedBoundaries()
404 SVGRenderSupport::computeContainerBoundingBoxes(*this, m_objectBoundingBox, m_objectBoundingBoxValid, m_strokeBoundingBox, m_repaintBoundingBoxExcludingShadow);
405 SVGRenderSupport::intersectRepaintRectWithResources(*this, m_repaintBoundingBoxExcludingShadow);
406 m_repaintBoundingBoxExcludingShadow.inflate(horizontalBorderAndPaddingExtent());
408 m_repaintBoundingBox = m_repaintBoundingBoxExcludingShadow;
409 SVGRenderSupport::intersectRepaintRectWithShadows(*this, m_repaintBoundingBox);
412 bool RenderSVGRoot::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
414 LayoutPoint pointInParent = locationInContainer.point() - toLayoutSize(accumulatedOffset);
415 LayoutPoint pointInBorderBox = pointInParent - toLayoutSize(location());
417 // Only test SVG content if the point is in our content box.
418 // FIXME: This should be an intersection when rect-based hit tests are supported by nodeAtFloatPoint.
419 if (contentBoxRect().contains(pointInBorderBox)) {
420 FloatPoint localPoint = localToParentTransform().inverse().mapPoint(FloatPoint(pointInParent));
422 for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
423 // FIXME: nodeAtFloatPoint() doesn't handle rect-based hit tests yet.
424 if (child->nodeAtFloatPoint(request, result, localPoint, hitTestAction)) {
425 updateHitTestResult(result, pointInBorderBox);
426 if (!result.addNodeToRectBasedTestResult(child->node(), request, locationInContainer))
432 // 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.
433 if (hitTestAction == HitTestBlockBackground && visibleToHitTesting()) {
434 // Only return true here, if the last hit testing phase 'BlockBackground' is executed. If we'd return true in the 'Foreground' phase,
435 // hit testing would stop immediately. For SVG only trees this doesn't matter. Though when we have a <foreignObject> subtree we need
436 // 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
437 // to detect these hits anymore.
438 LayoutRect boundsRect(accumulatedOffset + location(), size());
439 if (locationInContainer.intersects(boundsRect)) {
440 updateHitTestResult(result, pointInBorderBox);
441 if (!result.addNodeToRectBasedTestResult(&svgSVGElement(), request, locationInContainer, boundsRect))
449 bool RenderSVGRoot::hasRelativeDimensions() const
451 return svgSVGElement().intrinsicHeight().isPercentOrCalculated() || svgSVGElement().intrinsicWidth().isPercentOrCalculated();
454 void RenderSVGRoot::addResourceForClientInvalidation(RenderSVGResourceContainer* resource)
456 RenderElement* svgRoot = resource->parent();
457 while (svgRoot && !is<RenderSVGRoot>(*svgRoot))
458 svgRoot = svgRoot->parent();
461 downcast<RenderSVGRoot>(*svgRoot).m_resourcesNeedingToInvalidateClients.add(resource);