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));
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 repainter.repaintAfterLayout();
227 setNeedsLayout(false);
230 void RenderSVGRoot::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& adjustedPaintOffset)
232 // An empty viewport disables rendering.
233 if (borderBoxRect().isEmpty())
236 // Don't paint, if the context explicitely disabled it.
237 if (paintInfo.context->paintingDisabled())
240 // Don't paint if we don't have kids, except if we have filters we should paint those.
242 SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(this);
243 if (!resources || !resources->filter())
247 if (Frame* frame = this->frame()) {
248 if (Page* page = frame->page())
249 page->addRelevantRepaintedObject(this, paintInfo.rect);
252 // Make a copy of the PaintInfo because applyTransform will modify the damage rect.
253 PaintInfo childPaintInfo(paintInfo);
254 childPaintInfo.context->save();
256 // Apply initial viewport clip - not affected by overflow handling
257 childPaintInfo.context->clip(overflowClipRect(adjustedPaintOffset, paintInfo.renderRegion));
259 // Convert from container offsets (html renderers) to a relative transform (svg renderers).
260 // Transform from our paint container's coordinate system to our local coords.
261 childPaintInfo.applyTransform(AffineTransform::translation(adjustedPaintOffset.x() - x(), adjustedPaintOffset.y() - y()) * localToParentTransform());
263 bool continueRendering = true;
264 if (childPaintInfo.phase == PaintPhaseForeground)
265 continueRendering = SVGRenderSupport::prepareToRenderSVGContent(this, childPaintInfo);
267 if (continueRendering)
268 RenderBox::paint(childPaintInfo, LayoutPoint());
270 if (childPaintInfo.phase == PaintPhaseForeground)
271 SVGRenderSupport::finishRenderSVGContent(this, childPaintInfo, paintInfo.context);
273 childPaintInfo.context->restore();
276 void RenderSVGRoot::willBeDestroyed()
278 SVGResourcesCache::clientDestroyed(this);
279 RenderReplaced::willBeDestroyed();
282 void RenderSVGRoot::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
284 if (diff == StyleDifferenceLayout)
285 setNeedsBoundariesUpdate();
286 RenderReplaced::styleWillChange(diff, newStyle);
289 void RenderSVGRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
291 RenderReplaced::styleDidChange(diff, oldStyle);
292 SVGResourcesCache::clientStyleChanged(this, diff, style());
295 void RenderSVGRoot::updateFromElement()
297 RenderReplaced::updateFromElement();
298 SVGResourcesCache::clientUpdatedFromElement(this, style());
301 // RenderBox methods will expect coordinates w/o any transforms in coordinates
302 // relative to our borderBox origin. This method gives us exactly that.
303 void RenderSVGRoot::buildLocalToBorderBoxTransform()
305 SVGSVGElement* svg = static_cast<SVGSVGElement*>(node());
306 float scale = style()->effectiveZoom();
307 FloatPoint translate = svg->currentTranslate();
308 LayoutSize borderAndPadding(borderLeft() + paddingLeft(), borderTop() + paddingTop());
309 m_localToBorderBoxTransform = svg->viewBoxToViewTransform(width() / scale, height() / scale);
310 if (borderAndPadding.isEmpty() && scale == 1 && translate == FloatPoint::zero())
312 m_localToBorderBoxTransform = AffineTransform(scale, 0, 0, scale, borderAndPadding.width() + translate.x(), borderAndPadding.height() + translate.y()) * m_localToBorderBoxTransform;
315 const AffineTransform& RenderSVGRoot::localToParentTransform() const
317 // Slightly optimized version of m_localToParentTransform = AffineTransform::translation(x(), y()) * m_localToBorderBoxTransform;
318 m_localToParentTransform = m_localToBorderBoxTransform;
320 m_localToParentTransform.setE(m_localToParentTransform.e() + x());
322 m_localToParentTransform.setF(m_localToParentTransform.f() + y());
323 return m_localToParentTransform;
326 LayoutRect RenderSVGRoot::clippedOverflowRectForRepaint(RenderBoxModelObject* repaintContainer) const
328 return SVGRenderSupport::clippedOverflowRectForRepaint(this, repaintContainer);
331 void RenderSVGRoot::computeFloatRectForRepaint(RenderBoxModelObject* repaintContainer, FloatRect& repaintRect, bool fixed) const
333 // Apply our local transforms (except for x/y translation), then our shadow,
334 // and then call RenderBox's method to handle all the normal CSS Box model bits
335 repaintRect = m_localToBorderBoxTransform.mapRect(repaintRect);
337 // Apply initial viewport clip - not affected by overflow settings
338 repaintRect.intersect(borderBoxRect());
340 const SVGRenderStyle* svgStyle = style()->svgStyle();
341 if (const ShadowData* shadow = svgStyle->shadow())
342 shadow->adjustRectForShadow(repaintRect);
344 LayoutRect rect = enclosingIntRect(repaintRect);
345 RenderReplaced::computeRectForRepaint(repaintContainer, rect, fixed);
349 void RenderSVGRoot::mapLocalToContainer(RenderBoxModelObject* repaintContainer, bool fixed, bool useTransforms, TransformState& transformState, bool* wasFixed) const
351 ASSERT(!fixed); // We should have no fixed content in the SVG rendering tree.
352 ASSERT(useTransforms); // mapping a point through SVG w/o respecting trasnforms is useless.
354 // Transform to our border box and let RenderBox transform the rest of the way.
355 transformState.applyTransform(m_localToBorderBoxTransform);
356 RenderReplaced::mapLocalToContainer(repaintContainer, fixed, useTransforms, transformState, wasFixed);
359 void RenderSVGRoot::updateCachedBoundaries()
361 m_objectBoundingBox = FloatRect();
362 m_strokeBoundingBox = FloatRect();
363 m_repaintBoundingBox = FloatRect();
365 SVGRenderSupport::computeContainerBoundingBoxes(this, m_objectBoundingBox, m_strokeBoundingBox, m_repaintBoundingBox);
366 SVGRenderSupport::intersectRepaintRectWithResources(this, m_repaintBoundingBox);
367 m_repaintBoundingBox.inflate(borderAndPaddingWidth());
370 bool RenderSVGRoot::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
372 LayoutPoint pointInParent = pointInContainer - toLayoutSize(accumulatedOffset);
373 LayoutPoint pointInBorderBox(pointInParent.x() - x(), pointInParent.y() - y());
375 // Note: For now, we're ignoring hits to border and padding for <svg>
376 if (!contentBoxRect().contains(pointInBorderBox))
379 LayoutPoint localPoint = localToParentTransform().inverse().mapPoint(pointInParent);
381 for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
382 if (child->nodeAtFloatPoint(request, result, localPoint, hitTestAction)) {
383 // FIXME: CSS/HTML assumes the local point is relative to the border box, right?
384 updateHitTestResult(result, pointInBorderBox);
385 // FIXME: nodeAtFloatPoint() doesn't handle rect-based hit tests yet.
386 result.addNodeToRectBasedTestResult(child->node(), pointInContainer);
391 // 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.
392 if (hitTestAction == HitTestBlockBackground && style()->pointerEvents() != PE_NONE) {
393 // Only return true here, if the last hit testing phase 'BlockBackground' is executed. If we'd return true in the 'Foreground' phase,
394 // hit testing would stop immediately. For SVG only trees this doesn't matter. Though when we have a <foreignObject> subtree we need
395 // 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
396 // to detect these hits anymore.
397 updateHitTestResult(result, roundedLayoutPoint(localPoint));
406 #endif // ENABLE(SVG)