- add third_party src.
[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/page/Chrome.h"
29 #include "core/page/ChromeClient.h"
30 #include "core/frame/Frame.h"
31 #include "core/page/Page.h"
32 #include "core/platform/graphics/GraphicsContext.h"
33 #include "core/rendering/HitTestResult.h"
34 #include "core/rendering/LayoutRepainter.h"
35 #include "core/rendering/RenderPart.h"
36 #include "core/rendering/RenderView.h"
37 #include "core/rendering/svg/RenderSVGResourceContainer.h"
38 #include "core/rendering/svg/SVGRenderingContext.h"
39 #include "core/rendering/svg/SVGResources.h"
40 #include "core/rendering/svg/SVGResourcesCache.h"
41 #include "core/svg/SVGElement.h"
42 #include "core/svg/SVGSVGElement.h"
43 #include "core/svg/graphics/SVGImage.h"
44
45 using namespace std;
46
47 namespace WebCore {
48
49 RenderSVGRoot::RenderSVGRoot(SVGElement* node)
50     : RenderReplaced(node)
51     , m_objectBoundingBoxValid(false)
52     , m_isLayoutSizeChanged(false)
53     , m_needsBoundariesOrTransformUpdate(true)
54 {
55 }
56
57 RenderSVGRoot::~RenderSVGRoot()
58 {
59 }
60
61 void RenderSVGRoot::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio, bool& isPercentageIntrinsicSize) const
62 {
63     // Spec: http://www.w3.org/TR/SVG/coords.html#IntrinsicSizing
64     // SVG needs to specify how to calculate some intrinsic sizing properties to enable inclusion within other languages.
65     // The intrinsic width and height of the viewport of SVG content must be determined from the ‘width’ and ‘height’ attributes.
66     // If either of these are not specified, a value of '100%' must be assumed. Note: the ‘width’ and ‘height’ attributes are not
67     // the same as the CSS width and height properties. Specifically, percentage values do not provide an intrinsic width or height,
68     // and do not indicate a percentage of the containing block. Rather, once the viewport is established, they indicate the portion
69     // of the viewport that is actually covered by image data.
70     SVGSVGElement* svg = toSVGSVGElement(node());
71     ASSERT(svg);
72     Length intrinsicWidthAttribute = svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties);
73     Length intrinsicHeightAttribute = svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties);
74
75     // The intrinsic aspect ratio of the viewport of SVG content is necessary for example, when including SVG from an ‘object’
76     // element in HTML styled with CSS. It is possible (indeed, common) for an SVG graphic to have an intrinsic aspect ratio but
77     // not to have an intrinsic width or height. The intrinsic aspect ratio must be calculated based upon the following rules:
78     // - 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 (in, mm, cm, pt, pc,
80     //   px, em, ex) or in user units, then the aspect ratio is calculated from the ‘width’ and ‘height’ attributes after
81     //   resolving both values to user units.
82     if (intrinsicWidthAttribute.isFixed() || intrinsicHeightAttribute.isFixed()) {
83         if (intrinsicWidthAttribute.isFixed())
84             intrinsicSize.setWidth(floatValueForLength(intrinsicWidthAttribute, 0, 0));
85         if (intrinsicHeightAttribute.isFixed())
86             intrinsicSize.setHeight(floatValueForLength(intrinsicHeightAttribute, 0, 0));
87         if (!intrinsicSize.isEmpty())
88             intrinsicRatio = intrinsicSize.width() / static_cast<double>(intrinsicSize.height());
89         return;
90     }
91
92     // - If either/both of the ‘width’ and ‘height’ of the rootmost ‘svg’ element are in percentage units (or omitted), the
93     //   aspect ratio is calculated from the width and height values of the ‘viewBox’ specified for the current SVG document
94     //   fragment. If the ‘viewBox’ is not correctly specified, or set to 'none', the intrinsic aspect ratio cannot be
95     //   calculated and is considered unspecified.
96     intrinsicSize = svg->viewBoxCurrentValue().size();
97     if (!intrinsicSize.isEmpty()) {
98         // The viewBox can only yield an intrinsic ratio, not an intrinsic size.
99         intrinsicRatio = intrinsicSize.width() / static_cast<double>(intrinsicSize.height());
100         intrinsicSize = FloatSize();
101         return;
102     }
103
104     // If our intrinsic size is in percentage units, return those to the caller through the intrinsicSize. Notify the caller
105     // about the special situation, by setting isPercentageIntrinsicSize=true, so it knows how to interpret the return values.
106     if (intrinsicWidthAttribute.isPercent() && intrinsicHeightAttribute.isPercent()) {
107         isPercentageIntrinsicSize = true;
108         intrinsicSize = FloatSize(intrinsicWidthAttribute.percent(), intrinsicHeightAttribute.percent());
109     }
110 }
111
112 bool RenderSVGRoot::isEmbeddedThroughSVGImage() const
113 {
114     return SVGImage::isInSVGImage(toSVGSVGElement(node()));
115 }
116
117 bool RenderSVGRoot::isEmbeddedThroughFrameContainingSVGDocument() const
118 {
119     if (!node())
120         return false;
121
122     Frame* frame = node()->document().frame();
123     if (!frame)
124         return false;
125
126     // If our frame has an owner renderer, we're embedded through eg. object/embed/iframe,
127     // but we only negotiate if we're in an SVG document.
128     if (!frame->ownerRenderer())
129         return false;
130     return frame->document()->isSVGDocument();
131 }
132
133 static inline LayoutUnit resolveLengthAttributeForSVG(const Length& length, float scale, float maxSize, RenderView* renderView)
134 {
135     return static_cast<LayoutUnit>(valueForLength(length, maxSize, renderView) * (length.isFixed() ? scale : 1));
136 }
137
138 LayoutUnit RenderSVGRoot::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
139 {
140     SVGSVGElement* svg = toSVGSVGElement(node());
141     ASSERT(svg);
142
143     // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
144     if (!m_containerSize.isEmpty())
145         return m_containerSize.width();
146
147     if (style()->logicalWidth().isSpecified() || style()->logicalMaxWidth().isSpecified())
148         return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
149
150     if (svg->widthAttributeEstablishesViewport())
151         return resolveLengthAttributeForSVG(svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties), style()->effectiveZoom(), containingBlock()->availableLogicalWidth(), view());
152
153     // SVG embedded through object/embed/iframe.
154     if (isEmbeddedThroughFrameContainingSVGDocument())
155         return document().frame()->ownerRenderer()->availableLogicalWidth();
156
157     // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
158     return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
159 }
160
161 LayoutUnit RenderSVGRoot::computeReplacedLogicalHeight() const
162 {
163     SVGSVGElement* svg = toSVGSVGElement(node());
164     ASSERT(svg);
165
166     // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
167     if (!m_containerSize.isEmpty())
168         return m_containerSize.height();
169
170     if (style()->logicalHeight().isSpecified() || style()->logicalMaxHeight().isSpecified())
171         return RenderReplaced::computeReplacedLogicalHeight();
172
173     if (svg->heightAttributeEstablishesViewport()) {
174         Length height = svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties);
175         if (height.isPercent()) {
176             RenderBlock* cb = containingBlock();
177             ASSERT(cb);
178             while (cb->isAnonymous()) {
179                 cb = cb->containingBlock();
180                 cb->addPercentHeightDescendant(const_cast<RenderSVGRoot*>(this));
181             }
182         } else
183             RenderBlock::removePercentHeightDescendant(const_cast<RenderSVGRoot*>(this));
184
185         return resolveLengthAttributeForSVG(height, style()->effectiveZoom(), containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding), view());
186     }
187
188     // SVG embedded through object/embed/iframe.
189     if (isEmbeddedThroughFrameContainingSVGDocument())
190         return document().frame()->ownerRenderer()->availableLogicalHeight(IncludeMarginBorderPadding);
191
192     // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
193     return RenderReplaced::computeReplacedLogicalHeight();
194 }
195
196 void RenderSVGRoot::layout()
197 {
198     ASSERT(needsLayout());
199
200     // Arbitrary affine transforms are incompatible with LayoutState.
201     LayoutStateDisabler layoutStateDisabler(view());
202
203     bool needsLayout = selfNeedsLayout();
204     LayoutRepainter repainter(*this, checkForRepaintDuringLayout() && needsLayout);
205
206     LayoutSize oldSize = size();
207     updateLogicalWidth();
208     updateLogicalHeight();
209     buildLocalToBorderBoxTransform();
210
211     SVGRenderSupport::layoutResourcesIfNeeded(this);
212
213     SVGSVGElement* svg = toSVGSVGElement(node());
214     ASSERT(svg);
215     m_isLayoutSizeChanged = needsLayout || (svg->hasRelativeLengths() && oldSize != size());
216     SVGRenderSupport::layoutChildren(this, needsLayout || SVGRenderSupport::filtersForceContainerLayout(this));
217
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;
223     }
224
225     updateLayerTransform();
226
227     repainter.repaintAfterLayout();
228
229     clearNeedsLayout();
230 }
231
232 void RenderSVGRoot::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
233 {
234     // An empty viewport disables rendering.
235     if (pixelSnappedBorderBoxRect().isEmpty())
236         return;
237
238     // Don't paint, if the context explicitly disabled it.
239     if (paintInfo.context->paintingDisabled())
240         return;
241
242     // An empty viewBox also disables rendering.
243     // (http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute)
244     SVGSVGElement* svg = toSVGSVGElement(node());
245     ASSERT(svg);
246     if (svg->hasEmptyViewBox())
247         return;
248
249     // Don't paint if we don't have kids, except if we have filters we should paint those.
250     if (!firstChild()) {
251         SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(this);
252         if (!resources || !resources->filter())
253             return;
254     }
255
256     // Make a copy of the PaintInfo because applyTransform will modify the damage rect.
257     PaintInfo childPaintInfo(paintInfo);
258     childPaintInfo.context->save();
259
260     // Apply initial viewport clip - not affected by overflow handling
261     childPaintInfo.context->clip(pixelSnappedIntRect(overflowClipRect(paintOffset, paintInfo.renderRegion)));
262
263     // Convert from container offsets (html renderers) to a relative transform (svg renderers).
264     // Transform from our paint container's coordinate system to our local coords.
265     IntPoint adjustedPaintOffset = roundedIntPoint(paintOffset);
266     childPaintInfo.applyTransform(AffineTransform::translation(adjustedPaintOffset.x(), adjustedPaintOffset.y()) * localToBorderBoxTransform());
267
268     // SVGRenderingContext must be destroyed before we restore the childPaintInfo.context, because a filter may have
269     // changed the context and it is only reverted when the SVGRenderingContext destructor finishes applying the filter.
270     {
271         SVGRenderingContext renderingContext;
272         bool continueRendering = true;
273         if (childPaintInfo.phase == PaintPhaseForeground) {
274             renderingContext.prepareToRenderSVGContent(this, childPaintInfo);
275             continueRendering = renderingContext.isRenderingPrepared();
276         }
277
278         if (continueRendering)
279             RenderBox::paint(childPaintInfo, LayoutPoint());
280     }
281
282     childPaintInfo.context->restore();
283 }
284
285 void RenderSVGRoot::willBeDestroyed()
286 {
287     RenderBlock::removePercentHeightDescendant(const_cast<RenderSVGRoot*>(this));
288
289     SVGResourcesCache::clientDestroyed(this);
290     RenderReplaced::willBeDestroyed();
291 }
292
293 void RenderSVGRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
294 {
295     if (diff == StyleDifferenceLayout)
296         setNeedsBoundariesUpdate();
297
298     RenderReplaced::styleDidChange(diff, oldStyle);
299     SVGResourcesCache::clientStyleChanged(this, diff, style());
300 }
301
302 void RenderSVGRoot::addChild(RenderObject* child, RenderObject* beforeChild)
303 {
304     RenderReplaced::addChild(child, beforeChild);
305     SVGResourcesCache::clientWasAddedToTree(child, child->style());
306 }
307
308 void RenderSVGRoot::removeChild(RenderObject* child)
309 {
310     SVGResourcesCache::clientWillBeRemovedFromTree(child);
311     RenderReplaced::removeChild(child);
312 }
313
314 void RenderSVGRoot::insertedIntoTree()
315 {
316     RenderReplaced::insertedIntoTree();
317     SVGResourcesCache::clientWasAddedToTree(this, style());
318 }
319
320 void RenderSVGRoot::willBeRemovedFromTree()
321 {
322     SVGResourcesCache::clientWillBeRemovedFromTree(this);
323     RenderReplaced::willBeRemovedFromTree();
324 }
325
326 // RenderBox methods will expect coordinates w/o any transforms in coordinates
327 // relative to our borderBox origin.  This method gives us exactly that.
328 void RenderSVGRoot::buildLocalToBorderBoxTransform()
329 {
330     SVGSVGElement* svg = toSVGSVGElement(node());
331     ASSERT(svg);
332     float scale = style()->effectiveZoom();
333     SVGPoint translate = svg->currentTranslate();
334     LayoutSize borderAndPadding(borderLeft() + paddingLeft(), borderTop() + paddingTop());
335     m_localToBorderBoxTransform = svg->viewBoxToViewTransform(contentWidth() / scale, contentHeight() / scale);
336     if (borderAndPadding.isEmpty() && scale == 1 && translate == SVGPoint::zero())
337         return;
338     m_localToBorderBoxTransform = AffineTransform(scale, 0, 0, scale, borderAndPadding.width() + translate.x(), borderAndPadding.height() + translate.y()) * m_localToBorderBoxTransform;
339 }
340
341 const AffineTransform& RenderSVGRoot::localToParentTransform() const
342 {
343     // Slightly optimized version of m_localToParentTransform = AffineTransform::translation(x(), y()) * m_localToBorderBoxTransform;
344     m_localToParentTransform = m_localToBorderBoxTransform;
345     if (x())
346         m_localToParentTransform.setE(m_localToParentTransform.e() + roundToInt(x()));
347     if (y())
348         m_localToParentTransform.setF(m_localToParentTransform.f() + roundToInt(y()));
349     return m_localToParentTransform;
350 }
351
352 LayoutRect RenderSVGRoot::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
353 {
354     return SVGRenderSupport::clippedOverflowRectForRepaint(this, repaintContainer);
355 }
356
357 void RenderSVGRoot::computeFloatRectForRepaint(const RenderLayerModelObject* repaintContainer, FloatRect& repaintRect, bool fixed) const
358 {
359     // Apply our local transforms (except for x/y translation), then our shadow,
360     // and then call RenderBox's method to handle all the normal CSS Box model bits
361     repaintRect = m_localToBorderBoxTransform.mapRect(repaintRect);
362
363     // Apply initial viewport clip - not affected by overflow settings
364     repaintRect.intersect(pixelSnappedBorderBoxRect());
365
366     LayoutRect rect = enclosingIntRect(repaintRect);
367     RenderReplaced::computeRectForRepaint(repaintContainer, rect, fixed);
368     repaintRect = rect;
369 }
370
371 // This method expects local CSS box coordinates.
372 // Callers with local SVG viewport coordinates should first apply the localToBorderBoxTransform
373 // to convert from SVG viewport coordinates to local CSS box coordinates.
374 void RenderSVGRoot::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
375 {
376     ASSERT(mode & ~IsFixed); // We should have no fixed content in the SVG rendering tree.
377     ASSERT(mode & UseTransforms); // mapping a point through SVG w/o respecting trasnforms is useless.
378
379     RenderReplaced::mapLocalToContainer(repaintContainer, transformState, mode | ApplyContainerFlip, wasFixed);
380 }
381
382 const RenderObject* RenderSVGRoot::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
383 {
384     return RenderReplaced::pushMappingToContainer(ancestorToStopAt, geometryMap);
385 }
386
387 void RenderSVGRoot::updateCachedBoundaries()
388 {
389     SVGRenderSupport::computeContainerBoundingBoxes(this, m_objectBoundingBox, m_objectBoundingBoxValid, m_strokeBoundingBox, m_repaintBoundingBox);
390     SVGRenderSupport::intersectRepaintRectWithResources(this, m_repaintBoundingBox);
391     m_repaintBoundingBox.inflate(borderAndPaddingWidth());
392 }
393
394 bool RenderSVGRoot::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
395 {
396     LayoutPoint pointInParent = locationInContainer.point() - toLayoutSize(accumulatedOffset);
397     LayoutPoint pointInBorderBox = pointInParent - toLayoutSize(location());
398
399     // Only test SVG content if the point is in our content box.
400     // FIXME: This should be an intersection when rect-based hit tests are supported by nodeAtFloatPoint.
401     if (contentBoxRect().contains(pointInBorderBox)) {
402         FloatPoint localPoint = localToParentTransform().inverse().mapPoint(FloatPoint(pointInParent));
403
404         for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
405             // FIXME: nodeAtFloatPoint() doesn't handle rect-based hit tests yet.
406             if (child->nodeAtFloatPoint(request, result, localPoint, hitTestAction)) {
407                 updateHitTestResult(result, pointInBorderBox);
408                 if (!result.addNodeToRectBasedTestResult(child->node(), request, locationInContainer))
409                     return true;
410             }
411         }
412     }
413
414     // 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.
415     if (hitTestAction == HitTestBlockBackground && visibleToHitTestRequest(request)) {
416         // Only return true here, if the last hit testing phase 'BlockBackground' is executed. If we'd return true in the 'Foreground' phase,
417         // hit testing would stop immediately. For SVG only trees this doesn't matter. Though when we have a <foreignObject> subtree we need
418         // 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
419         // to detect these hits anymore.
420         LayoutRect boundsRect(accumulatedOffset + location(), size());
421         if (locationInContainer.intersects(boundsRect)) {
422             updateHitTestResult(result, pointInBorderBox);
423             if (!result.addNodeToRectBasedTestResult(node(), request, locationInContainer, boundsRect))
424                 return true;
425         }
426     }
427
428     return false;
429 }
430
431 bool RenderSVGRoot::hasRelativeDimensions() const
432 {
433     SVGSVGElement* svg = toSVGSVGElement(node());
434     ASSERT(svg);
435
436     return svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties).isPercent() || svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties).isPercent();
437 }
438
439 bool RenderSVGRoot::hasRelativeIntrinsicLogicalWidth() const
440 {
441     SVGSVGElement* svg = toSVGSVGElement(node());
442     ASSERT(svg);
443     return svg->intrinsicWidth(SVGSVGElement::IgnoreCSSProperties).isPercent();
444 }
445
446 bool RenderSVGRoot::hasRelativeLogicalHeight() const
447 {
448     SVGSVGElement* svg = toSVGSVGElement(node());
449     ASSERT(svg);
450
451     return svg->intrinsicHeight(SVGSVGElement::IgnoreCSSProperties).isPercent();
452 }
453
454 }