summaryrefslogtreecommitdiffstats
path: root/third_party/WebKit/Source/core/layout/svg/LayoutSVGRoot.cpp
blob: ed7548a52bcfe24d975cd47f74b3c527be43b265 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
/*
 * Copyright (C) 2004, 2005, 2007 Nikolas Zimmermann <zimmermann@kde.org>
 * Copyright (C) 2004, 2005, 2007, 2008, 2009 Rob Buis <buis@kde.org>
 * Copyright (C) 2007 Eric Seidel <eric@webkit.org>
 * Copyright (C) 2009 Google, Inc.
 * Copyright (C) Research In Motion Limited 2011. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "core/layout/svg/LayoutSVGRoot.h"

#include "core/frame/LocalFrame.h"
#include "core/layout/HitTestResult.h"
#include "core/layout/LayoutAnalyzer.h"
#include "core/layout/LayoutPart.h"
#include "core/layout/LayoutView.h"
#include "core/layout/svg/LayoutSVGText.h"
#include "core/layout/svg/SVGLayoutSupport.h"
#include "core/layout/svg/SVGResourcesCache.h"
#include "core/paint/PaintLayer.h"
#include "core/paint/SVGRootPainter.h"
#include "core/svg/SVGElement.h"
#include "core/svg/SVGSVGElement.h"
#include "core/svg/graphics/SVGImage.h"
#include "platform/LengthFunctions.h"

namespace blink {

LayoutSVGRoot::LayoutSVGRoot(SVGElement* node)
    : LayoutReplaced(node)
    , m_objectBoundingBoxValid(false)
    , m_isLayoutSizeChanged(false)
    , m_needsBoundariesOrTransformUpdate(true)
    , m_hasBoxDecorationBackground(false)
    , m_hasNonIsolatedBlendingDescendants(false)
    , m_hasNonIsolatedBlendingDescendantsDirty(false)
{
    SVGSVGElement* svg = toSVGSVGElement(node);
    ASSERT(svg);

    LayoutSize intrinsicSize(svg->intrinsicWidth(), svg->intrinsicHeight());
    if (!svg->hasIntrinsicWidth())
        intrinsicSize.setWidth(LayoutUnit(defaultWidth));
    if (!svg->hasIntrinsicHeight())
        intrinsicSize.setHeight(LayoutUnit(defaultHeight));
    setIntrinsicSize(intrinsicSize);
}

LayoutSVGRoot::~LayoutSVGRoot()
{
}

void LayoutSVGRoot::computeIntrinsicSizingInfo(IntrinsicSizingInfo& intrinsicSizingInfo) const
{
    // https://www.w3.org/TR/SVG/coords.html#IntrinsicSizing

    SVGSVGElement* svg = toSVGSVGElement(node());
    ASSERT(svg);

    intrinsicSizingInfo.size = FloatSize(svg->intrinsicWidth(), svg->intrinsicHeight());
    intrinsicSizingInfo.hasWidth = svg->hasIntrinsicWidth();
    intrinsicSizingInfo.hasHeight = svg->hasIntrinsicHeight();

    if (!intrinsicSizingInfo.size.isEmpty()) {
        intrinsicSizingInfo.aspectRatio = intrinsicSizingInfo.size;
    } else {
        FloatSize viewBoxSize = svg->viewBox()->currentValue()->value().size();
        if (!viewBoxSize.isEmpty()) {
            // The viewBox can only yield an intrinsic ratio, not an intrinsic size.
            intrinsicSizingInfo.aspectRatio = viewBoxSize;
        }
    }

    if (!isHorizontalWritingMode())
        intrinsicSizingInfo.transpose();
}

bool LayoutSVGRoot::isEmbeddedThroughSVGImage() const
{
    return SVGImage::isInSVGImage(toSVGSVGElement(node()));
}

bool LayoutSVGRoot::isEmbeddedThroughFrameContainingSVGDocument() const
{
    if (!node())
        return false;

    LocalFrame* frame = node()->document().frame();
    if (!frame)
        return false;

    // If our frame has an owner layoutObject, we're embedded through eg. object/embed/iframe,
    // but we only negotiate if we're in an SVG document inside a embedded object (object/embed).
    if (!frame->ownerLayoutObject() || !frame->ownerLayoutObject()->isEmbeddedObject())
        return false;
    return frame->document()->isSVGDocument();
}

LayoutUnit LayoutSVGRoot::computeReplacedLogicalWidth(ShouldComputePreferred shouldComputePreferred) const
{
    // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
    if (!m_containerSize.isEmpty())
        return LayoutUnit(m_containerSize.width());

    if (isEmbeddedThroughFrameContainingSVGDocument())
        return containingBlock()->availableLogicalWidth();

    return LayoutReplaced::computeReplacedLogicalWidth(shouldComputePreferred);
}

LayoutUnit LayoutSVGRoot::computeReplacedLogicalHeight() const
{
    // When we're embedded through SVGImage (border-image/background-image/<html:img>/...) we're forced to resize to a specific size.
    if (!m_containerSize.isEmpty())
        return LayoutUnit(m_containerSize.height());

    if (isEmbeddedThroughFrameContainingSVGDocument())
        return containingBlock()->availableLogicalHeight(IncludeMarginBorderPadding);

    return LayoutReplaced::computeReplacedLogicalHeight();
}

void LayoutSVGRoot::layout()
{
    ASSERT(needsLayout());
    LayoutAnalyzer::Scope analyzer(*this);

    bool needsLayout = selfNeedsLayout();

    LayoutSize oldSize = size();
    updateLogicalWidth();
    updateLogicalHeight();
    buildLocalToBorderBoxTransform();

    SVGLayoutSupport::layoutResourcesIfNeeded(this);

    SVGSVGElement* svg = toSVGSVGElement(node());
    ASSERT(svg);
    m_isLayoutSizeChanged = needsLayout || (svg->hasRelativeLengths() && oldSize != size());
    SVGLayoutSupport::layoutChildren(this, needsLayout || SVGLayoutSupport::filtersForceContainerLayout(this));

    if (m_needsBoundariesOrTransformUpdate) {
        updateCachedBoundaries();
        m_needsBoundariesOrTransformUpdate = false;
    }

    m_overflow.clear();
    addVisualEffectOverflow();

    if (!shouldApplyViewportClip()) {
        FloatRect contentPaintInvalidationRect = paintInvalidationRectInLocalSVGCoordinates();
        contentPaintInvalidationRect = m_localToBorderBoxTransform.mapRect(contentPaintInvalidationRect);
        addVisualOverflow(enclosingLayoutRect(contentPaintInvalidationRect));
    }

    updateLayerTransformAfterLayout();
    m_hasBoxDecorationBackground = isDocumentElement() ? calculateHasBoxDecorations() : hasBoxDecorationBackground();
    invalidateBackgroundObscurationStatus();

    clearNeedsLayout();
}

bool LayoutSVGRoot::shouldApplyViewportClip() const
{
    // the outermost svg is clipped if auto, and svg document roots are always clipped
    // When the svg is stand-alone (isDocumentElement() == true) the viewport clipping should always
    // be applied, noting that the window scrollbars should be hidden if overflow=hidden.
    return style()->overflowX() == OverflowHidden
        || style()->overflowX() == OverflowAuto
        || style()->overflowX() == OverflowScroll
        || this->isDocumentElement();
}

void LayoutSVGRoot::paintReplaced(const PaintInfo& paintInfo, const LayoutPoint& paintOffset) const
{
    SVGRootPainter(*this).paint(paintInfo, paintOffset);
}

void LayoutSVGRoot::willBeDestroyed()
{
    SVGResourcesCache::clientDestroyed(this);
    LayoutReplaced::willBeDestroyed();
}

void LayoutSVGRoot::styleDidChange(StyleDifference diff, const ComputedStyle* oldStyle)
{
    if (diff.needsFullLayout())
        setNeedsBoundariesUpdate();
    if (diff.needsPaintInvalidation()) {
        // Box decorations may have appeared/disappeared - recompute status.
        m_hasBoxDecorationBackground = calculateHasBoxDecorations();
    }

    LayoutReplaced::styleDidChange(diff, oldStyle);
    SVGResourcesCache::clientStyleChanged(this, diff, styleRef());
}

bool LayoutSVGRoot::isChildAllowed(LayoutObject* child, const ComputedStyle&) const
{
    return child->isSVG() && !(child->isSVGInline() || child->isSVGInlineText() || child->isSVGGradientStop());
}

void LayoutSVGRoot::addChild(LayoutObject* child, LayoutObject* beforeChild)
{
    LayoutReplaced::addChild(child, beforeChild);
    SVGResourcesCache::clientWasAddedToTree(child, child->styleRef());

    bool shouldIsolateDescendants = (child->isBlendingAllowed() && child->style()->hasBlendMode()) || child->hasNonIsolatedBlendingDescendants();
    if (shouldIsolateDescendants)
        descendantIsolationRequirementsChanged(DescendantIsolationRequired);
}

void LayoutSVGRoot::removeChild(LayoutObject* child)
{
    SVGResourcesCache::clientWillBeRemovedFromTree(child);
    LayoutReplaced::removeChild(child);

    bool hadNonIsolatedDescendants = (child->isBlendingAllowed() && child->style()->hasBlendMode()) || child->hasNonIsolatedBlendingDescendants();
    if (hadNonIsolatedDescendants)
        descendantIsolationRequirementsChanged(DescendantIsolationNeedsUpdate);
}

bool LayoutSVGRoot::hasNonIsolatedBlendingDescendants() const
{
    if (m_hasNonIsolatedBlendingDescendantsDirty) {
        m_hasNonIsolatedBlendingDescendants = SVGLayoutSupport::computeHasNonIsolatedBlendingDescendants(this);
        m_hasNonIsolatedBlendingDescendantsDirty = false;
    }
    return m_hasNonIsolatedBlendingDescendants;
}

void LayoutSVGRoot::descendantIsolationRequirementsChanged(DescendantIsolationState state)
{
    switch (state) {
    case DescendantIsolationRequired:
        m_hasNonIsolatedBlendingDescendants = true;
        m_hasNonIsolatedBlendingDescendantsDirty = false;
        break;
    case DescendantIsolationNeedsUpdate:
        m_hasNonIsolatedBlendingDescendantsDirty = true;
        break;
    }
}

void LayoutSVGRoot::insertedIntoTree()
{
    LayoutReplaced::insertedIntoTree();
    SVGResourcesCache::clientWasAddedToTree(this, styleRef());
}

void LayoutSVGRoot::willBeRemovedFromTree()
{
    SVGResourcesCache::clientWillBeRemovedFromTree(this);
    LayoutReplaced::willBeRemovedFromTree();
}

PositionWithAffinity LayoutSVGRoot::positionForPoint(const LayoutPoint& point)
{
    FloatPoint absolutePoint = FloatPoint(point);
    absolutePoint = m_localToBorderBoxTransform.inverse().mapPoint(absolutePoint);
    LayoutObject* closestDescendant = SVGLayoutSupport::findClosestLayoutSVGText(this, absolutePoint);

    if (!closestDescendant)
        return LayoutReplaced::positionForPoint(point);

    LayoutObject* layoutObject = closestDescendant;
    AffineTransform transform = layoutObject->localToSVGParentTransform();
    transform.translate(toLayoutSVGText(layoutObject)->location().x(), toLayoutSVGText(layoutObject)->location().y());
    while (layoutObject) {
        layoutObject = layoutObject->parent();
        if (layoutObject->isSVGRoot())
            break;
        transform = layoutObject->localToSVGParentTransform() * transform;
    }

    absolutePoint = transform.inverse().mapPoint(absolutePoint);

    return closestDescendant->positionForPoint(LayoutPoint(absolutePoint));
}

// LayoutBox methods will expect coordinates w/o any transforms in coordinates
// relative to our borderBox origin.  This method gives us exactly that.
void LayoutSVGRoot::buildLocalToBorderBoxTransform()
{
    SVGSVGElement* svg = toSVGSVGElement(node());
    ASSERT(svg);
    float scale = style()->effectiveZoom();
    FloatPoint translate = svg->currentTranslate();
    LayoutSize borderAndPadding(borderLeft() + paddingLeft(), borderTop() + paddingTop());
    m_localToBorderBoxTransform = svg->viewBoxToViewTransform(contentWidth() / scale, contentHeight() / scale);

    AffineTransform viewToBorderBoxTransform(scale, 0, 0, scale, borderAndPadding.width() + translate.x(), borderAndPadding.height() + translate.y());
    m_localToBorderBoxTransform.preMultiply(viewToBorderBoxTransform);
}

const AffineTransform& LayoutSVGRoot::localToSVGParentTransform() const
{
    // Slightly optimized version of m_localToParentTransform = AffineTransform::translation(x(), y()) * m_localToBorderBoxTransform;
    m_localToParentTransform = m_localToBorderBoxTransform;
    if (location().x())
        m_localToParentTransform.setE(m_localToParentTransform.e() + roundToInt(location().x()));
    if (location().y())
        m_localToParentTransform.setF(m_localToParentTransform.f() + roundToInt(location().y()));
    return m_localToParentTransform;
}

LayoutRect LayoutSVGRoot::localOverflowRectForPaintInvalidation() const
{
    // This is an open-coded aggregate of SVGLayoutSupport::localOverflowRectForPaintInvalidation,
    // and LayoutReplaced::localOverflowRectForPaintInvalidation.
    // The reason for this is to optimize/minimize the paint invalidation rect when the box is not "decorated"
    // (does not have background/border/etc.)
    // TODO(wangxianzhu): Verify if the optimization is still needed.

    // Return early for any cases where we don't actually paint.
    if (style()->visibility() != VISIBLE && !enclosingLayer()->hasVisibleContent())
        return LayoutRect();

    // Compute the paint invalidation rect of the content of the SVG in the border-box coordinate space.
    FloatRect contentPaintInvalidationRect = paintInvalidationRectInLocalSVGCoordinates();
    contentPaintInvalidationRect = m_localToBorderBoxTransform.mapRect(contentPaintInvalidationRect);

    // Apply initial viewport clip, overflow:visible content is added to visualOverflow
    // but the most common case is that overflow is hidden, so always intersect.
    contentPaintInvalidationRect.intersect(pixelSnappedBorderBoxRect());

    LayoutRect paintInvalidationRect = enclosingLayoutRect(contentPaintInvalidationRect);
    // If the box is decorated or is overflowing, extend it to include the border-box and overflow.
    if (m_hasBoxDecorationBackground || hasOverflowModel()) {
        // The selectionRect can project outside of the overflowRect, so take their union
        // for paint invalidation to avoid selection painting glitches.
        LayoutRect decoratedPaintInvalidationRect = unionRect(localSelectionRect(), visualOverflowRect());
        paintInvalidationRect.unite(decoratedPaintInvalidationRect);
    }

    return LayoutRect(enclosingIntRect(paintInvalidationRect));
}

bool LayoutSVGRoot::mapToVisibleRectInAncestorSpace(const LayoutBoxModelObject* ancestor, LayoutRect& rect, VisibleRectFlags visibleRectFlags) const
{
    // Note that we don't apply the border-box transform here - it's assumed
    // that whoever called us has done that already.

    // Apply initial viewport clip
    // TODO(crbug.com/597813): We should not apply clip on LayoutSVGRoot's own rect. This clip should
    // be applied in children's mapToVisibleRectInAncestorSpace().
    if (shouldApplyViewportClip()) {
        if (visibleRectFlags & EdgeInclusive) {
            if (!rect.inclusiveIntersect(LayoutRect(pixelSnappedBorderBoxRect())))
                return false;
        } else {
            rect.intersect(LayoutRect(pixelSnappedBorderBoxRect()));
        }
    }

    return LayoutReplaced::mapToVisibleRectInAncestorSpace(ancestor, rect, visibleRectFlags);
}

// This method expects local CSS box coordinates.
// Callers with local SVG viewport coordinates should first apply the localToBorderBoxTransform
// to convert from SVG viewport coordinates to local CSS box coordinates.
void LayoutSVGRoot::mapLocalToAncestor(const LayoutBoxModelObject* ancestor, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
{
    ASSERT(!(mode & IsFixed)); // We should have no fixed content in the SVG layout tree.

    LayoutReplaced::mapLocalToAncestor(ancestor, transformState, mode | ApplyContainerFlip, wasFixed);
}

const LayoutObject* LayoutSVGRoot::pushMappingToContainer(const LayoutBoxModelObject* ancestorToStopAt, LayoutGeometryMap& geometryMap) const
{
    return LayoutReplaced::pushMappingToContainer(ancestorToStopAt, geometryMap);
}

void LayoutSVGRoot::updateCachedBoundaries()
{
    SVGLayoutSupport::computeContainerBoundingBoxes(this, m_objectBoundingBox, m_objectBoundingBoxValid, m_strokeBoundingBox, m_paintInvalidationBoundingBox);
    SVGLayoutSupport::intersectPaintInvalidationRectWithResources(this, m_paintInvalidationBoundingBox);
}

bool LayoutSVGRoot::nodeAtPoint(HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction hitTestAction)
{
    LayoutPoint pointInParent = locationInContainer.point() - toLayoutSize(accumulatedOffset);
    LayoutPoint pointInBorderBox = pointInParent - toLayoutSize(location());

    // Only test SVG content if the point is in our content box, or in case we
    // don't clip to the viewport, the visual overflow rect.
    // FIXME: This should be an intersection when rect-based hit tests are supported by nodeAtFloatPoint.
    if (contentBoxRect().contains(pointInBorderBox) || (!shouldApplyViewportClip() && visualOverflowRect().contains(pointInBorderBox))) {
        const AffineTransform& localToParentTransform = this->localToSVGParentTransform();
        if (localToParentTransform.isInvertible()) {
            FloatPoint localPoint = localToParentTransform.inverse().mapPoint(FloatPoint(pointInParent));

            for (LayoutObject* child = lastChild(); child; child = child->previousSibling()) {
                // FIXME: nodeAtFloatPoint() doesn't handle rect-based hit tests yet.
                if (child->nodeAtFloatPoint(result, localPoint, hitTestAction)) {
                    updateHitTestResult(result, pointInBorderBox);
                    if (result.addNodeToListBasedTestResult(child->node(), locationInContainer) == StopHitTesting)
                        return true;
                }
            }
        }
    }

    // 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.
    if ((hitTestAction == HitTestBlockBackground || hitTestAction == HitTestChildBlockBackground) && visibleToHitTestRequest(result.hitTestRequest())) {
        // Only return true here, if the last hit testing phase 'BlockBackground' (or 'ChildBlockBackground' - depending on context) is executed.
        // If we'd return true in the 'Foreground' phase, hit testing would stop immediately. For SVG only trees this doesn't matter.
        // Though when we have a <foreignObject> subtree we need 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 to detect these hits anymore.
        LayoutRect boundsRect(accumulatedOffset + location(), size());
        if (locationInContainer.intersects(boundsRect)) {
            updateHitTestResult(result, pointInBorderBox);
            if (result.addNodeToListBasedTestResult(node(), locationInContainer, boundsRect) == StopHitTesting)
                return true;
        }
    }

    return false;
}

} // namespace blink