2 * Copyright (C) 2004, 2005, 2006, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
3 * Copyright (C) 2004, 2005, 2006, 2007 Rob Buis <buis@kde.org>
4 * Copyright (C) Research In Motion Limited 2009-2010. All rights reserved.
5 * Copyright (C) 2011 Torch Mobile (Beijing) Co. Ltd. All rights reserved.
6 * Copyright (C) 2012 University of Szeged
7 * Copyright (C) 2012 Renata Hodovan <reni@webkit.org>
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Library General Public
11 * License as published by the Free Software Foundation; either
12 * version 2 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Library General Public License for more details.
19 * You should have received a copy of the GNU Library General Public License
20 * along with this library; see the file COPYING.LIB. If not, write to
21 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
22 * Boston, MA 02110-1301, USA.
26 #include "SVGUseElement.h"
28 #include "CachedResourceLoader.h"
29 #include "CachedResourceRequest.h"
30 #include "CachedSVGDocument.h"
32 #include "ElementIterator.h"
34 #include "EventListener.h"
35 #include "HTMLNames.h"
36 #include "NodeRenderStyle.h"
37 #include "RegisteredEventListener.h"
38 #include "RenderSVGResource.h"
39 #include "RenderSVGTransformableContainer.h"
40 #include "ShadowRoot.h"
41 #include "SVGElementInstance.h"
42 #include "SVGElementRareData.h"
43 #include "SVGElementInstanceList.h"
44 #include "SVGGElement.h"
45 #include "SVGLengthContext.h"
47 #include "SVGSMILElement.h"
48 #include "SVGSVGElement.h"
49 #include "SVGSymbolElement.h"
50 #include "StyleResolver.h"
51 #include "XLinkNames.h"
52 #include "XMLDocumentParser.h"
53 #include "XMLSerializer.h"
54 #include <wtf/NeverDestroyed.h>
56 // Dump SVGElementInstance object tree - useful to debug instanceRoot problems
57 // #define DUMP_INSTANCE_TREE
59 // Dump the deep-expanded shadow tree (where the renderers are built from)
60 // #define DUMP_SHADOW_TREE
64 // Animated property definitions
65 DEFINE_ANIMATED_LENGTH(SVGUseElement, SVGNames::xAttr, X, x)
66 DEFINE_ANIMATED_LENGTH(SVGUseElement, SVGNames::yAttr, Y, y)
67 DEFINE_ANIMATED_LENGTH(SVGUseElement, SVGNames::widthAttr, Width, width)
68 DEFINE_ANIMATED_LENGTH(SVGUseElement, SVGNames::heightAttr, Height, height)
69 DEFINE_ANIMATED_STRING(SVGUseElement, XLinkNames::hrefAttr, Href, href)
70 DEFINE_ANIMATED_BOOLEAN(SVGUseElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
72 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGUseElement)
73 REGISTER_LOCAL_ANIMATED_PROPERTY(x)
74 REGISTER_LOCAL_ANIMATED_PROPERTY(y)
75 REGISTER_LOCAL_ANIMATED_PROPERTY(width)
76 REGISTER_LOCAL_ANIMATED_PROPERTY(height)
77 REGISTER_LOCAL_ANIMATED_PROPERTY(href)
78 REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
79 REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
80 END_REGISTER_ANIMATED_PROPERTIES
82 inline SVGUseElement::SVGUseElement(const QualifiedName& tagName, Document& document, bool wasInsertedByParser)
83 : SVGGraphicsElement(tagName, document)
84 , m_x(LengthModeWidth)
85 , m_y(LengthModeHeight)
86 , m_width(LengthModeWidth)
87 , m_height(LengthModeHeight)
88 , m_wasInsertedByParser(wasInsertedByParser)
89 , m_haveFiredLoadEvent(false)
90 , m_needsShadowTreeRecreation(false)
91 , m_svgLoadEventTimer(this, &SVGElement::svgLoadEventTimerFired)
93 ASSERT(hasCustomStyleResolveCallbacks());
94 ASSERT(hasTagName(SVGNames::useTag));
95 registerAnimatedPropertiesForSVGUseElement();
98 PassRefPtr<SVGUseElement> SVGUseElement::create(const QualifiedName& tagName, Document& document, bool wasInsertedByParser)
100 // Always build a #shadow-root for SVGUseElement.
101 RefPtr<SVGUseElement> use = adoptRef(new SVGUseElement(tagName, document, wasInsertedByParser));
102 use->ensureUserAgentShadowRoot();
103 return use.release();
106 SVGUseElement::~SVGUseElement()
108 setCachedDocument(0);
110 clearResourceReferences();
113 SVGElementInstance* SVGUseElement::instanceRoot()
115 // If there is no element instance tree, force immediate SVGElementInstance tree
116 // creation by asking the document to invoke our recalcStyle function - as we can't
117 // wait for the lazy creation to happen if e.g. JS wants to access the instanceRoot
118 // object right after creating the element on-the-fly
119 if (!m_targetElementInstance)
120 document().updateLayoutIgnorePendingStylesheets();
122 return m_targetElementInstance.get();
125 SVGElementInstance* SVGUseElement::animatedInstanceRoot() const
127 // FIXME: Implement me.
131 bool SVGUseElement::isSupportedAttribute(const QualifiedName& attrName)
133 static NeverDestroyed<HashSet<QualifiedName>> supportedAttributes;
134 if (supportedAttributes.get().isEmpty()) {
135 SVGLangSpace::addSupportedAttributes(supportedAttributes);
136 SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
137 SVGURIReference::addSupportedAttributes(supportedAttributes);
138 supportedAttributes.get().add(SVGNames::xAttr);
139 supportedAttributes.get().add(SVGNames::yAttr);
140 supportedAttributes.get().add(SVGNames::widthAttr);
141 supportedAttributes.get().add(SVGNames::heightAttr);
143 return supportedAttributes.get().contains<SVGAttributeHashTranslator>(attrName);
146 void SVGUseElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
148 SVGParsingError parseError = NoError;
150 if (!isSupportedAttribute(name))
151 SVGGraphicsElement::parseAttribute(name, value);
152 else if (name == SVGNames::xAttr)
153 setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
154 else if (name == SVGNames::yAttr)
155 setYBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
156 else if (name == SVGNames::widthAttr)
157 setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths));
158 else if (name == SVGNames::heightAttr)
159 setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths));
160 else if (SVGLangSpace::parseAttribute(name, value)
161 || SVGExternalResourcesRequired::parseAttribute(name, value)
162 || SVGURIReference::parseAttribute(name, value)) {
164 ASSERT_NOT_REACHED();
166 reportAttributeParsingError(parseError, name, value);
170 static inline bool isWellFormedDocument(Document& document)
172 if (document.isSVGDocument() || document.isXHTMLDocument())
173 return static_cast<XMLDocumentParser*>(document.parser())->wellFormed();
178 Node::InsertionNotificationRequest SVGUseElement::insertedInto(ContainerNode& rootParent)
180 // This functions exists to assure assumptions made in the code regarding SVGElementInstance creation/destruction are satisfied.
181 SVGGraphicsElement::insertedInto(rootParent);
182 if (!rootParent.inDocument())
183 return InsertionDone;
184 ASSERT(!m_targetElementInstance || !isWellFormedDocument(document()));
185 ASSERT(!hasPendingResources() || !isWellFormedDocument(document()));
186 SVGExternalResourcesRequired::insertedIntoDocument(this);
187 if (!m_wasInsertedByParser)
188 return InsertionShouldCallDidNotifySubtreeInsertions;
189 return InsertionDone;
192 void SVGUseElement::didNotifySubtreeInsertions(ContainerNode*)
194 buildPendingResource();
197 void SVGUseElement::removedFrom(ContainerNode& rootParent)
199 SVGGraphicsElement::removedFrom(rootParent);
200 if (rootParent.inDocument())
201 clearResourceReferences();
204 Document* SVGUseElement::referencedDocument() const
206 if (!isExternalURIReference(href(), document()))
208 return externalDocument();
211 Document* SVGUseElement::externalDocument() const
213 if (m_cachedDocument && m_cachedDocument->isLoaded()) {
214 // Gracefully handle error condition.
215 if (m_cachedDocument->errorOccurred())
217 ASSERT(m_cachedDocument->document());
218 return m_cachedDocument->document();
223 void SVGUseElement::svgAttributeChanged(const QualifiedName& attrName)
225 if (!isSupportedAttribute(attrName)) {
226 SVGGraphicsElement::svgAttributeChanged(attrName);
230 SVGElementInstance::InvalidationGuard invalidationGuard(this);
232 auto renderer = this->renderer();
233 if (attrName == SVGNames::xAttr
234 || attrName == SVGNames::yAttr
235 || attrName == SVGNames::widthAttr
236 || attrName == SVGNames::heightAttr) {
237 updateRelativeLengthsInformation();
239 RenderSVGResource::markForLayoutAndParentResourceInvalidation(*renderer);
243 if (SVGExternalResourcesRequired::handleAttributeChange(this, attrName))
246 if (SVGURIReference::isKnownAttribute(attrName)) {
247 bool isExternalReference = isExternalURIReference(href(), document());
248 if (isExternalReference) {
249 URL url = document().completeURL(href());
250 if (url.hasFragmentIdentifier()) {
251 CachedResourceRequest request(ResourceRequest(url.string()));
252 request.setInitiator(this);
253 setCachedDocument(document().cachedResourceLoader()->requestSVGDocument(request));
256 setCachedDocument(0);
258 if (!m_wasInsertedByParser)
259 buildPendingResource();
264 if (SVGLangSpace::isKnownAttribute(attrName)
265 || SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
266 invalidateShadowTree();
270 ASSERT_NOT_REACHED();
273 void SVGUseElement::willAttachRenderers()
275 if (m_needsShadowTreeRecreation)
276 buildPendingResource();
279 #ifdef DUMP_INSTANCE_TREE
280 static void dumpInstanceTree(unsigned int& depth, String& text, SVGElementInstance* targetInstance)
282 SVGElement* element = targetInstance->correspondingElement();
285 if (isSVGUseElement(element)) {
286 if (downcast<SVGUseElement>(*element).cachedDocumentIsStillLoading())
290 SVGElement* shadowTreeElement = targetInstance->shadowTreeElement();
291 ASSERT(shadowTreeElement);
293 SVGUseElement* directUseElement = targetInstance->directUseElement();
294 String directUseElementName = directUseElement ? directUseElement->nodeName() : "null";
296 String elementId = element->getIdAttribute();
297 String elementNodeName = element->nodeName();
298 String shadowTreeElementNodeName = shadowTreeElement->nodeName();
299 String parentNodeName = element->parentNode() ? element->parentNode()->nodeName() : "null";
300 String firstChildNodeName = element->firstChild() ? element->firstChild()->nodeName() : "null";
302 for (unsigned int i = 0; i < depth; ++i)
305 text += String::format("SVGElementInstance this=%p, (parentNode=%s (%p), firstChild=%s (%p), correspondingElement=%s (%p), directUseElement=%s (%p), shadowTreeElement=%s (%p), id=%s)\n",
306 targetInstance, parentNodeName.latin1().data(), element->parentNode(), firstChildNodeName.latin1().data(), element->firstChild(),
307 elementNodeName.latin1().data(), element, directUseElementName.latin1().data(), directUseElement, shadowTreeElementNodeName.latin1().data(), shadowTreeElement, elementId.latin1().data());
309 for (unsigned int i = 0; i < depth; ++i)
312 const HashSet<SVGElementInstance*>& elementInstances = element->instancesForElement();
313 text += "Corresponding element is associated with " + String::number(elementInstances.size()) + " instance(s):\n";
315 const HashSet<SVGElementInstance*>::const_iterator end = elementInstances.end();
316 for (HashSet<SVGElementInstance*>::const_iterator it = elementInstances.begin(); it != end; ++it) {
317 for (unsigned int i = 0; i < depth; ++i)
320 text += String::format(" -> SVGElementInstance this=%p, (refCount: %i, shadowTreeElement in document? %i)\n",
321 *it, (*it)->refCount(), (*it)->shadowTreeElement()->inDocument());
326 for (SVGElementInstance* instance = targetInstance->firstChild(); instance; instance = instance->nextSibling())
327 dumpInstanceTree(depth, text, instance);
333 static bool isDisallowedElement(const Element& element)
335 // Spec: "Any 'svg', 'symbol', 'g', graphics element or other 'use' is potentially a template object that can be re-used
336 // (i.e., "instanced") in the SVG document via a 'use' element."
337 // "Graphics Element" is defined as 'circle', 'ellipse', 'image', 'line', 'path', 'polygon', 'polyline', 'rect', 'text'
338 // Excluded are anything that is used by reference or that only make sense to appear once in a document.
340 if (!element.isSVGElement())
343 static NeverDestroyed<HashSet<QualifiedName>> allowedElementTags;
344 if (allowedElementTags.get().isEmpty()) {
345 allowedElementTags.get().add(SVGNames::aTag);
346 allowedElementTags.get().add(SVGNames::circleTag);
347 allowedElementTags.get().add(SVGNames::descTag);
348 allowedElementTags.get().add(SVGNames::ellipseTag);
349 allowedElementTags.get().add(SVGNames::gTag);
350 allowedElementTags.get().add(SVGNames::imageTag);
351 allowedElementTags.get().add(SVGNames::lineTag);
352 allowedElementTags.get().add(SVGNames::metadataTag);
353 allowedElementTags.get().add(SVGNames::pathTag);
354 allowedElementTags.get().add(SVGNames::polygonTag);
355 allowedElementTags.get().add(SVGNames::polylineTag);
356 allowedElementTags.get().add(SVGNames::rectTag);
357 allowedElementTags.get().add(SVGNames::svgTag);
358 allowedElementTags.get().add(SVGNames::switchTag);
359 allowedElementTags.get().add(SVGNames::symbolTag);
360 allowedElementTags.get().add(SVGNames::textTag);
361 allowedElementTags.get().add(SVGNames::textPathTag);
362 allowedElementTags.get().add(SVGNames::titleTag);
363 allowedElementTags.get().add(SVGNames::trefTag);
364 allowedElementTags.get().add(SVGNames::tspanTag);
365 allowedElementTags.get().add(SVGNames::useTag);
367 return !allowedElementTags.get().contains<SVGAttributeHashTranslator>(element.tagQName());
370 static bool subtreeContainsDisallowedElement(SVGElement& start)
372 for (auto& element : descendantsOfType<Element>(start)) {
373 if (isDisallowedElement(element))
380 void SVGUseElement::clearResourceReferences()
382 // FIXME: We should try to optimize this, to at least allow partial reclones.
383 if (ShadowRoot* shadowTreeRootElement = shadowRoot())
384 shadowTreeRootElement->removeChildren();
386 if (m_targetElementInstance) {
387 m_targetElementInstance->detach();
388 m_targetElementInstance = 0;
391 m_needsShadowTreeRecreation = false;
393 document().accessSVGExtensions().removeAllTargetReferencesForElement(this);
396 void SVGUseElement::buildPendingResource()
398 if (!referencedDocument() || isInShadowTree())
400 clearResourceReferences();
405 Element* target = SVGURIReference::targetElementFromIRIString(href(), document(), &id, externalDocument());
406 if (!target || !target->inDocument()) {
407 // If we can't find the target of an external element, just give up.
408 // We can't observe if the target somewhen enters the external document, nor should we do it.
409 if (externalDocument())
414 referencedDocument()->accessSVGExtensions().addPendingResource(id, this);
415 ASSERT(hasPendingResources());
419 if (target->isSVGElement()) {
420 buildShadowAndInstanceTree(downcast<SVGElement>(target));
421 invalidateDependentShadowTrees();
424 ASSERT(!m_needsShadowTreeRecreation);
427 void SVGUseElement::buildShadowAndInstanceTree(SVGElement* target)
429 ASSERT(!m_targetElementInstance);
431 // Do not build the shadow/instance tree for <use> elements living in a shadow tree.
432 // The will be expanded soon anyway - see expandUseElementsInShadowTree().
433 if (isInShadowTree())
436 // Do not allow self-referencing.
437 // 'target' may be null, if it's a non SVG namespaced element.
438 if (!target || target == this)
441 // Why a seperated instance/shadow tree? SVG demands it:
442 // The instance tree is accesable from JavaScript, and has to
443 // expose a 1:1 copy of the referenced tree, whereas internally we need
444 // to alter the tree for correct "use-on-symbol", "use-on-svg" support.
446 // Build instance tree. Create root SVGElementInstance object for the first sub-tree node.
448 // Spec: If the 'use' element references a simple graphics element such as a 'rect', then there is only a
449 // single SVGElementInstance object, and the correspondingElement attribute on this SVGElementInstance object
450 // is the SVGRectElement that corresponds to the referenced 'rect' element.
451 m_targetElementInstance = SVGElementInstance::create(this, this, target);
453 // Eventually enter recursion to build SVGElementInstance objects for the sub-tree children
454 bool foundProblem = false;
455 buildInstanceTree(target, m_targetElementInstance.get(), foundProblem, false);
457 if (instanceTreeIsLoading(m_targetElementInstance.get()))
460 // SVG specification does not say a word about <use> & cycles. My view on this is: just ignore it!
461 // Non-appearing <use> content is easier to debug, then half-appearing content.
463 clearResourceReferences();
467 // Assure instance tree building was successfull
468 ASSERT(m_targetElementInstance);
469 ASSERT(!m_targetElementInstance->shadowTreeElement());
470 ASSERT(m_targetElementInstance->correspondingUseElement() == this);
471 ASSERT(m_targetElementInstance->directUseElement() == this);
472 ASSERT(m_targetElementInstance->correspondingElement() == target);
474 ShadowRoot* shadowTreeRootElement = shadowRoot();
475 ASSERT(shadowTreeRootElement);
477 // Build shadow tree from instance tree
478 // This also handles the special cases: <use> on <symbol>, <use> on <svg>.
479 buildShadowTree(target, m_targetElementInstance.get());
481 // Expand all <use> elements in the shadow tree.
482 // Expand means: replace the actual <use> element by what it references.
483 expandUseElementsInShadowTree(shadowTreeRootElement);
485 // Expand all <symbol> elements in the shadow tree.
486 // Expand means: replace the actual <symbol> element by the <svg> element.
487 expandSymbolElementsInShadowTree(shadowTreeRootElement);
489 // Now that the shadow tree is completly expanded, we can associate
490 // shadow tree elements <-> instances in the instance tree.
491 associateInstancesWithShadowTreeElements(shadowTreeRootElement->firstChild(), m_targetElementInstance.get());
493 // If no shadow tree element is present, this means that the reference root
494 // element was removed, as it is disallowed (ie. <use> on <foreignObject>)
495 // Do NOT leave an inconsistent instance tree around, instead destruct it.
496 if (!m_targetElementInstance->shadowTreeElement()) {
497 clearResourceReferences();
501 ASSERT(m_targetElementInstance->shadowTreeElement()->parentNode() == shadowTreeRootElement);
503 // Transfer event listeners assigned to the referenced element to our shadow tree elements.
504 transferEventListenersToShadowTree(m_targetElementInstance.get());
506 // Update relative length information.
507 updateRelativeLengthsInformation();
509 // Eventually dump instance tree
510 #ifdef DUMP_INSTANCE_TREE
512 unsigned int depth = 0;
514 dumpInstanceTree(depth, text, m_targetElementInstance.get());
515 fprintf(stderr, "\nDumping <use> instance tree:\n%s\n", text.latin1().data());
518 // Eventually dump shadow tree
519 #ifdef DUMP_SHADOW_TREE
520 RefPtr<XMLSerializer> serializer = XMLSerializer::create();
521 String markup = serializer->serializeToString(shadowTreeRootElement, ASSERT_NO_EXCEPTION);
522 fprintf(stderr, "Dumping <use> shadow tree markup:\n%s\n", markup.latin1().data());
526 RenderPtr<RenderElement> SVGUseElement::createElementRenderer(PassRef<RenderStyle> style)
528 return createRenderer<RenderSVGTransformableContainer>(*this, WTF::move(style));
531 static bool isDirectReference(const SVGElement& element)
533 return element.hasTagName(SVGNames::pathTag)
534 || element.hasTagName(SVGNames::rectTag)
535 || element.hasTagName(SVGNames::circleTag)
536 || element.hasTagName(SVGNames::ellipseTag)
537 || element.hasTagName(SVGNames::polygonTag)
538 || element.hasTagName(SVGNames::polylineTag)
539 || element.hasTagName(SVGNames::textTag);
542 void SVGUseElement::toClipPath(Path& path)
544 ASSERT(path.isEmpty());
546 Node* node = m_targetElementInstance ? m_targetElementInstance->shadowTreeElement() : nullptr;
550 if (node->isSVGElement() && downcast<SVGElement>(*node).isSVGGraphicsElement()) {
551 if (!isDirectReference(downcast<SVGElement>(*node))) {
552 // Spec: Indirect references are an error (14.3.5)
553 document().accessSVGExtensions().reportError("Not allowed to use indirect reference in <clip-path>");
555 toSVGGraphicsElement(*node).toClipPath(path);
556 // FIXME: Avoid manual resolution of x/y here. Its potentially harmful.
557 SVGLengthContext lengthContext(this);
558 path.translate(FloatSize(x().value(lengthContext), y().value(lengthContext)));
559 path.transform(animatedLocalTransform());
564 RenderElement* SVGUseElement::rendererClipChild() const
566 if (!m_targetElementInstance)
569 auto* element = m_targetElementInstance->shadowTreeElement();
573 if (!isDirectReference(*element))
576 return element->renderer();
579 void SVGUseElement::buildInstanceTree(SVGElement* target, SVGElementInstance* targetInstance, bool& foundProblem, bool foundUse)
582 ASSERT(targetInstance);
584 // Spec: If the referenced object is itself a 'use', or if there are 'use' subelements within the referenced
585 // object, the instance tree will contain recursive expansion of the indirect references to form a complete tree.
586 bool targetHasUseTag = target->hasTagName(SVGNames::useTag);
587 SVGElement* newTarget = nullptr;
588 if (targetHasUseTag) {
589 foundProblem = hasCycleUseReferencing(downcast<SVGUseElement>(target), targetInstance, newTarget);
593 // We only need to track first degree <use> dependencies. Indirect references are handled
594 // as the invalidation bubbles up the dependency chain.
596 document().accessSVGExtensions().addElementReferencingTarget(this, target);
599 } else if (isDisallowedElement(*target)) {
604 // A general description from the SVG spec, describing what buildInstanceTree() actually does.
606 // Spec: If the 'use' element references a 'g' which contains two 'rect' elements, then the instance tree
607 // contains three SVGElementInstance objects, a root SVGElementInstance object whose correspondingElement
608 // is the SVGGElement object for the 'g', and then two child SVGElementInstance objects, each of which has
609 // its correspondingElement that is an SVGRectElement object.
611 for (auto& element : childrenOfType<SVGElement>(*target)) {
612 // Skip any non-svg nodes or any disallowed element.
613 if (isDisallowedElement(element))
616 // Create SVGElementInstance object, for both container/non-container nodes.
617 RefPtr<SVGElementInstance> instance = SVGElementInstance::create(this, 0, &element);
618 SVGElementInstance* instancePtr = instance.get();
619 targetInstance->appendChild(instance.release());
621 // Enter recursion, appending new instance tree nodes to the "instance" object.
622 buildInstanceTree(&element, instancePtr, foundProblem, foundUse);
627 if (!targetHasUseTag || !newTarget)
630 RefPtr<SVGElementInstance> newInstance = SVGElementInstance::create(this, downcast<SVGUseElement>(target), newTarget);
631 SVGElementInstance* newInstancePtr = newInstance.get();
632 targetInstance->appendChild(newInstance.release());
633 buildInstanceTree(newTarget, newInstancePtr, foundProblem, foundUse);
636 bool SVGUseElement::hasCycleUseReferencing(SVGUseElement* use, SVGElementInstance* targetInstance, SVGElement*& newTarget)
638 ASSERT(referencedDocument());
639 Element* targetElement = SVGURIReference::targetElementFromIRIString(use->href(), *referencedDocument());
641 if (targetElement && targetElement->isSVGElement())
642 newTarget = downcast<SVGElement>(targetElement);
647 // Shortcut for self-references
648 if (newTarget == this)
651 AtomicString targetId = newTarget->getIdAttribute();
652 SVGElementInstance* instance = targetInstance->parentNode();
654 SVGElement* element = instance->correspondingElement();
656 if (element->hasID() && element->getIdAttribute() == targetId && &element->document() == &newTarget->document())
659 instance = instance->parentNode();
664 static inline void removeDisallowedElementsFromSubtree(SVGElement& subtree)
666 ASSERT(!subtree.inDocument());
667 Vector<Element*> toRemove;
668 auto it = descendantsOfType<Element>(subtree).begin();
669 auto end = descendantsOfType<Element>(subtree).end();
671 if (isDisallowedElement(*it)) {
672 toRemove.append(&*it);
673 it.traverseNextSkippingChildren();
678 // The subtree is not in document so this won't generate events that could mutate the tree.
679 for (unsigned i = 0; i < toRemove.size(); ++i)
680 toRemove[i]->parentNode()->removeChild(toRemove[i]);
683 void SVGUseElement::buildShadowTree(SVGElement* target, SVGElementInstance* targetInstance)
685 ASSERT(target); // FIXME: Don't be a pointer!
687 // For instance <use> on <foreignObject> (direct case).
688 if (isDisallowedElement(*target))
691 RefPtr<SVGElement> newChild = static_pointer_cast<SVGElement>(targetInstance->correspondingElement()->cloneElementWithChildren());
693 // We don't walk the target tree element-by-element, and clone each element,
694 // but instead use cloneElementWithChildren(). This is an optimization for the common
695 // case where <use> doesn't contain disallowed elements (ie. <foreignObject>).
696 // Though if there are disallowed elements in the subtree, we have to remove them.
697 // For instance: <use> on <g> containing <foreignObject> (indirect case).
698 if (subtreeContainsDisallowedElement(*newChild))
699 removeDisallowedElementsFromSubtree(*newChild);
701 shadowRoot()->appendChild(newChild.release());
704 void SVGUseElement::expandUseElementsInShadowTree(Node* element)
706 // Why expand the <use> elements in the shadow tree here, and not just
707 // do this directly in buildShadowTree, if we encounter a <use> element?
709 // Short answer: Because we may miss to expand some elements. Ie. if a <symbol>
710 // contains <use> tags, we'd miss them. So once we're done with settin' up the
711 // actual shadow tree (after the special case modification for svg/symbol) we have
712 // to walk it completely and expand all <use> elements.
713 if (isSVGUseElement(element)) {
714 SVGUseElement& use = downcast<SVGUseElement>(*element);
715 ASSERT(!use.cachedDocumentIsStillLoading());
717 ASSERT(referencedDocument());
718 Element* targetElement = SVGURIReference::targetElementFromIRIString(use.href(), *referencedDocument());
719 SVGElement* target = nullptr;
720 if (targetElement && targetElement->isSVGElement())
721 target = downcast<SVGElement>(targetElement);
723 // Don't ASSERT(target) here, it may be "pending", too.
724 // Setup sub-shadow tree root node
725 RefPtr<SVGGElement> cloneParent = SVGGElement::create(SVGNames::gTag, *referencedDocument());
726 use.cloneChildNodes(cloneParent.get());
728 // Spec: In the generated content, the 'use' will be replaced by 'g', where all attributes from the
729 // 'use' element except for x, y, width, height and xlink:href are transferred to the generated 'g' element.
730 transferUseAttributesToReplacedElement(&use, cloneParent.get());
732 if (target && !isDisallowedElement(*target)) {
733 RefPtr<Element> newChild = target->cloneElementWithChildren();
734 ASSERT(newChild->isSVGElement());
735 cloneParent->appendChild(newChild.release());
738 // We don't walk the target tree element-by-element, and clone each element,
739 // but instead use cloneElementWithChildren(). This is an optimization for the common
740 // case where <use> doesn't contain disallowed elements (ie. <foreignObject>).
741 // Though if there are disallowed elements in the subtree, we have to remove them.
742 // For instance: <use> on <g> containing <foreignObject> (indirect case).
743 if (subtreeContainsDisallowedElement(*cloneParent))
744 removeDisallowedElementsFromSubtree(*cloneParent);
746 RefPtr<Node> replacingElement(cloneParent.get());
748 // Replace <use> with referenced content.
749 ASSERT(use.parentNode());
750 use.parentNode()->replaceChild(cloneParent.release(), &use);
752 // Expand the siblings because the *element* is replaced and we will
753 // lose the sibling chain when we are back from recursion.
754 element = replacingElement.get();
755 for (RefPtr<Node> sibling = element->nextSibling(); sibling; sibling = sibling->nextSibling())
756 expandUseElementsInShadowTree(sibling.get());
759 for (RefPtr<Node> child = element->firstChild(); child; child = child->nextSibling())
760 expandUseElementsInShadowTree(child.get());
763 void SVGUseElement::expandSymbolElementsInShadowTree(Node* element)
765 if (element->hasTagName(SVGNames::symbolTag)) {
766 // Spec: The referenced 'symbol' and its contents are deep-cloned into the generated tree,
767 // with the exception that the 'symbol' is replaced by an 'svg'. This generated 'svg' will
768 // always have explicit values for attributes width and height. If attributes width and/or
769 // height are provided on the 'use' element, then these attributes will be transferred to
770 // the generated 'svg'. If attributes width and/or height are not specified, the generated
771 // 'svg' element will use values of 100% for these attributes.
772 RefPtr<SVGSVGElement> svgElement = SVGSVGElement::create(SVGNames::svgTag, *referencedDocument());
774 // Transfer all data (attributes, etc.) from <symbol> to the new <svg> element.
775 svgElement->cloneDataFromElement(*toElement(element));
777 // Only clone symbol children, and add them to the new <svg> element
778 for (Node* child = element->firstChild(); child; child = child->nextSibling()) {
779 RefPtr<Node> newChild = child->cloneNode(true);
780 svgElement->appendChild(newChild.release());
783 // We don't walk the target tree element-by-element, and clone each element,
784 // but instead use cloneNode(deep=true). This is an optimization for the common
785 // case where <use> doesn't contain disallowed elements (ie. <foreignObject>).
786 // Though if there are disallowed elements in the subtree, we have to remove them.
787 // For instance: <use> on <g> containing <foreignObject> (indirect case).
788 if (subtreeContainsDisallowedElement(*svgElement))
789 removeDisallowedElementsFromSubtree(*svgElement);
791 RefPtr<Node> replacingElement(svgElement.get());
793 // Replace <symbol> with <svg>.
794 element->parentNode()->replaceChild(svgElement.release(), element);
796 // Expand the siblings because the *element* is replaced and we will
797 // lose the sibling chain when we are back from recursion.
798 element = replacingElement.get();
799 for (RefPtr<Node> sibling = element->nextSibling(); sibling; sibling = sibling->nextSibling())
800 expandSymbolElementsInShadowTree(sibling.get());
803 for (RefPtr<Node> child = element->firstChild(); child; child = child->nextSibling())
804 expandSymbolElementsInShadowTree(child.get());
807 void SVGUseElement::transferEventListenersToShadowTree(SVGElementInstance* target)
812 SVGElement* originalElement = target->correspondingElement();
813 ASSERT(originalElement);
815 if (SVGElement* shadowTreeElement = target->shadowTreeElement()) {
816 if (EventTargetData* data = originalElement->eventTargetData())
817 data->eventListenerMap.copyEventListenersNotCreatedFromMarkupToTarget(shadowTreeElement);
820 for (SVGElementInstance* instance = target->firstChild(); instance; instance = instance->nextSibling())
821 transferEventListenersToShadowTree(instance);
824 void SVGUseElement::associateInstancesWithShadowTreeElements(Node* target, SVGElementInstance* targetInstance)
826 if (!target || !targetInstance)
829 SVGElement* originalElement = targetInstance->correspondingElement();
831 if (originalElement->hasTagName(SVGNames::useTag)) {
832 // <use> gets replaced by <g>
833 ASSERT(target->nodeName() == SVGNames::gTag);
834 } else if (originalElement->hasTagName(SVGNames::symbolTag)) {
835 // <symbol> gets replaced by <svg>
836 ASSERT(target->nodeName() == SVGNames::svgTag);
838 ASSERT(target->nodeName() == originalElement->nodeName());
840 SVGElement* element = nullptr;
841 if (target->isSVGElement())
842 element = downcast<SVGElement>(target);
844 ASSERT(!targetInstance->shadowTreeElement());
845 targetInstance->setShadowTreeElement(element);
846 element->setCorrespondingElement(originalElement);
848 Node* node = target->firstChild();
849 for (SVGElementInstance* instance = targetInstance->firstChild(); node && instance; instance = instance->nextSibling()) {
850 // Skip any non-svg elements in shadow tree
851 while (node && !node->isSVGElement())
852 node = node->nextSibling();
857 associateInstancesWithShadowTreeElements(node, instance);
858 node = node->nextSibling();
862 SVGElementInstance* SVGUseElement::instanceForShadowTreeElement(Node* element) const
864 if (!m_targetElementInstance) {
865 ASSERT(!inDocument());
869 return instanceForShadowTreeElement(element, m_targetElementInstance.get());
872 SVGElementInstance* SVGUseElement::instanceForShadowTreeElement(Node* element, SVGElementInstance* instance) const
877 // We're dispatching a mutation event during shadow tree construction
878 // this instance hasn't yet been associated to a shadowTree element.
879 if (!instance->shadowTreeElement())
882 if (element == instance->shadowTreeElement())
885 for (SVGElementInstance* current = instance->firstChild(); current; current = current->nextSibling()) {
886 if (SVGElementInstance* search = instanceForShadowTreeElement(element, current))
893 void SVGUseElement::invalidateShadowTree()
895 if (m_needsShadowTreeRecreation)
897 m_needsShadowTreeRecreation = true;
898 setNeedsStyleRecalc(ReconstructRenderTree);
899 invalidateDependentShadowTrees();
902 void SVGUseElement::invalidateDependentShadowTrees()
904 // Recursively invalidate dependent <use> shadow trees
905 const HashSet<SVGElementInstance*>& instances = instancesForElement();
906 const HashSet<SVGElementInstance*>::const_iterator end = instances.end();
907 for (HashSet<SVGElementInstance*>::const_iterator it = instances.begin(); it != end; ++it) {
908 if (SVGUseElement* element = (*it)->correspondingUseElement()) {
909 ASSERT(element->inDocument());
910 element->invalidateShadowTree();
915 void SVGUseElement::transferUseAttributesToReplacedElement(SVGElement* from, SVGElement* to) const
920 to->cloneDataFromElement(*from);
922 to->removeAttribute(SVGNames::xAttr);
923 to->removeAttribute(SVGNames::yAttr);
924 to->removeAttribute(SVGNames::widthAttr);
925 to->removeAttribute(SVGNames::heightAttr);
926 to->removeAttribute(XLinkNames::hrefAttr);
929 bool SVGUseElement::selfHasRelativeLengths() const
933 || width().isRelative()
934 || height().isRelative())
937 if (!m_targetElementInstance)
940 SVGElement* element = m_targetElementInstance->correspondingElement();
944 return element->hasRelativeLengths();
947 void SVGUseElement::notifyFinished(CachedResource* resource)
952 invalidateShadowTree();
953 if (resource->errorOccurred())
954 dispatchEvent(Event::create(eventNames().errorEvent, false, false));
955 else if (!resource->wasCanceled())
956 SVGExternalResourcesRequired::dispatchLoadEvent(this);
959 bool SVGUseElement::cachedDocumentIsStillLoading()
961 if (m_cachedDocument && m_cachedDocument->isLoading())
966 bool SVGUseElement::instanceTreeIsLoading(SVGElementInstance* targetElementInstance)
968 for (SVGElementInstance* instance = targetElementInstance->firstChild(); instance; instance = instance->nextSibling()) {
969 if (SVGUseElement* use = instance->correspondingUseElement()) {
970 if (use->cachedDocumentIsStillLoading())
973 if (instance->hasChildNodes())
974 instanceTreeIsLoading(instance);
979 void SVGUseElement::finishParsingChildren()
981 SVGGraphicsElement::finishParsingChildren();
982 SVGExternalResourcesRequired::finishParsingChildren();
983 if (m_wasInsertedByParser) {
984 buildPendingResource();
985 m_wasInsertedByParser = false;
989 void SVGUseElement::setCachedDocument(CachedResourceHandle<CachedSVGDocument> cachedDocument)
991 if (m_cachedDocument == cachedDocument)
994 if (m_cachedDocument)
995 m_cachedDocument->removeClient(this);
997 m_cachedDocument = cachedDocument;
998 if (m_cachedDocument)
999 m_cachedDocument->addClient(this);