tizen beta release
[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 "Chrome.h"
30 #include "ChromeClient.h"
31 #include "Frame.h"
32 #include "GraphicsContext.h"
33 #include "HitTestResult.h"
34 #include "LayoutRepainter.h"
35 #include "Page.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"
48
49 #if ENABLE(FILTERS)
50 #include "RenderSVGResourceFilter.h"
51 #endif
52
53 using namespace std;
54
55 namespace WebCore {
56
57 RenderSVGRoot::RenderSVGRoot(SVGStyledElement* node)
58     : RenderBox(node)
59     , m_isLayoutSizeChanged(false)
60     , m_needsBoundariesOrTransformUpdate(true)
61     , m_needsSizeNegotiationWithHostDocument(false)
62 {
63     setReplaced(true);
64 }
65
66 RenderSVGRoot::~RenderSVGRoot()
67 {
68 }
69
70 void RenderSVGRoot::computeIntrinsicRatioInformation(FloatSize& intrinsicRatio, bool& isPercentageIntrinsicSize) const
71 {
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.
78
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());
85         return;
86     }
87
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();
93
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());
99     }
100 }
101
102 void RenderSVGRoot::computePreferredLogicalWidths()
103 {
104     ASSERT(preferredLogicalWidthsDirty());
105
106     LayoutUnit borderAndPadding = borderAndPaddingWidth();
107     LayoutUnit width = computeReplacedLogicalWidth(false) + borderAndPadding;
108
109     if (style()->maxWidth().isFixed())
110         width = min(width, style()->maxWidth().value() + (style()->boxSizing() == CONTENT_BOX ? borderAndPadding : 0));
111
112     if (style()->width().isPercent() || (style()->width().isAuto() && style()->height().isPercent())) {
113         m_minPreferredLogicalWidth = 0;
114         m_maxPreferredLogicalWidth = width;
115     } else
116         m_minPreferredLogicalWidth = m_maxPreferredLogicalWidth = width;
117
118     setPreferredLogicalWidthsDirty(false);
119 }
120
121 bool RenderSVGRoot::isEmbeddedThroughSVGImage() const
122 {
123     if (!node())
124         return false;
125
126     Frame* frame = node()->document()->frame();
127     if (!frame)
128         return false;
129
130     // Test whether we're embedded through an img.
131     if (!frame->page() || !frame->page()->chrome())
132         return false;
133
134     ChromeClient* chromeClient = frame->page()->chrome()->client();
135     if (!chromeClient || !chromeClient->isSVGImageChromeClient())
136         return false;
137
138     return true;
139 }
140
141 bool RenderSVGRoot::isEmbeddedThroughFrameContainingSVGDocument() const
142 {
143     if (!node())
144         return false;
145
146     Frame* frame = node()->document()->frame();
147     if (!frame)
148         return false;
149
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())
153         return false;
154     return frame->document()->isSVGDocument();
155 }
156
157 LayoutUnit RenderSVGRoot::computeReplacedLogicalWidth(bool includeMaxWidth) const
158 {
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;
163
164     replacedWidth = RenderBox::computeReplacedLogicalWidth(includeMaxWidth);
165     Frame* frame = node() && node()->document() ? node()->document()->frame() : 0;
166     if (!frame)
167         return replacedWidth;
168
169     if (!isEmbeddedThroughFrameContainingSVGDocument())
170         return replacedWidth;
171
172     RenderPart* ownerRenderer = frame->ownerRenderer();
173     RenderStyle* ownerRendererStyle = ownerRenderer->style();
174     ASSERT(ownerRendererStyle);
175     ASSERT(frame->contentRenderer());
176
177     Length ownerWidth = ownerRendererStyle->width();
178     if (ownerWidth.isAuto())
179         return replacedWidth;
180
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.
189
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.
197     //
198     // Under these conditions, the positioning properties establish the viewport's width.
199     return ownerRenderer->computeReplacedLogicalWidthRespectingMinMaxWidth(ownerRenderer->computeReplacedLogicalWidthUsing(ownerWidth), includeMaxWidth);
200 }
201
202 LayoutUnit RenderSVGRoot::computeReplacedLogicalHeight() const
203 {
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;
208
209     replacedHeight = RenderBox::computeReplacedLogicalHeight();
210     Frame* frame = node() && node()->document() ? node()->document()->frame() : 0;
211     if (!frame)
212         return replacedHeight;
213
214     if (!isEmbeddedThroughFrameContainingSVGDocument())
215         return replacedHeight;
216
217     RenderPart* ownerRenderer = frame->ownerRenderer();
218     ASSERT(ownerRenderer);
219
220     RenderStyle* ownerRendererStyle = ownerRenderer->style();
221     ASSERT(ownerRendererStyle);
222
223     Length ownerHeight = ownerRendererStyle->height();
224     if (ownerHeight.isAuto())
225         return replacedHeight;
226
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));
233 }
234
235 void RenderSVGRoot::layout()
236 {
237     ASSERT(needsLayout());
238
239     // Arbitrary affine transforms are incompatible with LayoutState.
240     LayoutStateDisabler layoutStateDisabler(view());
241
242     bool needsLayout = selfNeedsLayout();
243     LayoutRepainter repainter(*this, checkForRepaintDuringLayout() && needsLayout);
244
245     LayoutSize oldSize(width(), height());
246     computeLogicalWidth();
247     computeLogicalHeight();
248
249     SVGSVGElement* svg = static_cast<SVGSVGElement*>(node());
250     m_isLayoutSizeChanged = needsLayout || (svg->hasRelativeLengths() && oldSize != size());
251
252     if (view() && view()->frameView() && view()->frameView()->embeddedContentBox()) {
253         if (!m_needsSizeNegotiationWithHostDocument)
254             m_needsSizeNegotiationWithHostDocument = !m_everHadLayout || oldSize != size();
255     } else
256         ASSERT(!m_needsSizeNegotiationWithHostDocument);
257
258     SVGRenderSupport::layoutChildren(this, needsLayout || SVGRenderSupport::filtersForceContainerLayout(this));
259     m_isLayoutSizeChanged = false;
260
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;
266     }
267
268     repainter.repaintAfterLayout();
269
270     setNeedsLayout(false);
271 }
272
273 bool RenderSVGRoot::selfWillPaint()
274 {
275     SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(this);
276     return resources && resources->filter();
277 }
278
279 void RenderSVGRoot::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
280 {
281     if (paintInfo.context->paintingDisabled())
282         return;
283
284     bool isVisible = style()->visibility() == VISIBLE;
285     LayoutPoint borderBoxOriginInContainer = paintOffset + parentOriginToBorderBox();
286
287     if (hasBoxDecorations() && (paintInfo.phase == PaintPhaseBlockBackground || paintInfo.phase == PaintPhaseChildBlockBackground) && isVisible)
288         paintBoxDecorations(paintInfo, borderBoxOriginInContainer);
289
290     if (paintInfo.phase == PaintPhaseBlockBackground)
291         return;
292
293     // An empty viewport disables rendering.
294     if (borderBoxRect().isEmpty())
295         return;
296
297     // Don't paint if we don't have kids, except if we have filters we should paint those.
298     if (!firstChild() && !selfWillPaint())
299         return;
300
301     // Make a copy of the PaintInfo because applyTransform will modify the damage rect.
302     PaintInfo childPaintInfo(paintInfo);
303     childPaintInfo.context->save();
304
305     // Apply initial viewport clip - not affected by overflow handling
306     childPaintInfo.context->clip(overflowClipRect(borderBoxOriginInContainer, paintInfo.renderRegion));
307
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));
311
312     bool continueRendering = true;
313     if (childPaintInfo.phase == PaintPhaseForeground)
314         continueRendering = SVGRenderSupport::prepareToRenderSVGContent(this, childPaintInfo);
315
316     if (continueRendering)
317         RenderBox::paint(childPaintInfo, LayoutPoint());
318
319     if (childPaintInfo.phase == PaintPhaseForeground)
320         SVGRenderSupport::finishRenderSVGContent(this, childPaintInfo, paintInfo.context);
321
322     childPaintInfo.context->restore();
323
324     if ((paintInfo.phase == PaintPhaseOutline || paintInfo.phase == PaintPhaseSelfOutline) && style()->outlineWidth() && isVisible)
325         paintOutline(paintInfo.context, LayoutRect(borderBoxOriginInContainer, size()));
326 }
327
328 void RenderSVGRoot::willBeDestroyed()
329 {
330     SVGResourcesCache::clientDestroyed(this);
331     RenderBox::willBeDestroyed();
332 }
333
334 void RenderSVGRoot::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
335 {
336     if (diff == StyleDifferenceLayout)
337         setNeedsBoundariesUpdate();
338     RenderBox::styleWillChange(diff, newStyle);
339 }
340
341 void RenderSVGRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
342 {
343     RenderBox::styleDidChange(diff, oldStyle);
344     SVGResourcesCache::clientStyleChanged(this, diff, style());
345 }
346
347 void RenderSVGRoot::updateFromElement()
348 {
349     RenderBox::updateFromElement();
350     SVGResourcesCache::clientUpdatedFromElement(this, style());
351 }
352
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
356 {
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);
363 }
364
365 LayoutSize RenderSVGRoot::parentOriginToBorderBox() const
366 {
367     return locationOffset();
368 }
369
370 LayoutSize RenderSVGRoot::borderOriginToContentBox() const
371 {
372     return LayoutSize(borderLeft() + paddingLeft(), borderTop() + paddingTop());
373 }
374
375 AffineTransform RenderSVGRoot::localToRepaintContainerTransform(const LayoutPoint& parentOriginInContainer) const
376 {
377     return AffineTransform::translation(parentOriginInContainer.x(), parentOriginInContainer.y()) * localToParentTransform();
378 }
379
380 const AffineTransform& RenderSVGRoot::localToParentTransform() const
381 {
382     LayoutSize parentToBorderBoxOffset = parentOriginToBorderBox();
383
384     m_localToParentTransform = AffineTransform::translation(parentToBorderBoxOffset.width(), parentToBorderBoxOffset.height()) * localToBorderBoxTransform();
385
386     return m_localToParentTransform;
387 }
388
389 LayoutRect RenderSVGRoot::clippedOverflowRectForRepaint(RenderBoxModelObject* repaintContainer) const
390 {
391     return SVGRenderSupport::clippedOverflowRectForRepaint(this, repaintContainer);
392 }
393
394 void RenderSVGRoot::computeFloatRectForRepaint(RenderBoxModelObject* repaintContainer, FloatRect& repaintRect, bool fixed) const
395 {
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);
399
400     // Apply initial viewport clip - not affected by overflow settings    
401     repaintRect.intersect(borderBoxRect());
402
403     const SVGRenderStyle* svgStyle = style()->svgStyle();
404     if (const ShadowData* shadow = svgStyle->shadow())
405         shadow->adjustRectForShadow(repaintRect);
406
407     LayoutRect rect = enclosingIntRect(repaintRect);
408     RenderBox::computeRectForRepaint(repaintContainer, rect, fixed);
409     repaintRect = rect;
410 }
411
412 void RenderSVGRoot::mapLocalToContainer(RenderBoxModelObject* repaintContainer, bool fixed, bool useTransforms, TransformState& transformState, bool* wasFixed) const
413 {
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.
416
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);
420 }
421
422 void RenderSVGRoot::updateCachedBoundaries()
423 {
424     m_objectBoundingBox = FloatRect();
425     m_strokeBoundingBox = FloatRect();
426     m_repaintBoundingBox = FloatRect();
427
428     SVGRenderSupport::computeContainerBoundingBoxes(this, m_objectBoundingBox, m_strokeBoundingBox, m_repaintBoundingBox);
429     SVGRenderSupport::intersectRepaintRectWithResources(this, m_repaintBoundingBox);
430     m_repaintBoundingBox.inflate(borderAndPaddingWidth());
431 }
432
433 bool RenderSVGRoot::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const LayoutPoint& pointInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
434 {
435     LayoutPoint pointInParent = pointInContainer - toLayoutSize(accumulatedOffset);
436     LayoutPoint pointInBorderBox = pointInParent - parentOriginToBorderBox();
437
438     // Note: For now, we're ignoring hits to border and padding for <svg>
439     if (!contentBoxRect().contains(pointInBorderBox))
440         return false;
441
442     LayoutPoint localPoint = localToParentTransform().inverse().mapPoint(pointInParent);
443
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);
450             return true;
451         }
452     }
453
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));
461         return true;
462     }
463
464     return false;
465 }
466
467 }
468
469 #endif // ENABLE(SVG)