7d411da82c56e68b8c7d46020be0f4e60b77c0bc
[framework/web/webkit-efl.git] / Source / WebCore / 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 #if ENABLE(SVG)
27 #include "RenderSVGRoot.h"
28
29 #include "Frame.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"
44
45 #if ENABLE(FILTERS)
46 #include "RenderSVGResourceFilter.h"
47 #endif
48
49 using namespace std;
50
51 namespace WebCore {
52
53 RenderSVGRoot::RenderSVGRoot(SVGStyledElement* node)
54     : RenderBox(node)
55     , m_isLayoutSizeChanged(false)
56     , m_needsBoundariesOrTransformUpdate(true)
57     , m_needsSizeNegotiationWithHostDocument(false)
58 {
59     setReplaced(true);
60 }
61
62 RenderSVGRoot::~RenderSVGRoot()
63 {
64 }
65
66 void RenderSVGRoot::computeIntrinsicRatioInformation(FloatSize& intrinsicRatio, bool& isPercentageIntrinsicSize) const
67 {
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.
74
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());
81         return;
82     }
83
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();
89
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());
95     }
96 }
97
98 void RenderSVGRoot::computePreferredLogicalWidths()
99 {
100     ASSERT(preferredLogicalWidthsDirty());
101
102     LayoutUnit borderAndPadding = borderAndPaddingWidth();
103     LayoutUnit width = computeReplacedLogicalWidth(false) + borderAndPadding;
104
105     if (style()->maxWidth().isFixed())
106         width = min(width, style()->maxWidth().value() + (style()->boxSizing() == CONTENT_BOX ? borderAndPadding : 0));
107
108     if (style()->width().isPercent() || (style()->width().isAuto() && style()->height().isPercent())) {
109         m_minPreferredLogicalWidth = 0;
110         m_maxPreferredLogicalWidth = width;
111     } else
112         m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = width;
113
114     setPreferredLogicalWidthsDirty(false);
115 }
116
117 LayoutUnit RenderSVGRoot::computeIntrinsicWidth(LayoutUnit replacedWidth) const
118 {
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()));
123 }
124
125 LayoutUnit RenderSVGRoot::computeIntrinsicHeight(LayoutUnit replacedHeight) const
126 {
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()));
131 }
132
133 LayoutUnit RenderSVGRoot::computeReplacedLogicalWidth(bool includeMaxWidth) const
134 {
135     LayoutUnit replacedWidth = RenderBox::computeReplacedLogicalWidth(includeMaxWidth);
136     Frame* frame = node() && node()->document() ? node()->document()->frame() : 0;
137     if (!frame)
138         return computeIntrinsicWidth(replacedWidth);
139
140     // If our frame has an owner renderer, we're embedded through eg. object/embed.
141     RenderPart* ownerRenderer = frame->ownerRenderer();
142     if (!ownerRenderer)
143         return computeIntrinsicWidth(replacedWidth);
144
145     RenderStyle* ownerRendererStyle = ownerRenderer->style();
146     ASSERT(ownerRendererStyle);
147     ASSERT(frame->contentRenderer());
148
149     Length ownerWidth = ownerRendererStyle->width();
150     if (ownerWidth.isAuto())
151         return replacedWidth;
152
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.
161
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.
169     //
170     // Under these conditions, the positioning properties establish the viewport's width.
171     return ownerRenderer->computeReplacedLogicalWidthRespectingMinMaxWidth(ownerRenderer->computeReplacedLogicalWidthUsing(ownerWidth), includeMaxWidth);
172 }
173
174 LayoutUnit RenderSVGRoot::computeReplacedLogicalHeight() const
175 {
176     LayoutUnit replacedHeight = RenderBox::computeReplacedLogicalHeight();
177
178     Frame* frame = node() && node()->document() ? node()->document()->frame() : 0;
179     if (!frame)
180         return computeIntrinsicHeight(replacedHeight);
181
182     // If our frame has an owner renderer, we're embedded through eg. object/embed.
183     RenderPart* ownerRenderer = frame->ownerRenderer();
184     if (!ownerRenderer)
185         return computeIntrinsicHeight(replacedHeight);
186
187     RenderStyle* ownerRendererStyle = ownerRenderer->style();
188     ASSERT(ownerRendererStyle);
189     ASSERT(frame->contentRenderer());
190
191     Length ownerHeight = ownerRendererStyle->height();
192     if (ownerHeight.isAuto())
193         return replacedHeight;
194
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));
201 }
202
203 void RenderSVGRoot::layout()
204 {
205     ASSERT(needsLayout());
206
207     // Arbitrary affine transforms are incompatible with LayoutState.
208     LayoutStateDisabler layoutStateDisabler(view());
209
210     bool needsLayout = selfNeedsLayout();
211     LayoutRepainter repainter(*this, checkForRepaintDuringLayout() && needsLayout);
212
213     LayoutSize oldSize(width(), height());
214     computeLogicalWidth();
215     computeLogicalHeight();
216     calcViewport();
217
218     SVGSVGElement* svg = static_cast<SVGSVGElement*>(node());
219     m_isLayoutSizeChanged = svg->hasRelativeLengths() && oldSize != size();
220  
221     if (view() && view()->frameView() && view()->frameView()->embeddedContentBox()) {
222         if (!m_needsSizeNegotiationWithHostDocument)
223             m_needsSizeNegotiationWithHostDocument = !m_everHadLayout || oldSize != size();
224     } else
225         ASSERT(!m_needsSizeNegotiationWithHostDocument);
226
227     SVGRenderSupport::layoutChildren(this, needsLayout);
228     m_isLayoutSizeChanged = false;
229
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;
235     }
236
237     repainter.repaintAfterLayout();
238
239     setNeedsLayout(false);
240 }
241
242 bool RenderSVGRoot::selfWillPaint()
243 {
244 #if ENABLE(FILTERS)
245     SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(this);
246     return resources && resources->filter();
247 #else
248     return false;
249 #endif
250 }
251
252 void RenderSVGRoot::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
253 {
254     if (paintInfo.context->paintingDisabled())
255         return;
256
257     bool isVisible = style()->visibility() == VISIBLE;
258     LayoutPoint borderBoxOriginInContainer = paintOffset + parentOriginToBorderBox();
259
260     if (hasBoxDecorations() && (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseChildBlockBackground) && isVisible)
261         paintBoxDecorations(paintInfo, borderBoxOriginInContainer);
262
263     if (paintInfo.phase == PaintPhaseBlockBackground)
264         return;
265
266     // An empty viewport disables rendering.  FIXME: Should we still render filters?
267     if (m_viewportSize.isEmpty())
268         return;
269
270     // Don't paint if we don't have kids, except if we have filters we should paint those.
271     if (!firstChild() && !selfWillPaint())
272         return;
273
274     // Make a copy of the PaintInfo because applyTransform will modify the damage rect.
275     PaintInfo childPaintInfo(paintInfo);
276     childPaintInfo.context->save();
277
278     // Apply initial viewport clip - not affected by overflow handling
279     childPaintInfo.context->clip(overflowClipRect(borderBoxOriginInContainer, paintInfo.renderRegion));
280
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));
284
285     bool continueRendering = true;
286     if (childPaintInfo.phase == PaintPhaseForeground)
287         continueRendering = SVGRenderSupport::prepareToRenderSVGContent(this, childPaintInfo);
288
289     if (continueRendering)
290         RenderBox::paint(childPaintInfo, LayoutPoint());
291
292     if (childPaintInfo.phase == PaintPhaseForeground)
293         SVGRenderSupport::finishRenderSVGContent(this, childPaintInfo, paintInfo.context);
294
295     childPaintInfo.context->restore();
296
297     if ((paintInfo.phase == PaintPhaseOutline || paintInfo.phase == PaintPhaseSelfOutline) && style()->outlineWidth() && isVisible)
298         paintOutline(paintInfo.context, LayoutRect(borderBoxOriginInContainer, size()));
299 }
300
301 void RenderSVGRoot::willBeDestroyed()
302 {
303     SVGResourcesCache::clientDestroyed(this);
304     RenderBox::willBeDestroyed();
305 }
306
307 void RenderSVGRoot::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
308 {
309     if (diff == StyleDifferenceLayout)
310         setNeedsBoundariesUpdate();
311     RenderBox::styleWillChange(diff, newStyle);
312 }
313
314 void RenderSVGRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
315 {
316     RenderBox::styleDidChange(diff, oldStyle);
317     SVGResourcesCache::clientStyleChanged(this, diff, style());
318 }
319
320 void RenderSVGRoot::updateFromElement()
321 {
322     RenderBox::updateFromElement();
323     SVGResourcesCache::clientUpdatedFromElement(this, style());
324 }
325
326 void RenderSVGRoot::calcViewport()
327 {
328     SVGSVGElement* svg = static_cast<SVGSVGElement*>(node());
329
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());
334         return;
335     }
336
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));
344 }
345
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
349 {
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);
356 }
357
358 LayoutSize RenderSVGRoot::parentOriginToBorderBox() const
359 {
360     return locationOffset();
361 }
362
363 LayoutSize RenderSVGRoot::borderOriginToContentBox() const
364 {
365     return LayoutSize(borderLeft() + paddingLeft(), borderTop() + paddingTop());
366 }
367
368 AffineTransform RenderSVGRoot::localToRepaintContainerTransform(const LayoutPoint& parentOriginInContainer) const
369 {
370     return AffineTransform::translation(parentOriginInContainer.x(), parentOriginInContainer.y()) * localToParentTransform();
371 }
372
373 const AffineTransform& RenderSVGRoot::localToParentTransform() const
374 {
375     LayoutSize parentToBorderBoxOffset = parentOriginToBorderBox();
376
377     m_localToParentTransform = AffineTransform::translation(parentToBorderBoxOffset.width(), parentToBorderBoxOffset.height()) * localToBorderBoxTransform();
378
379     return m_localToParentTransform;
380 }
381
382 LayoutRect RenderSVGRoot::clippedOverflowRectForRepaint(RenderBoxModelObject* repaintContainer) const
383 {
384     return SVGRenderSupport::clippedOverflowRectForRepaint(this, repaintContainer);
385 }
386
387 void RenderSVGRoot::computeRectForRepaint(RenderBoxModelObject* repaintContainer, LayoutRect& repaintRect, bool fixed) const
388 {
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);
392
393     // Apply initial viewport clip - not affected by overflow settings    
394     repaintRect.intersect(enclosingLayoutRect(FloatRect(FloatPoint(), m_viewportSize)));
395
396     const SVGRenderStyle* svgStyle = style()->svgStyle();
397     if (const ShadowData* shadow = svgStyle->shadow())
398         shadow->adjustRectForShadow(repaintRect);
399
400     RenderBox::computeRectForRepaint(repaintContainer, repaintRect, fixed);
401 }
402
403 void RenderSVGRoot::mapLocalToContainer(RenderBoxModelObject* repaintContainer, bool fixed, bool useTransforms, TransformState& transformState, bool* wasFixed) const
404 {
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.
407
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);
411 }
412
413 void RenderSVGRoot::updateCachedBoundaries()
414 {
415     m_objectBoundingBox = FloatRect();
416     m_strokeBoundingBox = FloatRect();
417     m_repaintBoundingBox = FloatRect();
418
419     SVGRenderSupport::computeContainerBoundingBoxes(this, m_objectBoundingBox, m_strokeBoundingBox, m_repaintBoundingBox);
420     SVGRenderSupport::intersectRepaintRectWithResources(this, m_repaintBoundingBox);
421     m_repaintBoundingBox.inflate(borderAndPaddingWidth());
422 }
423
424 bool RenderSVGRoot::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
425 {
426     LayoutPoint pointInParent = pointInContainer - toLayoutSize(accumulatedOffset);
427     LayoutPoint pointInBorderBox = pointInParent - parentOriginToBorderBox();
428
429     // Note: For now, we're ignoring hits to border and padding for <svg>
430     LayoutPoint pointInContentBox = pointInBorderBox - borderOriginToContentBox();
431     if (!contentBoxRect().contains(pointInContentBox))
432         return false;
433
434     LayoutPoint localPoint = localToParentTransform().inverse().mapPoint(pointInParent);
435
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);
442             return true;
443         }
444     }
445
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));
453         return true;
454     }
455
456     return false;
457 }
458
459 }
460
461 #endif // ENABLE(SVG)