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#include "RenderSVGRoot.h"
26
27#include "Frame.h"
28#include "GraphicsContext.h"
29#include "HitTestResult.h"
30#include "LayoutRepainter.h"
31#include "Page.h"
32#include "RenderIterator.h"
33#include "RenderLayer.h"
34#include "RenderLayoutState.h"
35#include "RenderSVGResource.h"
36#include "RenderSVGResourceContainer.h"
37#include "RenderSVGResourceFilter.h"
38#include "RenderTreeBuilder.h"
39#include "RenderView.h"
40#include "SVGImage.h"
41#include "SVGRenderingContext.h"
42#include "SVGResources.h"
43#include "SVGResourcesCache.h"
44#include "SVGSVGElement.h"
45#include "SVGViewSpec.h"
46#include "TransformState.h"
47#include <wtf/IsoMallocInlines.h>
48#include <wtf/StackStats.h>
49
50namespace WebCore {
51
52WTF_MAKE_ISO_ALLOCATED_IMPL(RenderSVGRoot);
53
54RenderSVGRoot::RenderSVGRoot(SVGSVGElement& element, RenderStyle&& style)
55 : RenderReplaced(element, WTFMove(style))
56 , m_objectBoundingBoxValid(false)
57 , m_isLayoutSizeChanged(false)
58 , m_needsBoundariesOrTransformUpdate(true)
59 , m_hasBoxDecorations(false)
60{
61}
62
63RenderSVGRoot::~RenderSVGRoot() = default;
64
65SVGSVGElement& RenderSVGRoot::svgSVGElement() const
66{
67 return downcast<SVGSVGElement>(nodeForNonAnonymous());
68}
69
70void RenderSVGRoot::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio) const
71{
72 // Spec: http://www.w3.org/TR/SVG/coords.html#IntrinsicSizing
73 // SVG needs to specify how to calculate some intrinsic sizing properties to enable inclusion within other languages.
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 intrinsicSize.setWidth(floatValueForLength(svgSVGElement().intrinsicWidth(), 0));
83 intrinsicSize.setHeight(floatValueForLength(svgSVGElement().intrinsicHeight(), 0));
84
85
86 if (!intrinsicSize.isEmpty())
87 intrinsicRatio = intrinsicSize.width() / static_cast<double>(intrinsicSize.height());
88 else {
89 // - If either/both of the ‘width’ and ‘height’ of the rootmost ‘svg’ element are in percentage units (or omitted), the
90 // aspect ratio is calculated from the width and height values of the ‘viewBox’ specified for the current SVG document
91 // fragment. If the ‘viewBox’ is not correctly specified, or set to 'none', the intrinsic aspect ratio cannot be
92 // calculated and is considered unspecified.
93 FloatSize viewBoxSize = svgSVGElement().viewBox().size();
94 if (!viewBoxSize.isEmpty()) {
95 // The viewBox can only yield an intrinsic ratio, not an intrinsic size.
96 intrinsicRatio = viewBoxSize.width() / static_cast<double>(viewBoxSize.height());
97 }
98 }
99}
100
101bool RenderSVGRoot::isEmbeddedThroughSVGImage() const
102{
103 return isInSVGImage(&svgSVGElement());
104}
105
106bool RenderSVGRoot::isEmbeddedThroughFrameContainingSVGDocument() const
107{
108 // If our frame has an owner renderer, we're embedded through eg. object/embed/iframe,
109 // but we only negotiate if we're in an SVG document.
110 if (!frame().ownerRenderer())
111 return false;
112 return frame().document()->isSVGDocument();
113}
114
115LayoutUnit RenderSVGRoot::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
116{
117 // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
118 if (!m_containerSize.isEmpty())
119 return m_containerSize.width();
120
121 if (isEmbeddedThroughFrameContainingSVGDocument())
122 return containingBlock()->availableLogicalWidth();
123
124 // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
125 return RenderReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
126}
127
128LayoutUnit RenderSVGRoot::computeReplacedLogicalHeight(Optional<LayoutUnit> estimatedUsedWidth) const
129{
130 // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
131 if (!m_containerSize.isEmpty())
132 return m_containerSize.height();
133
134 if (isEmbeddedThroughFrameContainingSVGDocument())
135 return containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding);
136
137 // SVG embedded via SVGImage (background-image/border-image/etc) / Inline SVG.
138 return RenderReplaced::computeReplacedLogicalHeight(estimatedUsedWidth);
139}
140
141void RenderSVGRoot::layout()
142{
143 StackStats::LayoutCheckPoint layoutCheckPoint;
144 ASSERT(needsLayout());
145
146 m_resourcesNeedingToInvalidateClients.clear();
147
148 // Arbitrary affine transforms are incompatible with RenderLayoutState.
149 LayoutStateDisabler layoutStateDisabler(view().frameView().layoutContext());
150
151 bool needsLayout = selfNeedsLayout();
152 LayoutRepainter repainter(*this, checkForRepaintDuringLayout() && needsLayout);
153
154 LayoutSize oldSize = size();
155 updateLogicalWidth();
156 updateLogicalHeight();
157 buildLocalToBorderBoxTransform();
158
159 m_isLayoutSizeChanged = needsLayout || (svgSVGElement().hasRelativeLengths() && oldSize != size());
160 SVGRenderSupport::layoutChildren(*this, needsLayout || SVGRenderSupport::filtersForceContainerLayout(*this));
161
162 if (!m_resourcesNeedingToInvalidateClients.isEmpty()) {
163 // Invalidate resource clients, which may mark some nodes for layout.
164 for (auto& resource : m_resourcesNeedingToInvalidateClients) {
165 resource->removeAllClientsFromCache();
166 SVGResourcesCache::clientStyleChanged(*resource, StyleDifference::Layout, resource->style());
167 }
168
169 m_isLayoutSizeChanged = false;
170 SVGRenderSupport::layoutChildren(*this, false);
171 }
172
173 // At this point LayoutRepainter already grabbed the old bounds,
174 // recalculate them now so repaintAfterLayout() uses the new bounds.
175 if (m_needsBoundariesOrTransformUpdate) {
176 updateCachedBoundaries();
177 m_needsBoundariesOrTransformUpdate = false;
178 }
179
180 clearOverflow();
181 if (!shouldApplyViewportClip()) {
182 FloatRect contentRepaintRect = repaintRectInLocalCoordinates();
183 contentRepaintRect = m_localToBorderBoxTransform.mapRect(contentRepaintRect);
184 addVisualOverflow(enclosingLayoutRect(contentRepaintRect));
185 }
186
187 updateLayerTransform();
188 m_hasBoxDecorations = isDocumentElementRenderer() ? hasVisibleBoxDecorationStyle() : hasVisibleBoxDecorations();
189 invalidateBackgroundObscurationStatus();
190
191 repainter.repaintAfterLayout();
192
193 clearNeedsLayout();
194}
195
196bool RenderSVGRoot::shouldApplyViewportClip() const
197{
198 // the outermost svg is clipped if auto, and svg document roots are always clipped
199 // When the svg is stand-alone (isDocumentElement() == true) the viewport clipping should always
200 // be applied, noting that the window scrollbars should be hidden if overflow=hidden.
201 return style().overflowX() == Overflow::Hidden
202 || style().overflowX() == Overflow::Auto
203 || style().overflowX() == Overflow::Scroll
204 || this->isDocumentElementRenderer();
205}
206
207void RenderSVGRoot::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
208{
209 // An empty viewport disables rendering.
210 if (borderBoxRect().isEmpty())
211 return;
212
213 // Don't paint, if the context explicitly disabled it.
214 if (paintInfo.context().paintingDisabled())
215 return;
216
217 // SVG outlines are painted during PaintPhase::Foreground.
218 if (paintInfo.phase == PaintPhase::Outline || paintInfo.phase == PaintPhase::SelfOutline)
219 return;
220
221 // An empty viewBox also disables rendering.
222 // (http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute)
223 if (svgSVGElement().hasEmptyViewBox())
224 return;
225
226 // Don't paint if we don't have kids, except if we have filters we should paint those.
227 if (!firstChild()) {
228 auto* resources = SVGResourcesCache::cachedResourcesForRenderer(*this);
229 if (!resources || !resources->filter()) {
230 if (paintInfo.phase == PaintPhase::Foreground)
231 page().addRelevantUnpaintedObject(this, visualOverflowRect());
232 return;
233 }
234 }
235
236 if (paintInfo.phase == PaintPhase::Foreground)
237 page().addRelevantRepaintedObject(this, visualOverflowRect());
238
239 // Make a copy of the PaintInfo because applyTransform will modify the damage rect.
240 PaintInfo childPaintInfo(paintInfo);
241 childPaintInfo.context().save();
242
243 // Apply initial viewport clip
244 if (shouldApplyViewportClip())
245 childPaintInfo.context().clip(snappedIntRect(overflowClipRect(paintOffset)));
246
247 // Convert from container offsets (html renderers) to a relative transform (svg renderers).
248 // Transform from our paint container's coordinate system to our local coords.
249 IntPoint adjustedPaintOffset = roundedIntPoint(paintOffset);
250 childPaintInfo.applyTransform(AffineTransform::translation(adjustedPaintOffset.x(), adjustedPaintOffset.y()) * localToBorderBoxTransform());
251
252 // SVGRenderingContext must be destroyed before we restore the childPaintInfo.context(), because a filter may have
253 // changed the context and it is only reverted when the SVGRenderingContext destructor finishes applying the filter.
254 {
255 SVGRenderingContext renderingContext;
256 bool continueRendering = true;
257 if (childPaintInfo.phase == PaintPhase::Foreground) {
258 renderingContext.prepareToRenderSVGContent(*this, childPaintInfo);
259 continueRendering = renderingContext.isRenderingPrepared();
260 }
261
262 if (continueRendering) {
263 childPaintInfo.updateSubtreePaintRootForChildren(this);
264 for (auto& child : childrenOfType<RenderElement>(*this))
265 child.paint(childPaintInfo, location());
266 }
267 }
268
269 childPaintInfo.context().restore();
270}
271
272void RenderSVGRoot::willBeDestroyed()
273{
274 RenderBlock::removePercentHeightDescendant(const_cast<RenderSVGRoot&>(*this));
275
276 SVGResourcesCache::clientDestroyed(*this);
277 RenderReplaced::willBeDestroyed();
278}
279
280void RenderSVGRoot::insertedIntoTree()
281{
282 RenderReplaced::insertedIntoTree();
283 SVGResourcesCache::clientWasAddedToTree(*this);
284}
285
286void RenderSVGRoot::willBeRemovedFromTree()
287{
288 SVGResourcesCache::clientWillBeRemovedFromTree(*this);
289 RenderReplaced::willBeRemovedFromTree();
290}
291
292void RenderSVGRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
293{
294 if (diff == StyleDifference::Layout)
295 setNeedsBoundariesUpdate();
296
297 // Box decorations may have appeared/disappeared - recompute status.
298 if (diff == StyleDifference::Repaint)
299 m_hasBoxDecorations = hasVisibleBoxDecorationStyle();
300
301 RenderReplaced::styleDidChange(diff, oldStyle);
302 SVGResourcesCache::clientStyleChanged(*this, diff, style());
303}
304
305// RenderBox methods will expect coordinates w/o any transforms in coordinates
306// relative to our borderBox origin. This method gives us exactly that.
307void RenderSVGRoot::buildLocalToBorderBoxTransform()
308{
309 float scale = style().effectiveZoom();
310 FloatPoint translate = svgSVGElement().currentTranslateValue();
311 LayoutSize borderAndPadding(borderLeft() + paddingLeft(), borderTop() + paddingTop());
312 m_localToBorderBoxTransform = svgSVGElement().viewBoxToViewTransform(contentWidth() / scale, contentHeight() / scale);
313 if (borderAndPadding.isZero() && scale == 1 && translate == FloatPoint::zero())
314 return;
315 m_localToBorderBoxTransform = AffineTransform(scale, 0, 0, scale, borderAndPadding.width() + translate.x(), borderAndPadding.height() + translate.y()) * m_localToBorderBoxTransform;
316}
317
318const AffineTransform& RenderSVGRoot::localToParentTransform() const
319{
320 // Slightly optimized version of m_localToParentTransform = AffineTransform::translation(x(), y()) * m_localToBorderBoxTransform;
321 m_localToParentTransform = m_localToBorderBoxTransform;
322 if (x())
323 m_localToParentTransform.setE(m_localToParentTransform.e() + roundToInt(x()));
324 if (y())
325 m_localToParentTransform.setF(m_localToParentTransform.f() + roundToInt(y()));
326 return m_localToParentTransform;
327}
328
329LayoutRect RenderSVGRoot::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
330{
331 if (style().visibility() != Visibility::Visible && !enclosingLayer()->hasVisibleContent())
332 return LayoutRect();
333
334 FloatRect contentRepaintRect = m_localToBorderBoxTransform.mapRect(repaintRectInLocalCoordinates());
335 contentRepaintRect.intersect(snappedIntRect(borderBoxRect()));
336
337 LayoutRect repaintRect = enclosingLayoutRect(contentRepaintRect);
338 if (m_hasBoxDecorations || hasRenderOverflow())
339 repaintRect.unite(unionRect(localSelectionRect(false), visualOverflowRect()));
340
341 return RenderReplaced::computeRectForRepaint(enclosingIntRect(repaintRect), repaintContainer);
342}
343
344Optional<FloatRect> RenderSVGRoot::computeFloatVisibleRectInContainer(const FloatRect& rect, const RenderLayerModelObject* container, VisibleRectContext context) const
345{
346 // Apply our local transforms (except for x/y translation), then our shadow,
347 // and then call RenderBox's method to handle all the normal CSS Box model bits
348 FloatRect adjustedRect = m_localToBorderBoxTransform.mapRect(rect);
349
350 const SVGRenderStyle& svgStyle = style().svgStyle();
351 if (const ShadowData* shadow = svgStyle.shadow())
352 shadow->adjustRectForShadow(adjustedRect);
353
354 // Apply initial viewport clip
355 if (shouldApplyViewportClip()) {
356 if (context.m_options.contains(VisibleRectContextOption::UseEdgeInclusiveIntersection)) {
357 if (!adjustedRect.edgeInclusiveIntersect(snappedIntRect(borderBoxRect())))
358 return WTF::nullopt;
359 } else
360 adjustedRect.intersect(snappedIntRect(borderBoxRect()));
361 }
362
363 if (m_hasBoxDecorations || hasRenderOverflow()) {
364 // The selectionRect can project outside of the overflowRect, so take their union
365 // for repainting to avoid selection painting glitches.
366 LayoutRect decoratedRepaintRect = unionRect(localSelectionRect(false), visualOverflowRect());
367 adjustedRect.unite(decoratedRepaintRect);
368 }
369
370 if (Optional<LayoutRect> rectInContainer = RenderReplaced::computeVisibleRectInContainer(enclosingIntRect(adjustedRect), container, context))
371 return FloatRect(*rectInContainer);
372 return WTF::nullopt;
373}
374
375// This method expects local CSS box coordinates.
376// Callers with local SVG viewport coordinates should first apply the localToBorderBoxTransform
377// to convert from SVG viewport coordinates to local CSS box coordinates.
378void RenderSVGRoot::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
379{
380 ASSERT(mode & ~IsFixed); // We should have no fixed content in the SVG rendering tree.
381 ASSERT(mode & UseTransforms); // mapping a point through SVG w/o respecting trasnforms is useless.
382
383 RenderReplaced::mapLocalToContainer(repaintContainer, transformState, mode | ApplyContainerFlip, wasFixed);
384}
385
386const RenderObject* RenderSVGRoot::pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap& geometryMap) const
387{
388 return RenderReplaced::pushMappingToContainer(ancestorToStopAt, geometryMap);
389}
390
391void RenderSVGRoot::updateCachedBoundaries()
392{
393 SVGRenderSupport::computeContainerBoundingBoxes(*this, m_objectBoundingBox, m_objectBoundingBoxValid, m_strokeBoundingBox, m_repaintBoundingBoxExcludingShadow);
394 SVGRenderSupport::intersectRepaintRectWithResources(*this, m_repaintBoundingBoxExcludingShadow);
395 m_repaintBoundingBoxExcludingShadow.inflate(horizontalBorderAndPaddingExtent());
396
397 m_repaintBoundingBox = m_repaintBoundingBoxExcludingShadow;
398}
399
400bool RenderSVGRoot::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
401{
402 LayoutPoint pointInParent = locationInContainer.point() - toLayoutSize(accumulatedOffset);
403 LayoutPoint pointInBorderBox = pointInParent - toLayoutSize(location());
404
405 // Test SVG content if the point is in our content box or it is inside the visualOverflowRect and the overflow is visible.
406 // FIXME: This should be an intersection when rect-based hit tests are supported by nodeAtFloatPoint.
407 if (contentBoxRect().contains(pointInBorderBox) || (!shouldApplyViewportClip() && visualOverflowRect().contains(pointInParent))) {
408 FloatPoint localPoint = localToParentTransform().inverse().valueOr(AffineTransform()).mapPoint(FloatPoint(pointInParent));
409
410 for (RenderObject* child = lastChild(); child; child = child->previousSibling()) {
411 // FIXME: nodeAtFloatPoint() doesn't handle rect-based hit tests yet.
412 if (child->nodeAtFloatPoint(request, result, localPoint, hitTestAction)) {
413 updateHitTestResult(result, pointInBorderBox);
414 if (result.addNodeToListBasedTestResult(child->node(), request, locationInContainer) == HitTestProgress::Stop)
415 return true;
416 }
417 }
418 }
419
420 // 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.
421 if ((hitTestAction == HitTestBlockBackground || hitTestAction == HitTestChildBlockBackground) && visibleToHitTesting()) {
422 // Only return true here, if the last hit testing phase 'BlockBackground' is executed. If we'd return true in the 'Foreground' phase,
423 // hit testing would stop immediately. For SVG only trees this doesn't matter. Though when we have a <foreignObject> subtree we need
424 // 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
425 // to detect these hits anymore.
426 LayoutRect boundsRect(accumulatedOffset + location(), size());
427 if (locationInContainer.intersects(boundsRect)) {
428 updateHitTestResult(result, pointInBorderBox);
429 if (result.addNodeToListBasedTestResult(&svgSVGElement(), request, locationInContainer, boundsRect) == HitTestProgress::Stop)
430 return true;
431 }
432 }
433
434 return false;
435}
436
437bool RenderSVGRoot::hasRelativeDimensions() const
438{
439 return svgSVGElement().intrinsicHeight().isPercentOrCalculated() || svgSVGElement().intrinsicWidth().isPercentOrCalculated();
440}
441
442void RenderSVGRoot::addResourceForClientInvalidation(RenderSVGResourceContainer* resource)
443{
444 RenderSVGRoot* svgRoot = SVGRenderSupport::findTreeRootObject(*resource);
445 if (!svgRoot)
446 return;
447 svgRoot->m_resourcesNeedingToInvalidateClients.add(resource);
448}
449
450}
451