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)
59 , m_isLayoutSizeChanged(false)
60 , m_needsBoundariesOrTransformUpdate(true)
61 , m_needsSizeNegotiationWithHostDocument(false)
66 RenderSVGRoot::~RenderSVGRoot()
70 void RenderSVGRoot::computeIntrinsicRatioInformation(FloatSize& intrinsicRatio, bool& isPercentageIntrinsicSize) const
72 // Spec: http://dev.w3.org/SVG/profiles/1.1F2/publish/coords.html#IntrinsicSizing
73 // The intrinsic aspect ratio of the viewport of SVG content is necessary for example, when including
74 // SVG from an ‘object’ element in HTML styled with CSS. It is possible (indeed, common) for an SVG
75 // graphic to have an intrinsic aspect ratio but not to have an intrinsic width or height.
76 // The intrinsic aspect ratio must be calculated based upon the following rules:
77 // The aspect ratio is calculated by dividing a width by a height.
79 // If the ‘width’ and ‘height’ of the rootmost ‘svg’ element are both specified with unit identifiers
80 // (in, mm, cm, pt, pc, px, em, ex) or in user units, then the aspect ratio is calculated from the
81 // ‘width’ and ‘height’ attributes after resolving both values to user units.
82 isPercentageIntrinsicSize = false;
83 if (style()->width().isFixed() && style()->height().isFixed()) {
84 intrinsicRatio = FloatSize(width(), height());
88 // If either/both of the ‘width’ and ‘height’ of the rootmost ‘svg’ element are in percentage units (or omitted),
89 // the aspect ratio is calculated from the width and height values of the ‘viewBox’ specified for the current SVG
90 // document fragment. If the ‘viewBox’ is not correctly specified, or set to 'none', the intrinsic aspect ratio
91 // cannot be calculated and is considered unspecified.
92 intrinsicRatio = static_cast<SVGSVGElement*>(node())->currentViewBoxRect().size();
94 // Compatibility with authors expectations and Firefox/Opera: when percentage units are used, take them into
95 // account for certain cases of the intrinsic width/height calculation in RenderPart::computeReplacedLogicalWidth/Height.
96 if (intrinsicRatio.isEmpty() && style()->width().isPercent() && style()->height().isPercent()) {
97 isPercentageIntrinsicSize = true;
98 intrinsicRatio = FloatSize(style()->width().percent(), style()->height().percent());
102 void RenderSVGRoot::computePreferredLogicalWidths()
104 ASSERT(preferredLogicalWidthsDirty());
106 LayoutUnit borderAndPadding = borderAndPaddingWidth();
107 LayoutUnit width = computeReplacedLogicalWidth(false) + borderAndPadding;
109 if (style()->maxWidth().isFixed())
110 width = min(width, style()->maxWidth().value() + (style()->boxSizing() == CONTENT_BOX ? borderAndPadding : 0));
112 if (style()->width().isPercent() || (style()->width().isAuto() && style()->height().isPercent())) {
113 m_minPreferredLogicalWidth = 0;
114 m_maxPreferredLogicalWidth = width;
116 m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = width;
118 setPreferredLogicalWidthsDirty(false);
121 bool RenderSVGRoot::isEmbeddedThroughSVGImage() const
126 Frame* frame = node()->document()->frame();
130 // Test whether we're embedded through an img.
131 if (!frame->page() || !frame->page()->chrome())
134 ChromeClient* chromeClient = frame->page()->chrome()->client();
135 if (!chromeClient || !chromeClient->isSVGImageChromeClient())
141 bool RenderSVGRoot::isEmbeddedThroughFrameContainingSVGDocument() const
146 Frame* frame = node()->document()->frame();
150 // If our frame has an owner renderer, we're embedded through eg. object/embed/iframe,
151 // but we only negotiate if we're in an SVG document.
152 if (!frame->ownerRenderer())
154 return frame->document()->isSVGDocument();
157 LayoutUnit RenderSVGRoot::computeReplacedLogicalWidth(bool includeMaxWidth) const
159 // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
160 LayoutUnit replacedWidth = m_containerSize.width();
161 if (replacedWidth > 0)
162 return replacedWidth;
164 replacedWidth = RenderBox::computeReplacedLogicalWidth(includeMaxWidth);
165 Frame* frame = node() && node()->document() ? node()->document()->frame() : 0;
167 return replacedWidth;
169 if (!isEmbeddedThroughFrameContainingSVGDocument())
170 return replacedWidth;
172 RenderPart* ownerRenderer = frame->ownerRenderer();
173 RenderStyle* ownerRendererStyle = ownerRenderer->style();
174 ASSERT(ownerRendererStyle);
175 ASSERT(frame->contentRenderer());
177 Length ownerWidth = ownerRendererStyle->width();
178 if (ownerWidth.isAuto())
179 return replacedWidth;
181 // Spec: http://dev.w3.org/SVG/profiles/1.1F2/publish/coords.html#ViewportSpace
182 // The SVG user agent negotiates with its parent user agent to determine the viewport into which the SVG user agent can render
183 // the document. In some circumstances, SVG content will be embedded (by reference or inline) within a containing document.
184 // This containing document might include attributes, properties and/or other parameters (explicit or implicit) which specify
185 // or provide hints about the dimensions of the viewport for the SVG content. SVG content itself optionally can provide
186 // information about the appropriate viewport region for the content via the ‘width’ and ‘height’ XML attributes on the
187 // outermost svg element. The negotiation process uses any information provided by the containing document and the SVG
188 // content itself to choose the viewport location and size.
190 // The ‘width’ attribute on the outermost svg element establishes the viewport's width, unless the following conditions are met:
191 // * the SVG content is a separately stored resource that is embedded by reference (such as the ‘object’ element in XHTML [XHTML]),
192 // or the SVG content is embedded inline within a containing document;
193 // * and the referencing element or containing document is styled using CSS [CSS2] or XSL [XSL];
194 // * and there are CSS-compatible positioning properties ([CSS2], section 9.3) specified on the referencing element
195 // (e.g., the ‘object’ element) or on the containing document's outermost svg element that are sufficient to establish
196 // the width of the viewport.
198 // Under these conditions, the positioning properties establish the viewport's width.
199 return ownerRenderer->computeReplacedLogicalWidthRespectingMinMaxWidth(ownerRenderer->computeReplacedLogicalWidthUsing(ownerWidth), includeMaxWidth);
202 LayoutUnit RenderSVGRoot::computeReplacedLogicalHeight() const
204 // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
205 LayoutUnit replacedHeight = m_containerSize.height();
206 if (replacedHeight > 0)
207 return replacedHeight;
209 replacedHeight = RenderBox::computeReplacedLogicalHeight();
210 Frame* frame = node() && node()->document() ? node()->document()->frame() : 0;
212 return replacedHeight;
214 if (!isEmbeddedThroughFrameContainingSVGDocument())
215 return replacedHeight;
217 RenderPart* ownerRenderer = frame->ownerRenderer();
218 ASSERT(ownerRenderer);
220 RenderStyle* ownerRendererStyle = ownerRenderer->style();
221 ASSERT(ownerRendererStyle);
223 Length ownerHeight = ownerRendererStyle->height();
224 if (ownerHeight.isAuto())
225 return replacedHeight;
227 // Spec: http://dev.w3.org/SVG/profiles/1.1F2/publish/coords.html#ViewportSpace
228 // See comment in RenderSVGRoot::computeReplacedLogicalWidth().
229 // Similarly, if there are positioning properties specified on the referencing element or on the outermost svg element that
230 // are sufficient to establish the height of the viewport, then these positioning properties establish the viewport's height;
231 // otherwise, the ‘height’ attribute on the outermost svg element establishes the viewport's height.
232 return ownerRenderer->computeReplacedLogicalHeightRespectingMinMaxHeight(ownerRenderer->computeReplacedLogicalHeightUsing(ownerHeight));
235 void RenderSVGRoot::layout()
237 ASSERT(needsLayout());
239 // Arbitrary affine transforms are incompatible with LayoutState.
240 LayoutStateDisabler layoutStateDisabler(view());
242 bool needsLayout = selfNeedsLayout();
243 LayoutRepainter repainter(*this, checkForRepaintDuringLayout() && needsLayout);
245 LayoutSize oldSize(width(), height());
246 computeLogicalWidth();
247 computeLogicalHeight();
249 SVGSVGElement* svg = static_cast<SVGSVGElement*>(node());
250 m_isLayoutSizeChanged = needsLayout || (svg->hasRelativeLengths() && oldSize != size());
252 if (view() && view()->frameView() && view()->frameView()->embeddedContentBox()) {
253 if (!m_needsSizeNegotiationWithHostDocument)
254 m_needsSizeNegotiationWithHostDocument = !m_everHadLayout || oldSize != size();
256 ASSERT(!m_needsSizeNegotiationWithHostDocument);
258 SVGRenderSupport::layoutChildren(this, needsLayout || SVGRenderSupport::filtersForceContainerLayout(this));
259 m_isLayoutSizeChanged = false;
261 // At this point LayoutRepainter already grabbed the old bounds,
262 // recalculate them now so repaintAfterLayout() uses the new bounds.
263 if (m_needsBoundariesOrTransformUpdate) {
264 updateCachedBoundaries();
265 m_needsBoundariesOrTransformUpdate = false;
268 repainter.repaintAfterLayout();
270 setNeedsLayout(false);
273 bool RenderSVGRoot::selfWillPaint()
275 SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(this);
276 return resources && resources->filter();
279 void RenderSVGRoot::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
281 if (paintInfo.context->paintingDisabled())
284 bool isVisible = style()->visibility() == VISIBLE;
285 LayoutPoint borderBoxOriginInContainer = paintOffset + parentOriginToBorderBox();
287 if (hasBoxDecorations() && (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseChildBlockBackground) && isVisible)
288 paintBoxDecorations(paintInfo, borderBoxOriginInContainer);
290 if (paintInfo.phase == PaintPhaseBlockBackground)
293 // An empty viewport disables rendering.
294 if (borderBoxRect().isEmpty())
297 // Don't paint if we don't have kids, except if we have filters we should paint those.
298 if (!firstChild() && !selfWillPaint())
301 // Make a copy of the PaintInfo because applyTransform will modify the damage rect.
302 PaintInfo childPaintInfo(paintInfo);
303 childPaintInfo.context->save();
305 // Apply initial viewport clip - not affected by overflow handling
306 childPaintInfo.context->clip(overflowClipRect(borderBoxOriginInContainer, paintInfo.renderRegion));
308 // Convert from container offsets (html renderers) to a relative transform (svg renderers).
309 // Transform from our paint container's coordinate system to our local coords.
310 childPaintInfo.applyTransform(localToRepaintContainerTransform(paintOffset));
312 bool continueRendering = true;
313 if (childPaintInfo.phase == PaintPhaseForeground)
314 continueRendering = SVGRenderSupport::prepareToRenderSVGContent(this, childPaintInfo);
316 if (continueRendering)
317 RenderBox::paint(childPaintInfo, LayoutPoint());
319 if (childPaintInfo.phase == PaintPhaseForeground)
320 SVGRenderSupport::finishRenderSVGContent(this, childPaintInfo, paintInfo.context);
322 childPaintInfo.context->restore();
324 if ((paintInfo.phase == PaintPhaseOutline || paintInfo.phase == PaintPhaseSelfOutline) && style()->outlineWidth() && isVisible)
325 paintOutline(paintInfo.context, LayoutRect(borderBoxOriginInContainer, size()));
328 void RenderSVGRoot::willBeDestroyed()
330 SVGResourcesCache::clientDestroyed(this);
331 RenderBox::willBeDestroyed();
334 void RenderSVGRoot::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
336 if (diff == StyleDifferenceLayout)
337 setNeedsBoundariesUpdate();
338 RenderBox::styleWillChange(diff, newStyle);
341 void RenderSVGRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
343 RenderBox::styleDidChange(diff, oldStyle);
344 SVGResourcesCache::clientStyleChanged(this, diff, style());
347 void RenderSVGRoot::updateFromElement()
349 RenderBox::updateFromElement();
350 SVGResourcesCache::clientUpdatedFromElement(this, style());
353 // RenderBox methods will expect coordinates w/o any transforms in coordinates
354 // relative to our borderBox origin. This method gives us exactly that.
355 AffineTransform RenderSVGRoot::localToBorderBoxTransform() const
357 LayoutSize borderAndPadding = borderOriginToContentBox();
358 SVGSVGElement* svg = static_cast<SVGSVGElement*>(node());
359 float scale = style()->effectiveZoom();
360 FloatPoint translate = svg->currentTranslate();
361 AffineTransform ctm(scale, 0, 0, scale, borderAndPadding.width() + translate.x(), borderAndPadding.height() + translate.y());
362 return ctm * svg->viewBoxToViewTransform(width() / scale, height() / scale);
365 LayoutSize RenderSVGRoot::parentOriginToBorderBox() const
367 return locationOffset();
370 LayoutSize RenderSVGRoot::borderOriginToContentBox() const
372 return LayoutSize(borderLeft() + paddingLeft(), borderTop() + paddingTop());
375 AffineTransform RenderSVGRoot::localToRepaintContainerTransform(const LayoutPoint& parentOriginInContainer) const
377 return AffineTransform::translation(parentOriginInContainer.x(), parentOriginInContainer.y()) * localToParentTransform();
380 const AffineTransform& RenderSVGRoot::localToParentTransform() const
382 LayoutSize parentToBorderBoxOffset = parentOriginToBorderBox();
384 m_localToParentTransform = AffineTransform::translation(parentToBorderBoxOffset.width(), parentToBorderBoxOffset.height()) * localToBorderBoxTransform();
386 return m_localToParentTransform;
389 LayoutRect RenderSVGRoot::clippedOverflowRectForRepaint(RenderBoxModelObject* repaintContainer) const
391 return SVGRenderSupport::clippedOverflowRectForRepaint(this, repaintContainer);
394 void RenderSVGRoot::computeFloatRectForRepaint(RenderBoxModelObject* repaintContainer, FloatRect& repaintRect, bool fixed) const
396 // Apply our local transforms (except for x/y translation), then our shadow,
397 // and then call RenderBox's method to handle all the normal CSS Box model bits
398 repaintRect = localToBorderBoxTransform().mapRect(repaintRect);
400 // Apply initial viewport clip - not affected by overflow settings
401 repaintRect.intersect(borderBoxRect());
403 const SVGRenderStyle* svgStyle = style()->svgStyle();
404 if (const ShadowData* shadow = svgStyle->shadow())
405 shadow->adjustRectForShadow(repaintRect);
407 LayoutRect rect = enclosingIntRect(repaintRect);
408 RenderBox::computeRectForRepaint(repaintContainer, rect, fixed);
412 void RenderSVGRoot::mapLocalToContainer(RenderBoxModelObject* repaintContainer, bool fixed, bool useTransforms, TransformState& transformState, bool* wasFixed) const
414 ASSERT(!fixed); // We should have no fixed content in the SVG rendering tree.
415 ASSERT(useTransforms); // mapping a point through SVG w/o respecting trasnforms is useless.
417 // Transform to our border box and let RenderBox transform the rest of the way.
418 transformState.applyTransform(localToBorderBoxTransform());
419 RenderBox::mapLocalToContainer(repaintContainer, fixed, useTransforms, transformState, wasFixed);
422 void RenderSVGRoot::updateCachedBoundaries()
424 m_objectBoundingBox = FloatRect();
425 m_strokeBoundingBox = FloatRect();
426 m_repaintBoundingBox = FloatRect();
428 SVGRenderSupport::computeContainerBoundingBoxes(this, m_objectBoundingBox, m_strokeBoundingBox, m_repaintBoundingBox);
429 SVGRenderSupport::intersectRepaintRectWithResources(this, m_repaintBoundingBox);
430 m_repaintBoundingBox.inflate(borderAndPaddingWidth());
433 bool RenderSVGRoot::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
435 LayoutPoint pointInParent = pointInContainer - toLayoutSize(accumulatedOffset);
436 LayoutPoint pointInBorderBox = pointInParent - parentOriginToBorderBox();
438 // Note: For now, we're ignoring hits to border and padding for <svg>
439 if (!contentBoxRect().contains(pointInBorderBox))
442 LayoutPoint localPoint = localToParentTransform().inverse().mapPoint(pointInParent);
444 for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
445 if (child->nodeAtFloatPoint(request, result, localPoint, hitTestAction)) {
446 // FIXME: CSS/HTML assumes the local point is relative to the border box, right?
447 updateHitTestResult(result, pointInBorderBox);
448 // FIXME: nodeAtFloatPoint() doesn't handle rect-based hit tests yet.
449 result.addNodeToRectBasedTestResult(child->node(), pointInContainer);
454 // 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.
455 if (hitTestAction == HitTestBlockBackground && style()->pointerEvents() != PE_NONE) {
456 // Only return true here, if the last hit testing phase 'BlockBackground' is executed. If we'd return true in the 'Foreground' phase,
457 // hit testing would stop immediately. For SVG only trees this doesn't matter. Though when we have a <foreignObject> subtree we need
458 // 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
459 // to detect these hits anymore.
460 updateHitTestResult(result, roundedLayoutPoint(localPoint));
469 #endif // ENABLE(SVG)