Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / rendering / svg / RenderSVGRoot.cpp
1 /*
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.
7  *
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.
12  *
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.
17  *
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.
22  */
23
24 #include "config.h"
25
26 #include "core/rendering/svg/RenderSVGRoot.h"
27
28 #include "core/frame/LocalFrame.h"
29 #include "core/rendering/HitTestResult.h"
30 #include "core/rendering/RenderLayer.h"
31 #include "core/rendering/RenderPart.h"
32 #include "core/rendering/RenderView.h"
33 #include "core/rendering/svg/RenderSVGResourceContainer.h"
34 #include "core/rendering/svg/SVGRenderSupport.h"
35 #include "core/rendering/svg/SVGRenderingContext.h"
36 #include "core/rendering/svg/SVGResources.h"
37 #include "core/rendering/svg/SVGResourcesCache.h"
38 #include "core/svg/SVGElement.h"
39 #include "core/svg/SVGSVGElement.h"
40 #include "core/svg/graphics/SVGImage.h"
41 #include "platform/LengthFunctions.h"
42 #include "platform/graphics/GraphicsContext.h"
43
44 namespace blink {
45
46 RenderSVGRoot::RenderSVGRoot(SVGElement* node)
47     : RenderReplaced(node)
48     , m_objectBoundingBoxValid(false)
49     , m_isLayoutSizeChanged(false)
50     , m_needsBoundariesOrTransformUpdate(true)
51     , m_hasBoxDecorationBackground(false)
52 {
53 }
54
55 RenderSVGRoot::~RenderSVGRoot()
56 {
57 }
58
59 void RenderSVGRoot::trace(Visitor* visitor)
60 {
61     visitor->trace(m_children);
62     RenderReplaced::trace(visitor);
63 }
64
65 void RenderSVGRoot::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio) const
66 {
67     // Spec: http://www.w3.org/TR/SVG/coords.html#IntrinsicSizing
68     // SVG needs to specify how to calculate some intrinsic sizing properties to enable inclusion within other languages.
69     // The intrinsic width and height of the viewport of SVG content must be determined from the ‘width’ and ‘height’ attributes.
70     SVGSVGElement* svg = toSVGSVGElement(node());
71     ASSERT(svg);
72
73     // The intrinsic aspect ratio of the viewport of SVG content is necessary for example, when including SVG from an ‘object’
74     // element in HTML styled with CSS. It is possible (indeed, common) for an SVG graphic to have an intrinsic aspect ratio but
75     // not to have an intrinsic width or height. The intrinsic aspect ratio must be calculated based upon the following rules:
76     // - The aspect ratio is calculated by dividing a width by a height.
77     // - If the ‘width’ and ‘height’ of the rootmost ‘svg’ element are both specified with unit identifiers (in, mm, cm, pt, pc,
78     //   px, em, ex) or in user units, then the aspect ratio is calculated from the ‘width’ and ‘height’ attributes after
79     //   resolving both values to user units.
80     intrinsicSize.setWidth(floatValueForLength(svg->intrinsicWidth(), 0));
81     intrinsicSize.setHeight(floatValueForLength(svg->intrinsicHeight(), 0));
82
83     if (!intrinsicSize.isEmpty()) {
84         intrinsicRatio = intrinsicSize.width() / static_cast<double>(intrinsicSize.height());
85     } else {
86         // - If either/both of the ‘width’ and ‘height’ of the rootmost ‘svg’ element are in percentage units (or omitted), the
87         //   aspect ratio is calculated from the width and height values of the ‘viewBox’ specified for the current SVG document
88         //   fragment. If the ‘viewBox’ is not correctly specified, or set to 'none', the intrinsic aspect ratio cannot be
89         //   calculated and is considered unspecified.
90         FloatSize viewBoxSize = svg->viewBox()->currentValue()->value().size();
91         if (!viewBoxSize.isEmpty()) {
92             // The viewBox can only yield an intrinsic ratio, not an intrinsic size.
93             intrinsicRatio = viewBoxSize.width() / static_cast<double>(viewBoxSize.height());
94         }
95     }
96 }
97
98 bool RenderSVGRoot::isEmbeddedThroughSVGImage() const
99 {
100     return SVGImage::isInSVGImage(toSVGSVGElement(node()));
101 }
102
103 bool RenderSVGRoot::isEmbeddedThroughFrameContainingSVGDocument() const
104 {
105     if (!node())
106         return false;
107
108     LocalFrame* frame = node()->document().frame();
109     if (!frame)
110         return false;
111
112     // If our frame has an owner renderer, we're embedded through eg. object/embed/iframe,
113     // but we only negotiate if we're in an SVG document inside a embedded object (object/embed).
114     if (!frame->ownerRenderer() || !frame->ownerRenderer()->isEmbeddedObject())
115         return false;
116     return frame->document()->isSVGDocument();
117 }
118
119 static inline LayoutUnit resolveLengthAttributeForSVG(const Length& length, float scale, float maxSize)
120 {
121     return static_cast<LayoutUnit>(valueForLength(length, maxSize) * (length.isFixed() ? scale : 1));
122 }
123
124 LayoutUnit RenderSVGRoot::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
125 {
126     SVGSVGElement* svg = toSVGSVGElement(node());
127     ASSERT(svg);
128
129     // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
130     if (!m_containerSize.isEmpty())
131         return m_containerSize.width();
132
133     if (isEmbeddedThroughFrameContainingSVGDocument())
134         return containingBlock()->availableLogicalWidth();
135
136     if (style()->logicalWidth().isSpecified() || style()->logicalMaxWidth().isSpecified())
137         return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
138
139     if (svg->hasIntrinsicWidth())
140         return resolveLengthAttributeForSVG(svg->intrinsicWidth(), style()->effectiveZoom(), containingBlock()->availableLogicalWidth().toFloat());
141
142     // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
143     return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
144 }
145
146 LayoutUnit RenderSVGRoot::computeReplacedLogicalHeight() const
147 {
148     SVGSVGElement* svg = toSVGSVGElement(node());
149     ASSERT(svg);
150
151     // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
152     if (!m_containerSize.isEmpty())
153         return m_containerSize.height();
154
155     if (isEmbeddedThroughFrameContainingSVGDocument())
156         return containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding);
157
158     if (style()->logicalHeight().isSpecified() || style()->logicalMaxHeight().isSpecified())
159         return RenderReplaced::computeReplacedLogicalHeight();
160
161     if (svg->hasIntrinsicHeight())
162         return resolveLengthAttributeForSVG(svg->intrinsicHeight(), style()->effectiveZoom(), containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding).toFloat());
163
164     // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
165     return RenderReplaced::computeReplacedLogicalHeight();
166 }
167
168 void RenderSVGRoot::layout()
169 {
170     ASSERT(needsLayout());
171
172     bool needsLayout = selfNeedsLayout();
173
174     LayoutSize oldSize = size();
175     updateLogicalWidth();
176     updateLogicalHeight();
177     buildLocalToBorderBoxTransform();
178
179     SVGRenderSupport::layoutResourcesIfNeeded(this);
180
181     SVGSVGElement* svg = toSVGSVGElement(node());
182     ASSERT(svg);
183     m_isLayoutSizeChanged = needsLayout || (svg->hasRelativeLengths() && oldSize != size());
184     SVGRenderSupport::layoutChildren(this, needsLayout || SVGRenderSupport::filtersForceContainerLayout(this));
185
186     if (m_needsBoundariesOrTransformUpdate) {
187         updateCachedBoundaries();
188         m_needsBoundariesOrTransformUpdate = false;
189     }
190
191     m_overflow.clear();
192     addVisualEffectOverflow();
193
194     if (!shouldApplyViewportClip()) {
195         FloatRect contentPaintInvalidationRect = paintInvalidationRectInLocalCoordinates();
196         contentPaintInvalidationRect = m_localToBorderBoxTransform.mapRect(contentPaintInvalidationRect);
197         addVisualOverflow(enclosingLayoutRect(contentPaintInvalidationRect));
198     }
199
200     updateLayerTransformAfterLayout();
201     m_hasBoxDecorationBackground = isDocumentElement() ? calculateHasBoxDecorations() : hasBoxDecorationBackground();
202     invalidateBackgroundObscurationStatus();
203
204     clearNeedsLayout();
205 }
206
207 bool RenderSVGRoot::shouldApplyViewportClip() const
208 {
209     // the outermost svg is clipped if auto, and svg document roots are always clipped
210     // When the svg is stand-alone (isDocumentElement() == true) the viewport clipping should always
211     // be applied, noting that the window scrollbars should be hidden if overflow=hidden.
212     return style()->overflowX() == OHIDDEN
213         || style()->overflowX() == OAUTO
214         || style()->overflowX() == OSCROLL
215         || this->isDocumentElement();
216 }
217
218 void RenderSVGRoot::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
219 {
220     // An empty viewport disables rendering.
221     if (pixelSnappedBorderBoxRect().isEmpty())
222         return;
223
224     // SVG outlines are painted during PaintPhaseForeground.
225     if (paintInfo.phase == PaintPhaseOutline || paintInfo.phase == PaintPhaseSelfOutline)
226         return;
227
228     // An empty viewBox also disables rendering.
229     // (http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute)
230     SVGSVGElement* svg = toSVGSVGElement(node());
231     ASSERT(svg);
232     if (svg->hasEmptyViewBox())
233         return;
234
235     // Don't paint if we don't have kids, except if we have filters we should paint those.
236     if (!firstChild()) {
237         SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(this);
238         if (!resources || !resources->filter())
239             return;
240     }
241
242     // Make a copy of the PaintInfo because applyTransform will modify the damage rect.
243     PaintInfo childPaintInfo(paintInfo);
244     GraphicsContextStateSaver stateSaver(*childPaintInfo.context);
245
246     // Apply initial viewport clip
247     if (shouldApplyViewportClip())
248         childPaintInfo.context->clip(pixelSnappedIntRect(overflowClipRect(paintOffset)));
249
250     // Convert from container offsets (html renderers) to a relative transform (svg renderers).
251     // Transform from our paint container's coordinate system to our local coords.
252     IntPoint adjustedPaintOffset = roundedIntPoint(paintOffset);
253     childPaintInfo.applyTransform(AffineTransform::translation(adjustedPaintOffset.x(), adjustedPaintOffset.y()) * localToBorderBoxTransform());
254
255     SVGRenderingContext renderingContext;
256     if (childPaintInfo.phase == PaintPhaseForeground) {
257         renderingContext.prepareToRenderSVGContent(this, childPaintInfo);
258         if (!renderingContext.isRenderingPrepared())
259             return;
260     }
261
262     RenderBox::paint(childPaintInfo, LayoutPoint());
263 }
264
265 void RenderSVGRoot::willBeDestroyed()
266 {
267     RenderBlock::removePercentHeightDescendant(const_cast<RenderSVGRoot*>(this));
268
269     SVGResourcesCache::clientDestroyed(this);
270     RenderReplaced::willBeDestroyed();
271 }
272
273 void RenderSVGRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
274 {
275     if (diff.needsFullLayout())
276         setNeedsBoundariesUpdate();
277     if (diff.needsPaintInvalidation()) {
278         // Box decorations may have appeared/disappeared - recompute status.
279         m_hasBoxDecorationBackground = calculateHasBoxDecorations();
280     }
281
282     RenderReplaced::styleDidChange(diff, oldStyle);
283     SVGResourcesCache::clientStyleChanged(this, diff, style());
284 }
285
286 bool RenderSVGRoot::isChildAllowed(RenderObject* child, RenderStyle*) const
287 {
288     return child->isSVG() && !(child->isSVGInline() || child->isSVGInlineText());
289 }
290
291 void RenderSVGRoot::addChild(RenderObject* child, RenderObject* beforeChild)
292 {
293     RenderReplaced::addChild(child, beforeChild);
294     SVGResourcesCache::clientWasAddedToTree(child, child->style());
295 }
296
297 void RenderSVGRoot::removeChild(RenderObject* child)
298 {
299     SVGResourcesCache::clientWillBeRemovedFromTree(child);
300     RenderReplaced::removeChild(child);
301 }
302
303 void RenderSVGRoot::insertedIntoTree()
304 {
305     RenderReplaced::insertedIntoTree();
306     SVGResourcesCache::clientWasAddedToTree(this, style());
307 }
308
309 void RenderSVGRoot::willBeRemovedFromTree()
310 {
311     SVGResourcesCache::clientWillBeRemovedFromTree(this);
312     RenderReplaced::willBeRemovedFromTree();
313 }
314
315 // RenderBox methods will expect coordinates w/o any transforms in coordinates
316 // relative to our borderBox origin.  This method gives us exactly that.
317 void RenderSVGRoot::buildLocalToBorderBoxTransform()
318 {
319     SVGSVGElement* svg = toSVGSVGElement(node());
320     ASSERT(svg);
321     float scale = style()->effectiveZoom();
322     FloatPoint translate = svg->currentTranslate();
323     LayoutSize borderAndPadding(borderLeft() + paddingLeft(), borderTop() + paddingTop());
324     m_localToBorderBoxTransform = svg->viewBoxToViewTransform(contentWidth() / scale, contentHeight() / scale);
325     AffineTransform viewToBorderBoxTransform(scale, 0, 0, scale, borderAndPadding.width() + translate.x(), borderAndPadding.height() + translate.y());
326     if (viewToBorderBoxTransform.isIdentity())
327         return;
328     m_localToBorderBoxTransform = viewToBorderBoxTransform * m_localToBorderBoxTransform;
329 }
330
331 const AffineTransform& RenderSVGRoot::localToParentTransform() const
332 {
333     // Slightly optimized version of m_localToParentTransform = AffineTransform::translation(x(), y()) * m_localToBorderBoxTransform;
334     m_localToParentTransform = m_localToBorderBoxTransform;
335     if (x())
336         m_localToParentTransform.setE(m_localToParentTransform.e() + roundToInt(x()));
337     if (y())
338         m_localToParentTransform.setF(m_localToParentTransform.f() + roundToInt(y()));
339     return m_localToParentTransform;
340 }
341
342 LayoutRect RenderSVGRoot::clippedOverflowRectForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer, const PaintInvalidationState* paintInvalidationState) const
343 {
344     // This is an open-coded aggregate of SVGRenderSupport::clippedOverflowRectForPaintInvalidation,
345     // RenderSVGRoot::computeFloatRectForPaintInvalidation and RenderReplaced::clippedOverflowRectForPaintInvalidation.
346     // The reason for this is to optimize/minimize the paint invalidation rect when the box is not "decorated"
347     // (does not have background/border/etc.)
348
349     // Return early for any cases where we don't actually paint.
350     if (style()->visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent())
351         return LayoutRect();
352
353     // Compute the paint invalidation rect of the content of the SVG in the border-box coordinate space.
354     FloatRect contentPaintInvalidationRect = paintInvalidationRectInLocalCoordinates();
355     contentPaintInvalidationRect = m_localToBorderBoxTransform.mapRect(contentPaintInvalidationRect);
356
357     // Apply initial viewport clip, overflow:visible content is added to visualOverflow
358     // but the most common case is that overflow is hidden, so always intersect.
359     contentPaintInvalidationRect.intersect(pixelSnappedBorderBoxRect());
360
361     LayoutRect paintInvalidationRect = enclosingLayoutRect(contentPaintInvalidationRect);
362     // If the box is decorated or is overflowing, extend it to include the border-box and overflow.
363     if (m_hasBoxDecorationBackground || hasRenderOverflow()) {
364         // The selectionRect can project outside of the overflowRect, so take their union
365         // for paint invalidation to avoid selection painting glitches.
366         LayoutRect decoratedPaintInvalidationRect = unionRect(localSelectionRect(false), visualOverflowRect());
367         paintInvalidationRect.unite(decoratedPaintInvalidationRect);
368     }
369
370     // Compute the paint invalidation rect in the parent coordinate space.
371     LayoutRect rect = enclosingIntRect(paintInvalidationRect);
372     RenderReplaced::mapRectToPaintInvalidationBacking(paintInvalidationContainer, rect, paintInvalidationState);
373     return rect;
374 }
375
376 void RenderSVGRoot::computeFloatRectForPaintInvalidation(const RenderLayerModelObject* paintInvalidationContainer, FloatRect& paintInvalidationRect, const PaintInvalidationState* paintInvalidationState) const
377 {
378     // Apply our local transforms (except for x/y translation), then our shadow,
379     // and then call RenderBox's method to handle all the normal CSS Box model bits
380     paintInvalidationRect = m_localToBorderBoxTransform.mapRect(paintInvalidationRect);
381
382     // Apply initial viewport clip
383     if (shouldApplyViewportClip())
384         paintInvalidationRect.intersect(pixelSnappedBorderBoxRect());
385
386     LayoutRect rect = enclosingIntRect(paintInvalidationRect);
387     RenderReplaced::mapRectToPaintInvalidationBacking(paintInvalidationContainer, rect, paintInvalidationState);
388     paintInvalidationRect = rect;
389 }
390
391 // This method expects local CSS box coordinates.
392 // Callers with local SVG viewport coordinates should first apply the localToBorderBoxTransform
393 // to convert from SVG viewport coordinates to local CSS box coordinates.
394 void RenderSVGRoot::mapLocalToContainer(const RenderLayerModelObject* paintInvalidationContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed, const PaintInvalidationState* paintInvalidationState) const
395 {
396     ASSERT(mode & ~IsFixed); // We should have no fixed content in the SVG rendering tree.
397     // We used to have this ASSERT here, but we removed it when enabling layer squashing.
398     // See http://crbug.com/364901
399     // ASSERT(mode & UseTransforms); // mapping a point through SVG w/o respecting trasnforms is useless.
400
401     RenderReplaced::mapLocalToContainer(paintInvalidationContainer, transformState, mode | ApplyContainerFlip, wasFixed, paintInvalidationState);
402 }
403
404 const RenderObject* RenderSVGRoot::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
405 {
406     return RenderReplaced::pushMappingToContainer(ancestorToStopAt, geometryMap);
407 }
408
409 void RenderSVGRoot::updateCachedBoundaries()
410 {
411     SVGRenderSupport::computeContainerBoundingBoxes(this, m_objectBoundingBox, m_objectBoundingBoxValid, m_strokeBoundingBox, m_paintInvalidationBoundingBox);
412     SVGRenderSupport::intersectPaintInvalidationRectWithResources(this, m_paintInvalidationBoundingBox);
413 }
414
415 bool RenderSVGRoot::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
416 {
417     LayoutPoint pointInParent = locationInContainer.point() - toLayoutSize(accumulatedOffset);
418     LayoutPoint pointInBorderBox = pointInParent - toLayoutSize(location());
419
420     // Only test SVG content if the point is in our content box, or in case we
421     // don't clip to the viewport, the visual overflow rect.
422     // FIXME: This should be an intersection when rect-based hit tests are supported by nodeAtFloatPoint.
423     if (contentBoxRect().contains(pointInBorderBox) || (!shouldApplyViewportClip() && visualOverflowRect().contains(pointInBorderBox))) {
424         const AffineTransform& localToParentTransform = this->localToParentTransform();
425         if (localToParentTransform.isInvertible()) {
426             FloatPoint localPoint = localToParentTransform.inverse().mapPoint(FloatPoint(pointInParent));
427
428             for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
429                 // FIXME: nodeAtFloatPoint() doesn't handle rect-based hit tests yet.
430                 if (child->nodeAtFloatPoint(request, result, localPoint, hitTestAction)) {
431                     updateHitTestResult(result, pointInBorderBox);
432                     if (!result.addNodeToRectBasedTestResult(child->node(), request, locationInContainer))
433                         return true;
434                 }
435             }
436         }
437     }
438
439     // 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.
440     if ((hitTestAction == HitTestBlockBackground || hitTestAction == HitTestChildBlockBackground) && visibleToHitTestRequest(request)) {
441         // Only return true here, if the last hit testing phase 'BlockBackground' (or 'ChildBlockBackground' - depending on context) is executed.
442         // If we'd return true in the 'Foreground' phase, hit testing would stop immediately. For SVG only trees this doesn't matter.
443         // Though when we have a <foreignObject> subtree we need to be able to detect hits on the background of a <div> element.
444         // If we'd return true here in the 'Foreground' phase, we are not able to detect these hits anymore.
445         LayoutRect boundsRect(accumulatedOffset + location(), size());
446         if (locationInContainer.intersects(boundsRect)) {
447             updateHitTestResult(result, pointInBorderBox);
448             if (!result.addNodeToRectBasedTestResult(node(), request, locationInContainer, boundsRect))
449                 return true;
450         }
451     }
452
453     return false;
454 }
455
456 }