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 "GraphicsContext.h"
31 #include "HitTestResult.h"
32 #include "LayoutRepainter.h"
33 #include "RenderPart.h"
34 #include "RenderSVGContainer.h"
35 #include "RenderSVGResource.h"
36 #include "RenderView.h"
37 #include "SVGLength.h"
38 #include "SVGRenderSupport.h"
39 #include "SVGResources.h"
40 #include "SVGSVGElement.h"
41 #include "SVGStyledElement.h"
42 #include "SVGViewSpec.h"
43 #include "TransformState.h"
46 #include "RenderSVGResourceFilter.h"
53 RenderSVGRoot::RenderSVGRoot(SVGStyledElement* node)
55 , m_isLayoutSizeChanged(false)
56 , m_needsBoundariesOrTransformUpdate(true)
57 , m_needsSizeNegotiationWithHostDocument(false)
62 RenderSVGRoot::~RenderSVGRoot()
66 void RenderSVGRoot::computeIntrinsicRatioInformation(FloatSize& intrinsicRatio, bool& isPercentageIntrinsicSize) const
68 // Spec: http://dev.w3.org/SVG/profiles/1.1F2/publish/coords.html#IntrinsicSizing
69 // The intrinsic aspect ratio of the viewport of SVG content is necessary for example, when including
70 // SVG from an ‘object’ element in HTML styled with CSS. It is possible (indeed, common) for an SVG
71 // graphic to have an intrinsic aspect ratio but not to have an intrinsic width or height.
72 // The intrinsic aspect ratio must be calculated based upon the following rules:
73 // The aspect ratio is calculated by dividing a width by a height.
75 // If the ‘width’ and ‘height’ of the rootmost ‘svg’ element are both specified with unit identifiers
76 // (in, mm, cm, pt, pc, px, em, ex) or in user units, then the aspect ratio is calculated from the
77 // ‘width’ and ‘height’ attributes after resolving both values to user units.
78 isPercentageIntrinsicSize = false;
79 if (style()->width().isFixed() && style()->height().isFixed()) {
80 intrinsicRatio = FloatSize(width(), height());
84 // If either/both of the ‘width’ and ‘height’ of the rootmost ‘svg’ element are in percentage units (or omitted),
85 // the aspect ratio is calculated from the width and height values of the ‘viewBox’ specified for the current SVG
86 // document fragment. If the ‘viewBox’ is not correctly specified, or set to 'none', the intrinsic aspect ratio
87 // cannot be calculated and is considered unspecified.
88 intrinsicRatio = static_cast<SVGSVGElement*>(node())->currentViewBoxRect().size();
90 // Compatibility with authors expectations and Firefox/Opera: when percentage units are used, take them into
91 // account for certain cases of the intrinsic width/height calculation in RenderPart::computeReplacedLogicalWidth/Height.
92 if (intrinsicRatio.isEmpty() && style()->width().isPercent() && style()->height().isPercent()) {
93 isPercentageIntrinsicSize = true;
94 intrinsicRatio = FloatSize(style()->width().percent(), style()->height().percent());
98 void RenderSVGRoot::computePreferredLogicalWidths()
100 ASSERT(preferredLogicalWidthsDirty());
102 LayoutUnit borderAndPadding = borderAndPaddingWidth();
103 LayoutUnit width = computeReplacedLogicalWidth(false) + borderAndPadding;
105 if (style()->maxWidth().isFixed())
106 width = min(width, style()->maxWidth().value() + (style()->boxSizing() == CONTENT_BOX ? borderAndPadding : 0));
108 if (style()->width().isPercent() || (style()->width().isAuto() && style()->height().isPercent())) {
109 m_minPreferredLogicalWidth = 0;
110 m_maxPreferredLogicalWidth = width;
112 m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = width;
114 setPreferredLogicalWidthsDirty(false);
117 LayoutUnit RenderSVGRoot::computeIntrinsicWidth(LayoutUnit replacedWidth) const
119 if (!style()->width().isPercent())
120 return replacedWidth;
121 // FIXME: Remove unnecessary rounding when layout is off ints: webkit.org/b/63656
122 return static_cast<int>(ceilf(replacedWidth * style()->effectiveZoom()));
125 LayoutUnit RenderSVGRoot::computeIntrinsicHeight(LayoutUnit replacedHeight) const
127 if (!style()->height().isPercent())
128 return replacedHeight;
129 // FIXME: Remove unnecessary rounding when layout is off ints: webkit.org/b/63656
130 return static_cast<int>(ceilf(replacedHeight * style()->effectiveZoom()));
133 LayoutUnit RenderSVGRoot::computeReplacedLogicalWidth(bool includeMaxWidth) const
135 LayoutUnit replacedWidth = RenderBox::computeReplacedLogicalWidth(includeMaxWidth);
136 Frame* frame = node() && node()->document() ? node()->document()->frame() : 0;
138 return computeIntrinsicWidth(replacedWidth);
140 // If our frame has an owner renderer, we're embedded through eg. object/embed.
141 RenderPart* ownerRenderer = frame->ownerRenderer();
143 return computeIntrinsicWidth(replacedWidth);
145 RenderStyle* ownerRendererStyle = ownerRenderer->style();
146 ASSERT(ownerRendererStyle);
147 ASSERT(frame->contentRenderer());
149 Length ownerWidth = ownerRendererStyle->width();
150 if (ownerWidth.isAuto())
151 return replacedWidth;
153 // Spec: http://dev.w3.org/SVG/profiles/1.1F2/publish/coords.html#ViewportSpace
154 // The SVG user agent negotiates with its parent user agent to determine the viewport into which the SVG user agent can render
155 // the document. In some circumstances, SVG content will be embedded (by reference or inline) within a containing document.
156 // This containing document might include attributes, properties and/or other parameters (explicit or implicit) which specify
157 // or provide hints about the dimensions of the viewport for the SVG content. SVG content itself optionally can provide
158 // information about the appropriate viewport region for the content via the ‘width’ and ‘height’ XML attributes on the
159 // outermost svg element. The negotiation process uses any information provided by the containing document and the SVG
160 // content itself to choose the viewport location and size.
162 // The ‘width’ attribute on the outermost svg element establishes the viewport's width, unless the following conditions are met:
163 // * the SVG content is a separately stored resource that is embedded by reference (such as the ‘object’ element in XHTML [XHTML]),
164 // or the SVG content is embedded inline within a containing document;
165 // * and the referencing element or containing document is styled using CSS [CSS2] or XSL [XSL];
166 // * and there are CSS-compatible positioning properties ([CSS2], section 9.3) specified on the referencing element
167 // (e.g., the ‘object’ element) or on the containing document's outermost svg element that are sufficient to establish
168 // the width of the viewport.
170 // Under these conditions, the positioning properties establish the viewport's width.
171 return ownerRenderer->computeReplacedLogicalWidthRespectingMinMaxWidth(ownerRenderer->computeReplacedLogicalWidthUsing(ownerWidth), includeMaxWidth);
174 LayoutUnit RenderSVGRoot::computeReplacedLogicalHeight() const
176 LayoutUnit replacedHeight = RenderBox::computeReplacedLogicalHeight();
178 Frame* frame = node() && node()->document() ? node()->document()->frame() : 0;
180 return computeIntrinsicHeight(replacedHeight);
182 // If our frame has an owner renderer, we're embedded through eg. object/embed.
183 RenderPart* ownerRenderer = frame->ownerRenderer();
185 return computeIntrinsicHeight(replacedHeight);
187 RenderStyle* ownerRendererStyle = ownerRenderer->style();
188 ASSERT(ownerRendererStyle);
189 ASSERT(frame->contentRenderer());
191 Length ownerHeight = ownerRendererStyle->height();
192 if (ownerHeight.isAuto())
193 return replacedHeight;
195 // Spec: http://dev.w3.org/SVG/profiles/1.1F2/publish/coords.html#ViewportSpace
196 // See comment in RenderSVGRoot::computeReplacedLogicalWidth().
197 // Similarly, if there are positioning properties specified on the referencing element or on the outermost svg element that
198 // are sufficient to establish the height of the viewport, then these positioning properties establish the viewport's height;
199 // otherwise, the ‘height’ attribute on the outermost svg element establishes the viewport's height.
200 return ownerRenderer->computeReplacedLogicalHeightRespectingMinMaxHeight(ownerRenderer->computeReplacedLogicalHeightUsing(ownerHeight));
203 void RenderSVGRoot::layout()
205 ASSERT(needsLayout());
207 // Arbitrary affine transforms are incompatible with LayoutState.
208 LayoutStateDisabler layoutStateDisabler(view());
210 bool needsLayout = selfNeedsLayout();
211 LayoutRepainter repainter(*this, checkForRepaintDuringLayout() && needsLayout);
213 LayoutSize oldSize(width(), height());
214 computeLogicalWidth();
215 computeLogicalHeight();
218 SVGSVGElement* svg = static_cast<SVGSVGElement*>(node());
219 m_isLayoutSizeChanged = svg->hasRelativeLengths() && oldSize != size();
221 if (view() && view()->frameView() && view()->frameView()->embeddedContentBox()) {
222 if (!m_needsSizeNegotiationWithHostDocument)
223 m_needsSizeNegotiationWithHostDocument = !m_everHadLayout || oldSize != size();
225 ASSERT(!m_needsSizeNegotiationWithHostDocument);
227 SVGRenderSupport::layoutChildren(this, needsLayout);
228 m_isLayoutSizeChanged = false;
230 // At this point LayoutRepainter already grabbed the old bounds,
231 // recalculate them now so repaintAfterLayout() uses the new bounds.
232 if (m_needsBoundariesOrTransformUpdate) {
233 updateCachedBoundaries();
234 m_needsBoundariesOrTransformUpdate = false;
237 repainter.repaintAfterLayout();
239 setNeedsLayout(false);
242 bool RenderSVGRoot::selfWillPaint()
245 SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(this);
246 return resources && resources->filter();
252 void RenderSVGRoot::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
254 if (paintInfo.context->paintingDisabled())
257 bool isVisible = style()->visibility() == VISIBLE;
258 LayoutPoint borderBoxOriginInContainer = paintOffset + parentOriginToBorderBox();
260 if (hasBoxDecorations() && (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseChildBlockBackground) && isVisible)
261 paintBoxDecorations(paintInfo, borderBoxOriginInContainer);
263 if (paintInfo.phase == PaintPhaseBlockBackground)
266 // An empty viewport disables rendering. FIXME: Should we still render filters?
267 if (m_viewportSize.isEmpty())
270 // Don't paint if we don't have kids, except if we have filters we should paint those.
271 if (!firstChild() && !selfWillPaint())
274 // Make a copy of the PaintInfo because applyTransform will modify the damage rect.
275 PaintInfo childPaintInfo(paintInfo);
276 childPaintInfo.context->save();
278 // Apply initial viewport clip - not affected by overflow handling
279 childPaintInfo.context->clip(overflowClipRect(borderBoxOriginInContainer, paintInfo.renderRegion));
281 // Convert from container offsets (html renderers) to a relative transform (svg renderers).
282 // Transform from our paint container's coordinate system to our local coords.
283 childPaintInfo.applyTransform(localToRepaintContainerTransform(paintOffset));
285 bool continueRendering = true;
286 if (childPaintInfo.phase == PaintPhaseForeground)
287 continueRendering = SVGRenderSupport::prepareToRenderSVGContent(this, childPaintInfo);
289 if (continueRendering)
290 RenderBox::paint(childPaintInfo, LayoutPoint());
292 if (childPaintInfo.phase == PaintPhaseForeground)
293 SVGRenderSupport::finishRenderSVGContent(this, childPaintInfo, paintInfo.context);
295 childPaintInfo.context->restore();
297 if ((paintInfo.phase == PaintPhaseOutline || paintInfo.phase == PaintPhaseSelfOutline) && style()->outlineWidth() && isVisible)
298 paintOutline(paintInfo.context, LayoutRect(borderBoxOriginInContainer, size()));
301 void RenderSVGRoot::willBeDestroyed()
303 SVGResourcesCache::clientDestroyed(this);
304 RenderBox::willBeDestroyed();
307 void RenderSVGRoot::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
309 if (diff == StyleDifferenceLayout)
310 setNeedsBoundariesUpdate();
311 RenderBox::styleWillChange(diff, newStyle);
314 void RenderSVGRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
316 RenderBox::styleDidChange(diff, oldStyle);
317 SVGResourcesCache::clientStyleChanged(this, diff, style());
320 void RenderSVGRoot::updateFromElement()
322 RenderBox::updateFromElement();
323 SVGResourcesCache::clientUpdatedFromElement(this, style());
326 void RenderSVGRoot::calcViewport()
328 SVGSVGElement* svg = static_cast<SVGSVGElement*>(node());
330 if (!svg->hasSetContainerSize()) {
331 // In the normal case of <svg> being stand-alone or in a CSSBoxModel object we use
332 // RenderBox::width()/height() (which pulls data from RenderStyle)
333 m_viewportSize = FloatSize(width(), height());
337 // In the SVGImage case grab the SVGLength values off of SVGSVGElement and use
338 // the special relativeWidthValue accessors which respect the specified containerSize
339 // FIXME: Check how SVGImage + zooming is supposed to be handled?
340 SVGLength width = svg->width();
341 SVGLength height = svg->height();
342 m_viewportSize = FloatSize(width.unitType() == LengthTypePercentage ? svg->relativeWidthValue() : width.value(svg),
343 height.unitType() == LengthTypePercentage ? svg->relativeHeightValue() : height.value(svg));
346 // RenderBox methods will expect coordinates w/o any transforms in coordinates
347 // relative to our borderBox origin. This method gives us exactly that.
348 AffineTransform RenderSVGRoot::localToBorderBoxTransform() const
350 LayoutSize borderAndPadding = borderOriginToContentBox();
351 SVGSVGElement* svg = static_cast<SVGSVGElement*>(node());
352 float scale = style()->effectiveZoom();
353 FloatPoint translate = svg->currentTranslate();
354 AffineTransform ctm(scale, 0, 0, scale, borderAndPadding.width() + translate.x(), borderAndPadding.height() + translate.y());
355 return ctm * svg->viewBoxToViewTransform(width() / scale, height() / scale);
358 LayoutSize RenderSVGRoot::parentOriginToBorderBox() const
360 return locationOffset();
363 LayoutSize RenderSVGRoot::borderOriginToContentBox() const
365 return LayoutSize(borderLeft() + paddingLeft(), borderTop() + paddingTop());
368 AffineTransform RenderSVGRoot::localToRepaintContainerTransform(const LayoutPoint& parentOriginInContainer) const
370 return AffineTransform::translation(parentOriginInContainer.x(), parentOriginInContainer.y()) * localToParentTransform();
373 const AffineTransform& RenderSVGRoot::localToParentTransform() const
375 LayoutSize parentToBorderBoxOffset = parentOriginToBorderBox();
377 m_localToParentTransform = AffineTransform::translation(parentToBorderBoxOffset.width(), parentToBorderBoxOffset.height()) * localToBorderBoxTransform();
379 return m_localToParentTransform;
382 LayoutRect RenderSVGRoot::clippedOverflowRectForRepaint(RenderBoxModelObject* repaintContainer) const
384 return SVGRenderSupport::clippedOverflowRectForRepaint(this, repaintContainer);
387 void RenderSVGRoot::computeRectForRepaint(RenderBoxModelObject* repaintContainer, LayoutRect& repaintRect, bool fixed) const
389 // Apply our local transforms (except for x/y translation), then our shadow,
390 // and then call RenderBox's method to handle all the normal CSS Box model bits
391 repaintRect = localToBorderBoxTransform().mapRect(repaintRect);
393 // Apply initial viewport clip - not affected by overflow settings
394 repaintRect.intersect(enclosingLayoutRect(FloatRect(FloatPoint(), m_viewportSize)));
396 const SVGRenderStyle* svgStyle = style()->svgStyle();
397 if (const ShadowData* shadow = svgStyle->shadow())
398 shadow->adjustRectForShadow(repaintRect);
400 RenderBox::computeRectForRepaint(repaintContainer, repaintRect, fixed);
403 void RenderSVGRoot::mapLocalToContainer(RenderBoxModelObject* repaintContainer, bool fixed, bool useTransforms, TransformState& transformState, bool* wasFixed) const
405 ASSERT(!fixed); // We should have no fixed content in the SVG rendering tree.
406 ASSERT(useTransforms); // mapping a point through SVG w/o respecting trasnforms is useless.
408 // Transform to our border box and let RenderBox transform the rest of the way.
409 transformState.applyTransform(localToBorderBoxTransform());
410 RenderBox::mapLocalToContainer(repaintContainer, fixed, useTransforms, transformState, wasFixed);
413 void RenderSVGRoot::updateCachedBoundaries()
415 m_objectBoundingBox = FloatRect();
416 m_strokeBoundingBox = FloatRect();
417 m_repaintBoundingBox = FloatRect();
419 SVGRenderSupport::computeContainerBoundingBoxes(this, m_objectBoundingBox, m_strokeBoundingBox, m_repaintBoundingBox);
420 SVGRenderSupport::intersectRepaintRectWithResources(this, m_repaintBoundingBox);
421 m_repaintBoundingBox.inflate(borderAndPaddingWidth());
424 bool RenderSVGRoot::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
426 LayoutPoint pointInParent = pointInContainer - toLayoutSize(accumulatedOffset);
427 LayoutPoint pointInBorderBox = pointInParent - parentOriginToBorderBox();
429 // Note: For now, we're ignoring hits to border and padding for <svg>
430 LayoutPoint pointInContentBox = pointInBorderBox - borderOriginToContentBox();
431 if (!contentBoxRect().contains(pointInContentBox))
434 LayoutPoint localPoint = localToParentTransform().inverse().mapPoint(pointInParent);
436 for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
437 if (child->nodeAtFloatPoint(request, result, localPoint, hitTestAction)) {
438 // FIXME: CSS/HTML assumes the local point is relative to the border box, right?
439 updateHitTestResult(result, pointInBorderBox);
440 // FIXME: nodeAtFloatPoint() doesn't handle rect-based hit tests yet.
441 result.addNodeToRectBasedTestResult(child->node(), pointInContainer);
446 // 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.
447 if (hitTestAction == HitTestBlockBackground && style()->pointerEvents() != PE_NONE) {
448 // Only return true here, if the last hit testing phase 'BlockBackground' is executed. If we'd return true in the 'Foreground' phase,
449 // hit testing would stop immediately. For SVG only trees this doesn't matter. Though when we have a <foreignObject> subtree we need
450 // 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
451 // to detect these hits anymore.
452 updateHitTestResult(result, roundedLayoutPoint(localPoint));
461 #endif // ENABLE(SVG)