summaryrefslogtreecommitdiffstats
path: root/chromium/third_party/WebKit/Source/core/dom/shadow/InsertionPoint.cpp
blob: e3c5d4df9fc6861cb0bade2b05a51e8e67d0b7cd (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
/*
 * Copyright (C) 2012 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "core/dom/shadow/InsertionPoint.h"

#include "HTMLNames.h"
#include "core/dom/ElementTraversal.h"
#include "core/dom/QualifiedName.h"
#include "core/dom/StaticNodeList.h"
#include "core/dom/shadow/ElementShadow.h"
#include "core/html/shadow/HTMLContentElement.h"
#include "core/html/shadow/HTMLShadowElement.h"

namespace WebCore {

using namespace HTMLNames;

InsertionPoint::InsertionPoint(const QualifiedName& tagName, Document& document)
    : HTMLElement(tagName, document, CreateInsertionPoint)
    , m_registeredWithShadowRoot(false)
{
    setHasCustomStyleCallbacks();
}

InsertionPoint::~InsertionPoint()
{
}

void InsertionPoint::setDistribution(ContentDistribution& distribution)
{
    if (shouldUseFallbackElements()) {
        for (Node* child = firstChild(); child; child = child->nextSibling())
            child->lazyReattachIfAttached();
    }

    // Attempt not to reattach nodes that would be distributed to the exact same
    // location by comparing the old and new distributions.

    size_t i = 0;
    size_t j = 0;

    for ( ; i < m_distribution.size() && j < distribution.size(); ++i, ++j) {
        if (m_distribution.size() < distribution.size()) {
            // If the new distribution is larger than the old one, reattach all nodes in
            // the new distribution that were inserted.
            for ( ; j < distribution.size() && m_distribution.at(i) != distribution.at(j); ++j)
                distribution.at(j)->lazyReattachIfAttached();
        } else if (m_distribution.size() > distribution.size()) {
            // If the old distribution is larger than the new one, reattach all nodes in
            // the old distribution that were removed.
            for ( ; i < m_distribution.size() && m_distribution.at(i) != distribution.at(j); ++i)
                m_distribution.at(i)->lazyReattachIfAttached();
        } else if (m_distribution.at(i) != distribution.at(j)) {
            // If both distributions are the same length reattach both old and new.
            m_distribution.at(i)->lazyReattachIfAttached();
            distribution.at(j)->lazyReattachIfAttached();
        }
    }

    // If we hit the end of either list above we need to reattach all remaining nodes.

    for ( ; i < m_distribution.size(); ++i)
        m_distribution.at(i)->lazyReattachIfAttached();

    for ( ; j < distribution.size(); ++j)
        distribution.at(j)->lazyReattachIfAttached();

    m_distribution.swap(distribution);
    m_distribution.shrinkToFit();
}

void InsertionPoint::attach(const AttachContext& context)
{
    // We need to attach the distribution here so that they're inserted in the right order
    // otherwise the n^2 protection inside NodeRenderingContext will cause them to be
    // inserted in the wrong place later. This also lets distributed nodes benefit from
    // the n^2 protection.
    for (size_t i = 0; i < m_distribution.size(); ++i) {
        if (m_distribution.at(i)->needsAttach())
            m_distribution.at(i)->attach(context);
    }

    HTMLElement::attach(context);
}

void InsertionPoint::detach(const AttachContext& context)
{
    for (size_t i = 0; i < m_distribution.size(); ++i)
        m_distribution.at(i)->lazyReattachIfAttached();

    HTMLElement::detach(context);
}

void InsertionPoint::willRecalcStyle(StyleRecalcChange change)
{
    if (change < Inherit)
        return;
    for (size_t i = 0; i < m_distribution.size(); ++i)
        m_distribution.at(i)->setNeedsStyleRecalc(LocalStyleChange);
}

bool InsertionPoint::shouldUseFallbackElements() const
{
    return isActive() && !hasDistribution();
}

bool InsertionPoint::canBeActive() const
{
    if (!isInShadowTree())
        return false;
    bool foundShadowElementInAncestors = false;
    bool thisIsContentHTMLElement = isHTMLContentElement(this);
    for (Node* node = parentNode(); node; node = node->parentNode()) {
        if (node->isInsertionPoint()) {
            // For HTMLContentElement, at most one HTMLShadowElement may appear in its ancestors.
            if (thisIsContentHTMLElement && isHTMLShadowElement(node) && !foundShadowElementInAncestors)
                foundShadowElementInAncestors = true;
            else
                return false;
        }
    }
    return true;
}

bool InsertionPoint::isActive() const
{
    if (!canBeActive())
        return false;
    ShadowRoot* shadowRoot = containingShadowRoot();
    ASSERT(shadowRoot);
    if (!isHTMLShadowElement(this) || shadowRoot->descendantShadowElementCount() <= 1)
        return true;

    // Slow path only when there are more than one shadow elements in a shadow tree. That should be a rare case.
    const Vector<RefPtr<InsertionPoint> >& insertionPoints = shadowRoot->descendantInsertionPoints();
    for (size_t i = 0; i < insertionPoints.size(); ++i) {
        InsertionPoint* point = insertionPoints[i].get();
        if (isHTMLShadowElement(point))
            return point == this;
    }
    return true;
}

bool InsertionPoint::isShadowInsertionPoint() const
{
    return isHTMLShadowElement(this) && isActive();
}

bool InsertionPoint::isContentInsertionPoint() const
{
    return isHTMLContentElement(this) && isActive();
}

PassRefPtr<NodeList> InsertionPoint::getDistributedNodes()
{
    document().updateDistributionForNodeIfNeeded(this);

    Vector<RefPtr<Node> > nodes;
    nodes.reserveInitialCapacity(m_distribution.size());
    for (size_t i = 0; i < m_distribution.size(); ++i)
        nodes.uncheckedAppend(m_distribution.at(i));

    return StaticNodeList::adopt(nodes);
}

bool InsertionPoint::rendererIsNeeded(const RenderStyle& style)
{
    return !isActive() && HTMLElement::rendererIsNeeded(style);
}

void InsertionPoint::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
{
    HTMLElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
    if (ShadowRoot* root = containingShadowRoot()) {
        if (ElementShadow* rootOwner = root->owner())
            rootOwner->setNeedsDistributionRecalc();
    }
}

Node::InsertionNotificationRequest InsertionPoint::insertedInto(ContainerNode* insertionPoint)
{
    HTMLElement::insertedInto(insertionPoint);
    if (ShadowRoot* root = containingShadowRoot()) {
        if (ElementShadow* rootOwner = root->owner()) {
            rootOwner->setNeedsDistributionRecalc();
            if (canBeActive() && !m_registeredWithShadowRoot && insertionPoint->treeScope().rootNode() == root) {
                m_registeredWithShadowRoot = true;
                root->didAddInsertionPoint(this);
                rootOwner->didAffectApplyAuthorStyles();
                if (canAffectSelector())
                    rootOwner->willAffectSelector();
            }
        }
    }

    return InsertionDone;
}

void InsertionPoint::removedFrom(ContainerNode* insertionPoint)
{
    ShadowRoot* root = containingShadowRoot();
    if (!root)
        root = insertionPoint->containingShadowRoot();

    if (root) {
        if (ElementShadow* rootOwner = root->owner())
            rootOwner->setNeedsDistributionRecalc();
    }

    // host can be null when removedFrom() is called from ElementShadow destructor.
    ElementShadow* rootOwner = root ? root->owner() : 0;

    // Since this insertion point is no longer visible from the shadow subtree, it need to clean itself up.
    clearDistribution();

    if (m_registeredWithShadowRoot && insertionPoint->treeScope().rootNode() == root) {
        ASSERT(root);
        m_registeredWithShadowRoot = false;
        root->didRemoveInsertionPoint(this);
        if (rootOwner) {
            rootOwner->didAffectApplyAuthorStyles();
            if (canAffectSelector())
                rootOwner->willAffectSelector();
        }
    }

    HTMLElement::removedFrom(insertionPoint);
}

void InsertionPoint::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
    if (name == reset_style_inheritanceAttr) {
        if (!inDocument() || !isActive())
            return;
        containingShadowRoot()->host()->setNeedsStyleRecalc();
    } else
        HTMLElement::parseAttribute(name, value);
}

bool InsertionPoint::resetStyleInheritance() const
{
    return fastHasAttribute(reset_style_inheritanceAttr);
}

void InsertionPoint::setResetStyleInheritance(bool value)
{
    setBooleanAttribute(reset_style_inheritanceAttr, value);
}

const InsertionPoint* resolveReprojection(const Node* projectedNode)
{
    ASSERT(projectedNode);
    const InsertionPoint* insertionPoint = 0;
    const Node* current = projectedNode;
    ElementShadow* lastElementShadow = 0;
    while (true) {
        ElementShadow* shadow = shadowWhereNodeCanBeDistributed(*current);
        if (!shadow || shadow == lastElementShadow)
            break;
        lastElementShadow = shadow;
        const InsertionPoint* insertedTo = shadow->finalDestinationInsertionPointFor(projectedNode);
        if (!insertedTo)
            break;
        ASSERT(current != insertedTo);
        current = insertedTo;
        insertionPoint = insertedTo;
    }
    return insertionPoint;
}

void collectDestinationInsertionPoints(const Node& node, Vector<InsertionPoint*, 8>& results)
{
    const Node* current = &node;
    ElementShadow* lastElementShadow = 0;
    while (true) {
        ElementShadow* shadow = shadowWhereNodeCanBeDistributed(*current);
        if (!shadow || shadow == lastElementShadow)
            return;
        lastElementShadow = shadow;
        const DestinationInsertionPoints* insertionPoints = shadow->destinationInsertionPointsFor(&node);
        if (!insertionPoints)
            return;
        for (size_t i = 0; i < insertionPoints->size(); ++i)
            results.append(insertionPoints->at(i).get());
        ASSERT(current != insertionPoints->last().get());
        current = insertionPoints->last().get();
    }
}

} // namespace WebCore