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.
27 #include "RenderSVGRoot.h"
30 #include "ChromeClient.h"
32 #include "GraphicsContext.h"
33 #include "HitTestResult.h"
34 #include "LayoutRepainter.h"
36 #include "RenderPart.h"
37 #include "RenderSVGContainer.h"
38 #include "RenderSVGResource.h"
39 #include "RenderView.h"
40 #include "SVGLength.h"
41 #include "SVGRenderSupport.h"
42 #include "SVGResources.h"
43 #include "SVGResourcesCache.h"
44 #include "SVGSVGElement.h"
45 #include "SVGStyledElement.h"
46 #include "SVGViewSpec.h"
47 #include "TransformState.h"
50 #include "RenderSVGResourceFilter.h"
57 RenderSVGRoot::RenderSVGRoot(SVGStyledElement* node)
58 : RenderReplaced(node)
59 , m_isLayoutSizeChanged(false)
60 , m_needsBoundariesOrTransformUpdate(true)
64 RenderSVGRoot::~RenderSVGRoot()
68 void RenderSVGRoot::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio, bool& isPercentageIntrinsicSize) const
70 // Spec: http://www.w3.org/TR/SVG/coords.html#IntrinsicSizing
71 // SVG needs to specify how to calculate some intrinsic sizing properties to enable inclusion within other languages.
72 // The intrinsic width and height of the viewport of SVG content must be determined from the ‘width’ and ‘height’ attributes.
73 // If either of these are not specified, a value of '100%' must be assumed. Note: the ‘width’ and ‘height’ attributes are not
74 // the same as the CSS width and height properties. Specifically, percentage values do not provide an intrinsic width or height,
75 // and do not indicate a percentage of the containing block. Rather, once the viewport is established, they indicate the portion
76 // of the viewport that is actually covered by image data.
77 SVGSVGElement* svg = static_cast<SVGSVGElement*>(node());
78 Length intrinsicWidthAttribute = svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties);
79 Length intrinsicHeightAttribute = svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties);
81 // The intrinsic aspect ratio of the viewport of SVG content is necessary for example, when including SVG from an ‘object’
82 // element in HTML styled with CSS. It is possible (indeed, common) for an SVG graphic to have an intrinsic aspect ratio but
83 // not to have an intrinsic width or height. The intrinsic aspect ratio must be calculated based upon the following rules:
84 // - The aspect ratio is calculated by dividing a width by a height.
85 // - If the ‘width’ and ‘height’ of the rootmost ‘svg’ element are both specified with unit identifiers (in, mm, cm, pt, pc,
86 // px, em, ex) or in user units, then the aspect ratio is calculated from the ‘width’ and ‘height’ attributes after
87 // resolving both values to user units.
88 if (intrinsicWidthAttribute.isFixed() || intrinsicHeightAttribute.isFixed()) {
89 if (intrinsicWidthAttribute.isFixed())
90 intrinsicSize.setWidth(intrinsicWidthAttribute.calcFloatValue(0));
91 if (intrinsicHeightAttribute.isFixed())
92 intrinsicSize.setHeight(intrinsicHeightAttribute.calcFloatValue(0));
93 if (!intrinsicSize.isEmpty())
94 intrinsicRatio = intrinsicSize.width() / static_cast<double>(intrinsicSize.height());
98 // - If either/both of the ‘width’ and ‘height’ of the rootmost ‘svg’ element are in percentage units (or omitted), the
99 // aspect ratio is calculated from the width and height values of the ‘viewBox’ specified for the current SVG document
100 // fragment. If the ‘viewBox’ is not correctly specified, or set to 'none', the intrinsic aspect ratio cannot be
101 // calculated and is considered unspecified.
102 intrinsicSize = svg->viewBox().size();
103 if (!intrinsicSize.isEmpty()) {
104 // The viewBox can only yield an intrinsic ratio, not an intrinsic size.
105 intrinsicRatio = intrinsicSize.width() / static_cast<double>(intrinsicSize.height());
106 intrinsicSize = FloatSize();
110 // If our intrinsic size is in percentage units, return those to the caller through the intrinsicSize. Notify the caller
111 // about the special situation, by setting isPercentageIntrinsicSize=true, so it knows how to interpret the return values.
112 if (intrinsicWidthAttribute.isPercent() && intrinsicHeightAttribute.isPercent()) {
113 isPercentageIntrinsicSize = true;
114 intrinsicSize = FloatSize(intrinsicWidthAttribute.percent(), intrinsicHeightAttribute.percent());
118 bool RenderSVGRoot::isEmbeddedThroughSVGImage() const
123 Frame* frame = node()->document()->frame();
127 // Test whether we're embedded through an img.
128 if (!frame->page() || !frame->page()->chrome())
131 ChromeClient* chromeClient = frame->page()->chrome()->client();
132 if (!chromeClient || !chromeClient->isSVGImageChromeClient())
138 bool RenderSVGRoot::isEmbeddedThroughFrameContainingSVGDocument() const
143 Frame* frame = node()->document()->frame();
147 // If our frame has an owner renderer, we're embedded through eg. object/embed/iframe,
148 // but we only negotiate if we're in an SVG document.
149 if (!frame->ownerRenderer())
151 return frame->document()->isSVGDocument();
154 static inline LayoutUnit resolveLengthAttributeForSVG(const Length& length, float scale, float maxSize)
156 return static_cast<LayoutUnit>(length.calcValue(maxSize) * (length.isFixed() ? scale : 1));
159 LayoutUnit RenderSVGRoot::computeReplacedLogicalWidth(bool includeMaxWidth) const
161 SVGSVGElement* svg = static_cast<SVGSVGElement*>(node());
164 // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
165 if (!m_containerSize.isEmpty())
166 return m_containerSize.width();
168 if (style()->logicalWidth().isSpecified())
169 return RenderReplaced::computeReplacedLogicalWidth(includeMaxWidth);
171 if (svg->widthAttributeEstablishesViewport())
172 return resolveLengthAttributeForSVG(svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties), style()->effectiveZoom(), containingBlock()->availableLogicalWidth());
174 // Only SVGs embedded in <object> reach this point.
175 ASSERT(isEmbeddedThroughFrameContainingSVGDocument());
176 return document()->frame()->ownerRenderer()->availableLogicalWidth();
179 LayoutUnit RenderSVGRoot::computeReplacedLogicalHeight() const
181 SVGSVGElement* svg = static_cast<SVGSVGElement*>(node());
184 // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
185 if (!m_containerSize.isEmpty())
186 return m_containerSize.height();
188 if (hasReplacedLogicalHeight())
189 return RenderReplaced::computeReplacedLogicalHeight();
191 if (svg->heightAttributeEstablishesViewport())
192 return resolveLengthAttributeForSVG(svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties), style()->effectiveZoom(), containingBlock()->availableLogicalHeight());
194 // Only SVGs embedded in <object> reach this point.
195 ASSERT(isEmbeddedThroughFrameContainingSVGDocument());
196 return document()->frame()->ownerRenderer()->availableLogicalHeight();
199 void RenderSVGRoot::layout()
201 ASSERT(needsLayout());
203 // Arbitrary affine transforms are incompatible with LayoutState.
204 LayoutStateDisabler layoutStateDisabler(view());
206 bool needsLayout = selfNeedsLayout();
207 LayoutRepainter repainter(*this, checkForRepaintDuringLayout() && needsLayout);
209 LayoutSize oldSize(width(), height());
210 computeLogicalWidth();
211 computeLogicalHeight();
212 buildLocalToBorderBoxTransform();
214 SVGSVGElement* svg = static_cast<SVGSVGElement*>(node());
215 m_isLayoutSizeChanged = needsLayout || (svg->hasRelativeLengths() && oldSize != size());
216 SVGRenderSupport::layoutChildren(this, needsLayout || SVGRenderSupport::filtersForceContainerLayout(this));
217 m_isLayoutSizeChanged = false;
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 repainter.repaintAfterLayout();
228 setNeedsLayout(false);
231 void RenderSVGRoot::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& adjustedPaintOffset)
233 // An empty viewport disables rendering.
234 if (borderBoxRect().isEmpty())
237 // Don't paint, if the context explicitely disabled it.
238 if (paintInfo.context->paintingDisabled())
241 // Don't paint if we don't have kids, except if we have filters we should paint those.
243 SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(this);
244 if (!resources || !resources->filter())
248 if (Frame* frame = this->frame()) {
249 if (Page* page = frame->page())
250 page->addRelevantRepaintedObject(this, paintInfo.rect);
253 // Make a copy of the PaintInfo because applyTransform will modify the damage rect.
254 PaintInfo childPaintInfo(paintInfo);
255 childPaintInfo.context->save();
257 // Apply initial viewport clip - not affected by overflow handling
258 childPaintInfo.context->clip(overflowClipRect(adjustedPaintOffset, paintInfo.renderRegion));
260 // Convert from container offsets (html renderers) to a relative transform (svg renderers).
261 // Transform from our paint container's coordinate system to our local coords.
262 childPaintInfo.applyTransform(AffineTransform::translation(adjustedPaintOffset.x() - x(), adjustedPaintOffset.y() - y()) * localToParentTransform());
264 bool continueRendering = true;
265 if (childPaintInfo.phase == PaintPhaseForeground)
266 continueRendering = SVGRenderSupport::prepareToRenderSVGContent(this, childPaintInfo);
268 if (continueRendering)
269 RenderBox::paint(childPaintInfo, LayoutPoint());
271 if (childPaintInfo.phase == PaintPhaseForeground)
272 SVGRenderSupport::finishRenderSVGContent(this, childPaintInfo, paintInfo.context);
274 childPaintInfo.context->restore();
277 void RenderSVGRoot::willBeDestroyed()
279 SVGResourcesCache::clientDestroyed(this);
280 RenderReplaced::willBeDestroyed();
283 void RenderSVGRoot::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
285 if (diff == StyleDifferenceLayout)
286 setNeedsBoundariesUpdate();
287 RenderReplaced::styleWillChange(diff, newStyle);
290 void RenderSVGRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
292 RenderReplaced::styleDidChange(diff, oldStyle);
293 SVGResourcesCache::clientStyleChanged(this, diff, style());
296 void RenderSVGRoot::updateFromElement()
298 RenderReplaced::updateFromElement();
299 SVGResourcesCache::clientUpdatedFromElement(this, style());
302 // RenderBox methods will expect coordinates w/o any transforms in coordinates
303 // relative to our borderBox origin. This method gives us exactly that.
304 void RenderSVGRoot::buildLocalToBorderBoxTransform()
306 SVGSVGElement* svg = static_cast<SVGSVGElement*>(node());
307 float scale = style()->effectiveZoom();
308 FloatPoint translate = svg->currentTranslate();
309 LayoutSize borderAndPadding(borderLeft() + paddingLeft(), borderTop() + paddingTop());
310 m_localToBorderBoxTransform = svg->viewBoxToViewTransform(width() / scale, height() / scale);
311 if (borderAndPadding.isEmpty() && scale == 1 && translate == FloatPoint::zero())
313 m_localToBorderBoxTransform = AffineTransform(scale, 0, 0, scale, borderAndPadding.width() + translate.x(), borderAndPadding.height() + translate.y()) * m_localToBorderBoxTransform;
316 const AffineTransform& RenderSVGRoot::localToParentTransform() const
318 // Slightly optimized version of m_localToParentTransform = AffineTransform::translation(x(), y()) * m_localToBorderBoxTransform;
319 m_localToParentTransform = m_localToBorderBoxTransform;
321 m_localToParentTransform.setE(m_localToParentTransform.e() + x());
323 m_localToParentTransform.setF(m_localToParentTransform.f() + y());
324 return m_localToParentTransform;
327 LayoutRect RenderSVGRoot::clippedOverflowRectForRepaint(RenderBoxModelObject* repaintContainer) const
329 return SVGRenderSupport::clippedOverflowRectForRepaint(this, repaintContainer);
332 void RenderSVGRoot::computeFloatRectForRepaint(RenderBoxModelObject* repaintContainer, FloatRect& repaintRect, bool fixed) const
334 // Apply our local transforms (except for x/y translation), then our shadow,
335 // and then call RenderBox's method to handle all the normal CSS Box model bits
336 repaintRect = m_localToBorderBoxTransform.mapRect(repaintRect);
338 // Apply initial viewport clip - not affected by overflow settings
339 repaintRect.intersect(borderBoxRect());
341 const SVGRenderStyle* svgStyle = style()->svgStyle();
342 if (const ShadowData* shadow = svgStyle->shadow())
343 shadow->adjustRectForShadow(repaintRect);
345 LayoutRect rect = enclosingIntRect(repaintRect);
346 RenderReplaced::computeRectForRepaint(repaintContainer, rect, fixed);
350 void RenderSVGRoot::mapLocalToContainer(RenderBoxModelObject* repaintContainer, bool fixed, bool useTransforms, TransformState& transformState, bool* wasFixed) const
352 ASSERT(!fixed); // We should have no fixed content in the SVG rendering tree.
353 ASSERT(useTransforms); // mapping a point through SVG w/o respecting trasnforms is useless.
355 // Transform to our border box and let RenderBox transform the rest of the way.
356 transformState.applyTransform(m_localToBorderBoxTransform);
357 RenderReplaced::mapLocalToContainer(repaintContainer, fixed, useTransforms, transformState, wasFixed);
360 void RenderSVGRoot::updateCachedBoundaries()
362 m_objectBoundingBox = FloatRect();
363 m_strokeBoundingBox = FloatRect();
364 m_repaintBoundingBox = FloatRect();
366 SVGRenderSupport::computeContainerBoundingBoxes(this, m_objectBoundingBox, m_strokeBoundingBox, m_repaintBoundingBox);
367 SVGRenderSupport::intersectRepaintRectWithResources(this, m_repaintBoundingBox);
368 m_repaintBoundingBox.inflate(borderAndPaddingWidth());
371 bool RenderSVGRoot::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
373 LayoutPoint pointInParent = pointInContainer - toLayoutSize(accumulatedOffset);
374 LayoutPoint pointInBorderBox(pointInParent.x() - x(), pointInParent.y() - y());
376 // Note: For now, we're ignoring hits to border and padding for <svg>
377 if (!contentBoxRect().contains(pointInBorderBox))
380 LayoutPoint localPoint = localToParentTransform().inverse().mapPoint(pointInParent);
382 for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
383 if (child->nodeAtFloatPoint(request, result, localPoint, hitTestAction)) {
384 // FIXME: CSS/HTML assumes the local point is relative to the border box, right?
385 updateHitTestResult(result, pointInBorderBox);
386 // FIXME: nodeAtFloatPoint() doesn't handle rect-based hit tests yet.
387 result.addNodeToRectBasedTestResult(child->node(), pointInContainer);
392 // 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.
393 if (hitTestAction == HitTestBlockBackground && style()->pointerEvents() != PE_NONE) {
394 // Only return true here, if the last hit testing phase 'BlockBackground' is executed. If we'd return true in the 'Foreground' phase,
395 // hit testing would stop immediately. For SVG only trees this doesn't matter. Though when we have a <foreignObject> subtree we need
396 // 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
397 // to detect these hits anymore.
398 updateHitTestResult(result, roundedLayoutPoint(localPoint));
407 #endif // ENABLE(SVG)