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.
26 #include "core/layout/svg/LayoutSVGRoot.h"
28 #include "core/frame/LocalFrame.h"
29 #include "core/layout/HitTestResult.h"
30 #include "core/layout/LayoutAnalyzer.h"
31 #include "core/layout/LayoutPart.h"
32 #include "core/layout/LayoutView.h"
33 #include "core/layout/svg/SVGLayoutSupport.h"
34 #include "core/layout/svg/SVGResourcesCache.h"
35 #include "core/paint/DeprecatedPaintLayer.h"
36 #include "core/paint/SVGRootPainter.h"
37 #include "core/svg/SVGElement.h"
38 #include "core/svg/SVGSVGElement.h"
39 #include "core/svg/graphics/SVGImage.h"
40 #include "platform/LengthFunctions.h"
44 LayoutSVGRoot::LayoutSVGRoot(SVGElement
* node
)
45 : LayoutReplaced(node
)
46 , m_objectBoundingBoxValid(false)
47 , m_isLayoutSizeChanged(false)
48 , m_needsBoundariesOrTransformUpdate(true)
49 , m_hasBoxDecorationBackground(false)
50 , m_hasNonIsolatedBlendingDescendants(false)
51 , m_hasNonIsolatedBlendingDescendantsDirty(false)
55 LayoutSVGRoot::~LayoutSVGRoot()
59 void LayoutSVGRoot::computeIntrinsicRatioInformation(FloatSize
& intrinsicSize
, double& intrinsicRatio
) const
61 // Spec: http://www.w3.org/TR/SVG/coords.html#IntrinsicSizing
62 // SVG needs to specify how to calculate some intrinsic sizing properties to enable inclusion within other languages.
63 // The intrinsic width and height of the viewport of SVG content must be determined from the 'width' and 'height' attributes.
64 SVGSVGElement
* svg
= toSVGSVGElement(node());
67 // The intrinsic aspect ratio of the viewport of SVG content is necessary for example, when including SVG from an 'object'
68 // element in HTML styled with CSS. It is possible (indeed, common) for an SVG graphic to have an intrinsic aspect ratio but
69 // not to have an intrinsic width or height. The intrinsic aspect ratio must be calculated based upon the following rules:
70 // - The aspect ratio is calculated by dividing a width by a height.
71 // - If the 'width' and 'height' of the rootmost 'svg' element are both specified with unit identifiers (in, mm, cm, pt, pc,
72 // px, em, ex) or in user units, then the aspect ratio is calculated from the 'width' and 'height' attributes after
73 // resolving both values to user units.
74 intrinsicSize
.setWidth(floatValueForLength(svg
->intrinsicWidth(), 0));
75 intrinsicSize
.setHeight(floatValueForLength(svg
->intrinsicHeight(), 0));
77 if (!isHorizontalWritingMode())
78 intrinsicSize
= intrinsicSize
.transposedSize();
80 if (!intrinsicSize
.isEmpty()) {
81 intrinsicRatio
= intrinsicSize
.width() / static_cast<double>(intrinsicSize
.height());
83 // - If either/both of the 'width' and 'height' of the rootmost 'svg' element are in percentage units (or omitted), the
84 // aspect ratio is calculated from the width and height values of the 'viewBox' specified for the current SVG document
85 // fragment. If the 'viewBox' is not correctly specified, or set to 'none', the intrinsic aspect ratio cannot be
86 // calculated and is considered unspecified.
87 FloatSize viewBoxSize
= svg
->viewBox()->currentValue()->value().size();
88 if (!viewBoxSize
.isEmpty()) {
89 // The viewBox can only yield an intrinsic ratio, not an intrinsic size.
90 intrinsicRatio
= viewBoxSize
.width() / static_cast<double>(viewBoxSize
.height());
91 if (!isHorizontalWritingMode())
92 intrinsicRatio
= 1 / intrinsicRatio
;
97 bool LayoutSVGRoot::isEmbeddedThroughSVGImage() const
99 return SVGImage::isInSVGImage(toSVGSVGElement(node()));
102 bool LayoutSVGRoot::isEmbeddedThroughFrameContainingSVGDocument() const
107 LocalFrame
* frame
= node()->document().frame();
111 // If our frame has an owner layoutObject, we're embedded through eg. object/embed/iframe,
112 // but we only negotiate if we're in an SVG document inside a embedded object (object/embed).
113 if (!frame
->ownerLayoutObject() || !frame
->ownerLayoutObject()->isEmbeddedObject())
115 return frame
->document()->isSVGDocument();
118 LayoutUnit
LayoutSVGRoot::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred
) const
120 // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
121 if (!m_containerSize
.isEmpty())
122 return m_containerSize
.width();
124 if (isEmbeddedThroughFrameContainingSVGDocument())
125 return containingBlock()->availableLogicalWidth();
127 if (style()->logicalWidth().isSpecified() || style()->logicalMaxWidth().isSpecified())
128 return LayoutReplaced::computeReplacedLogicalWidth(shouldComputePreferred
);
130 // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
131 return LayoutReplaced::computeReplacedLogicalWidth(shouldComputePreferred
);
134 LayoutUnit
LayoutSVGRoot::computeReplacedLogicalHeight() const
136 // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
137 if (!m_containerSize
.isEmpty())
138 return m_containerSize
.height();
140 if (isEmbeddedThroughFrameContainingSVGDocument())
141 return containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding
);
143 if (style()->logicalHeight().isSpecified() || style()->logicalMaxHeight().isSpecified())
144 return LayoutReplaced::computeReplacedLogicalHeight();
146 // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
147 return LayoutReplaced::computeReplacedLogicalHeight();
150 void LayoutSVGRoot::layout()
152 ASSERT(needsLayout());
153 LayoutAnalyzer::Scope
analyzer(*this);
155 bool needsLayout
= selfNeedsLayout();
157 LayoutSize oldSize
= size();
158 updateLogicalWidth();
159 updateLogicalHeight();
160 buildLocalToBorderBoxTransform();
162 SVGLayoutSupport::layoutResourcesIfNeeded(this);
164 SVGSVGElement
* svg
= toSVGSVGElement(node());
166 m_isLayoutSizeChanged
= needsLayout
|| (svg
->hasRelativeLengths() && oldSize
!= size());
167 SVGLayoutSupport::layoutChildren(this, needsLayout
|| SVGLayoutSupport::filtersForceContainerLayout(this));
169 if (m_needsBoundariesOrTransformUpdate
) {
170 updateCachedBoundaries();
171 m_needsBoundariesOrTransformUpdate
= false;
175 addVisualEffectOverflow();
177 if (!shouldApplyViewportClip()) {
178 FloatRect contentPaintInvalidationRect
= paintInvalidationRectInLocalCoordinates();
179 contentPaintInvalidationRect
= m_localToBorderBoxTransform
.mapRect(contentPaintInvalidationRect
);
180 addVisualOverflow(enclosingLayoutRect(contentPaintInvalidationRect
));
183 updateLayerTransformAfterLayout();
184 m_hasBoxDecorationBackground
= isDocumentElement() ? calculateHasBoxDecorations() : hasBoxDecorationBackground();
185 invalidateBackgroundObscurationStatus();
190 bool LayoutSVGRoot::shouldApplyViewportClip() const
192 // the outermost svg is clipped if auto, and svg document roots are always clipped
193 // When the svg is stand-alone (isDocumentElement() == true) the viewport clipping should always
194 // be applied, noting that the window scrollbars should be hidden if overflow=hidden.
195 return style()->overflowX() == OHIDDEN
196 || style()->overflowX() == OAUTO
197 || style()->overflowX() == OSCROLL
198 || this->isDocumentElement();
201 void LayoutSVGRoot::paintReplaced(const PaintInfo
& paintInfo
, const LayoutPoint
& paintOffset
)
203 SVGRootPainter(*this).paint(paintInfo
, paintOffset
);
206 void LayoutSVGRoot::willBeDestroyed()
208 LayoutBlock::removePercentHeightDescendant(const_cast<LayoutSVGRoot
*>(this));
210 SVGResourcesCache::clientDestroyed(this);
211 LayoutReplaced::willBeDestroyed();
214 void LayoutSVGRoot::styleDidChange(StyleDifference diff
, const ComputedStyle
* oldStyle
)
216 if (diff
.needsFullLayout())
217 setNeedsBoundariesUpdate();
218 if (diff
.needsPaintInvalidation()) {
219 // Box decorations may have appeared/disappeared - recompute status.
220 m_hasBoxDecorationBackground
= calculateHasBoxDecorations();
223 LayoutReplaced::styleDidChange(diff
, oldStyle
);
224 SVGResourcesCache::clientStyleChanged(this, diff
, styleRef());
227 bool LayoutSVGRoot::isChildAllowed(LayoutObject
* child
, const ComputedStyle
&) const
229 return child
->isSVG() && !(child
->isSVGInline() || child
->isSVGInlineText() || child
->isSVGGradientStop());
232 void LayoutSVGRoot::addChild(LayoutObject
* child
, LayoutObject
* beforeChild
)
234 LayoutReplaced::addChild(child
, beforeChild
);
235 SVGResourcesCache::clientWasAddedToTree(child
, child
->styleRef());
237 bool shouldIsolateDescendants
= (child
->isBlendingAllowed() && child
->style()->hasBlendMode()) || child
->hasNonIsolatedBlendingDescendants();
238 if (shouldIsolateDescendants
)
239 descendantIsolationRequirementsChanged(DescendantIsolationRequired
);
242 void LayoutSVGRoot::removeChild(LayoutObject
* child
)
244 SVGResourcesCache::clientWillBeRemovedFromTree(child
);
245 LayoutReplaced::removeChild(child
);
247 bool hadNonIsolatedDescendants
= (child
->isBlendingAllowed() && child
->style()->hasBlendMode()) || child
->hasNonIsolatedBlendingDescendants();
248 if (hadNonIsolatedDescendants
)
249 descendantIsolationRequirementsChanged(DescendantIsolationNeedsUpdate
);
252 bool LayoutSVGRoot::hasNonIsolatedBlendingDescendants() const
254 if (m_hasNonIsolatedBlendingDescendantsDirty
) {
255 m_hasNonIsolatedBlendingDescendants
= SVGLayoutSupport::computeHasNonIsolatedBlendingDescendants(this);
256 m_hasNonIsolatedBlendingDescendantsDirty
= false;
258 return m_hasNonIsolatedBlendingDescendants
;
261 void LayoutSVGRoot::descendantIsolationRequirementsChanged(DescendantIsolationState state
)
264 case DescendantIsolationRequired
:
265 m_hasNonIsolatedBlendingDescendants
= true;
266 m_hasNonIsolatedBlendingDescendantsDirty
= false;
268 case DescendantIsolationNeedsUpdate
:
269 m_hasNonIsolatedBlendingDescendantsDirty
= true;
274 void LayoutSVGRoot::insertedIntoTree()
276 LayoutReplaced::insertedIntoTree();
277 SVGResourcesCache::clientWasAddedToTree(this, styleRef());
280 void LayoutSVGRoot::willBeRemovedFromTree()
282 SVGResourcesCache::clientWillBeRemovedFromTree(this);
283 LayoutReplaced::willBeRemovedFromTree();
286 // LayoutBox methods will expect coordinates w/o any transforms in coordinates
287 // relative to our borderBox origin. This method gives us exactly that.
288 void LayoutSVGRoot::buildLocalToBorderBoxTransform()
290 SVGSVGElement
* svg
= toSVGSVGElement(node());
292 float scale
= style()->effectiveZoom();
293 FloatPoint translate
= svg
->currentTranslate();
294 LayoutSize
borderAndPadding(borderLeft() + paddingLeft(), borderTop() + paddingTop());
295 m_localToBorderBoxTransform
= svg
->viewBoxToViewTransform(contentWidth() / scale
, contentHeight() / scale
);
297 AffineTransform
viewToBorderBoxTransform(scale
, 0, 0, scale
, borderAndPadding
.width() + translate
.x(), borderAndPadding
.height() + translate
.y());
298 m_localToBorderBoxTransform
.preMultiply(viewToBorderBoxTransform
);
301 const AffineTransform
& LayoutSVGRoot::localToParentTransform() const
303 // Slightly optimized version of m_localToParentTransform = AffineTransform::translation(x(), y()) * m_localToBorderBoxTransform;
304 m_localToParentTransform
= m_localToBorderBoxTransform
;
306 m_localToParentTransform
.setE(m_localToParentTransform
.e() + roundToInt(location().x()));
308 m_localToParentTransform
.setF(m_localToParentTransform
.f() + roundToInt(location().y()));
309 return m_localToParentTransform
;
312 LayoutRect
LayoutSVGRoot::clippedOverflowRectForPaintInvalidation(const LayoutBoxModelObject
* paintInvalidationContainer
, const PaintInvalidationState
* paintInvalidationState
) const
314 // This is an open-coded aggregate of SVGLayoutSupport::clippedOverflowRectForPaintInvalidation,
315 // LayoutSVGRoot::mapRectToPaintInvalidationBacking and LayoutReplaced::clippedOverflowRectForPaintInvalidation.
316 // The reason for this is to optimize/minimize the paint invalidation rect when the box is not "decorated"
317 // (does not have background/border/etc.)
319 // Return early for any cases where we don't actually paint.
320 if (style()->visibility() != VISIBLE
&& !enclosingLayer()->hasVisibleContent())
323 // Compute the paint invalidation rect of the content of the SVG in the border-box coordinate space.
324 FloatRect contentPaintInvalidationRect
= paintInvalidationRectInLocalCoordinates();
325 contentPaintInvalidationRect
= m_localToBorderBoxTransform
.mapRect(contentPaintInvalidationRect
);
327 // Apply initial viewport clip, overflow:visible content is added to visualOverflow
328 // but the most common case is that overflow is hidden, so always intersect.
329 contentPaintInvalidationRect
.intersect(pixelSnappedBorderBoxRect());
331 LayoutRect paintInvalidationRect
= enclosingLayoutRect(contentPaintInvalidationRect
);
332 // If the box is decorated or is overflowing, extend it to include the border-box and overflow.
333 if (m_hasBoxDecorationBackground
|| hasOverflowModel()) {
334 // The selectionRect can project outside of the overflowRect, so take their union
335 // for paint invalidation to avoid selection painting glitches.
336 LayoutRect decoratedPaintInvalidationRect
= unionRect(localSelectionRect(false), visualOverflowRect());
337 paintInvalidationRect
.unite(decoratedPaintInvalidationRect
);
340 // Compute the paint invalidation rect in the parent coordinate space.
341 LayoutRect
rect(enclosingIntRect(paintInvalidationRect
));
342 LayoutReplaced::mapRectToPaintInvalidationBacking(paintInvalidationContainer
, rect
, paintInvalidationState
);
346 void LayoutSVGRoot::mapRectToPaintInvalidationBacking(const LayoutBoxModelObject
* paintInvalidationContainer
, LayoutRect
& rect
, const PaintInvalidationState
* paintInvalidationState
) const
348 // Note that we don't apply the border-box transform here - it's assumed
349 // that whoever called us has done that already.
351 // Apply initial viewport clip
352 if (shouldApplyViewportClip())
353 rect
.intersect(LayoutRect(pixelSnappedBorderBoxRect()));
355 LayoutReplaced::mapRectToPaintInvalidationBacking(paintInvalidationContainer
, rect
, paintInvalidationState
);
358 // This method expects local CSS box coordinates.
359 // Callers with local SVG viewport coordinates should first apply the localToBorderBoxTransform
360 // to convert from SVG viewport coordinates to local CSS box coordinates.
361 void LayoutSVGRoot::mapLocalToContainer(const LayoutBoxModelObject
* paintInvalidationContainer
, TransformState
& transformState
, MapCoordinatesFlags mode
, bool* wasFixed
, const PaintInvalidationState
* paintInvalidationState
) const
363 ASSERT(mode
& ~IsFixed
); // We should have no fixed content in the SVG layout tree.
364 // We used to have this ASSERT here, but we removed it when enabling layer squashing.
365 // See http://crbug.com/364901
366 // ASSERT(mode & UseTransforms); // mapping a point through SVG w/o respecting trasnforms is useless.
368 LayoutReplaced::mapLocalToContainer(paintInvalidationContainer
, transformState
, mode
| ApplyContainerFlip
, wasFixed
, paintInvalidationState
);
371 const LayoutObject
* LayoutSVGRoot::pushMappingToContainer(const LayoutBoxModelObject
* ancestorToStopAt
, LayoutGeometryMap
& geometryMap
) const
373 return LayoutReplaced::pushMappingToContainer(ancestorToStopAt
, geometryMap
);
376 void LayoutSVGRoot::updateCachedBoundaries()
378 SVGLayoutSupport::computeContainerBoundingBoxes(this, m_objectBoundingBox
, m_objectBoundingBoxValid
, m_strokeBoundingBox
, m_paintInvalidationBoundingBox
);
379 SVGLayoutSupport::intersectPaintInvalidationRectWithResources(this, m_paintInvalidationBoundingBox
);
382 bool LayoutSVGRoot::nodeAtPoint(HitTestResult
& result
, const HitTestLocation
& locationInContainer
, const LayoutPoint
& accumulatedOffset
, HitTestAction hitTestAction
)
384 LayoutPoint pointInParent
= locationInContainer
.point() - toLayoutSize(accumulatedOffset
);
385 LayoutPoint pointInBorderBox
= pointInParent
- toLayoutSize(location());
387 // Only test SVG content if the point is in our content box, or in case we
388 // don't clip to the viewport, the visual overflow rect.
389 // FIXME: This should be an intersection when rect-based hit tests are supported by nodeAtFloatPoint.
390 if (contentBoxRect().contains(pointInBorderBox
) || (!shouldApplyViewportClip() && visualOverflowRect().contains(pointInBorderBox
))) {
391 const AffineTransform
& localToParentTransform
= this->localToParentTransform();
392 if (localToParentTransform
.isInvertible()) {
393 FloatPoint localPoint
= localToParentTransform
.inverse().mapPoint(FloatPoint(pointInParent
));
395 for (LayoutObject
* child
= lastChild(); child
; child
= child
->previousSibling()) {
396 // FIXME: nodeAtFloatPoint() doesn't handle rect-based hit tests yet.
397 if (child
->nodeAtFloatPoint(result
, localPoint
, hitTestAction
)) {
398 updateHitTestResult(result
, pointInBorderBox
);
399 if (!result
.addNodeToListBasedTestResult(child
->node(), locationInContainer
))
406 // 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.
407 if ((hitTestAction
== HitTestBlockBackground
|| hitTestAction
== HitTestChildBlockBackground
) && visibleToHitTestRequest(result
.hitTestRequest())) {
408 // Only return true here, if the last hit testing phase 'BlockBackground' (or 'ChildBlockBackground' - depending on context) is executed.
409 // If we'd return true in the 'Foreground' phase, hit testing would stop immediately. For SVG only trees this doesn't matter.
410 // Though when we have a <foreignObject> subtree we need to be able to detect hits on the background of a <div> element.
411 // If we'd return true here in the 'Foreground' phase, we are not able to detect these hits anymore.
412 LayoutRect
boundsRect(accumulatedOffset
+ location(), size());
413 if (locationInContainer
.intersects(boundsRect
)) {
414 updateHitTestResult(result
, pointInBorderBox
);
415 if (!result
.addNodeToListBasedTestResult(node(), locationInContainer
, boundsRect
))