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.
28 #include "SVGUseElement.h"
30 #include "Attribute.h"
31 #include "CachedResourceLoader.h"
32 #include "CachedResourceRequest.h"
33 #include "CachedSVGDocument.h"
35 #include "ElementTraversal.h"
37 #include "EventListener.h"
38 #include "HTMLNames.h"
39 #include "NodeRenderStyle.h"
40 #include "RegisteredEventListener.h"
41 #include "RenderSVGResource.h"
42 #include "RenderSVGTransformableContainer.h"
43 #include "ShadowRoot.h"
44 #include "SVGElementInstance.h"
45 #include "SVGElementRareData.h"
46 #include "SVGElementInstanceList.h"
47 #include "SVGGElement.h"
48 #include "SVGLengthContext.h"
50 #include "SVGSMILElement.h"
51 #include "SVGSVGElement.h"
52 #include "SVGSymbolElement.h"
53 #include "StyleResolver.h"
54 #include "XLinkNames.h"
55 #include "XMLDocumentParser.h"
56 #include "XMLSerializer.h"
58 // Dump SVGElementInstance object tree - useful to debug instanceRoot problems
59 // #define DUMP_INSTANCE_TREE
61 // Dump the deep-expanded shadow tree (where the renderers are built from)
62 // #define DUMP_SHADOW_TREE
66 // Animated property definitions
67 DEFINE_ANIMATED_LENGTH(SVGUseElement, SVGNames::xAttr, X, x)
68 DEFINE_ANIMATED_LENGTH(SVGUseElement, SVGNames::yAttr, Y, y)
69 DEFINE_ANIMATED_LENGTH(SVGUseElement, SVGNames::widthAttr, Width, width)
70 DEFINE_ANIMATED_LENGTH(SVGUseElement, SVGNames::heightAttr, Height, height)
71 DEFINE_ANIMATED_STRING(SVGUseElement, XLinkNames::hrefAttr, Href, href)
72 DEFINE_ANIMATED_BOOLEAN(SVGUseElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
74 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGUseElement)
75 REGISTER_LOCAL_ANIMATED_PROPERTY(x)
76 REGISTER_LOCAL_ANIMATED_PROPERTY(y)
77 REGISTER_LOCAL_ANIMATED_PROPERTY(width)
78 REGISTER_LOCAL_ANIMATED_PROPERTY(height)
79 REGISTER_LOCAL_ANIMATED_PROPERTY(href)
80 REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
81 REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
82 END_REGISTER_ANIMATED_PROPERTIES
84 inline SVGUseElement::SVGUseElement(const QualifiedName& tagName, Document& document, bool wasInsertedByParser)
85 : SVGGraphicsElement(tagName, document)
86 , m_x(LengthModeWidth)
87 , m_y(LengthModeHeight)
88 , m_width(LengthModeWidth)
89 , m_height(LengthModeHeight)
90 , m_wasInsertedByParser(wasInsertedByParser)
91 , m_haveFiredLoadEvent(false)
92 , m_needsShadowTreeRecreation(false)
93 , m_svgLoadEventTimer(this, &SVGElement::svgLoadEventTimerFired)
95 ASSERT(hasCustomStyleResolveCallbacks());
96 ASSERT(hasTagName(SVGNames::useTag));
97 registerAnimatedPropertiesForSVGUseElement();
100 PassRefPtr<SVGUseElement> SVGUseElement::create(const QualifiedName& tagName, Document& document, bool wasInsertedByParser)
102 // Always build a #shadow-root for SVGUseElement.
103 RefPtr<SVGUseElement> use = adoptRef(new SVGUseElement(tagName, document, wasInsertedByParser));
104 use->ensureUserAgentShadowRoot();
105 return use.release();
108 SVGUseElement::~SVGUseElement()
110 setCachedDocument(0);
112 clearResourceReferences();
115 SVGElementInstance* SVGUseElement::instanceRoot()
117 // If there is no element instance tree, force immediate SVGElementInstance tree
118 // creation by asking the document to invoke our recalcStyle function - as we can't
119 // wait for the lazy creation to happen if e.g. JS wants to access the instanceRoot
120 // object right after creating the element on-the-fly
121 if (!m_targetElementInstance)
122 document().updateLayoutIgnorePendingStylesheets();
124 return m_targetElementInstance.get();
127 SVGElementInstance* SVGUseElement::animatedInstanceRoot() const
129 // FIXME: Implement me.
133 bool SVGUseElement::isSupportedAttribute(const QualifiedName& attrName)
135 DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
136 if (supportedAttributes.isEmpty()) {
137 SVGLangSpace::addSupportedAttributes(supportedAttributes);
138 SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
139 SVGURIReference::addSupportedAttributes(supportedAttributes);
140 supportedAttributes.add(SVGNames::xAttr);
141 supportedAttributes.add(SVGNames::yAttr);
142 supportedAttributes.add(SVGNames::widthAttr);
143 supportedAttributes.add(SVGNames::heightAttr);
145 return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
148 void SVGUseElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
150 SVGParsingError parseError = NoError;
152 if (!isSupportedAttribute(name))
153 SVGGraphicsElement::parseAttribute(name, value);
154 else if (name == SVGNames::xAttr)
155 setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
156 else if (name == SVGNames::yAttr)
157 setYBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
158 else if (name == SVGNames::widthAttr)
159 setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths));
160 else if (name == SVGNames::heightAttr)
161 setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths));
162 else if (SVGLangSpace::parseAttribute(name, value)
163 || SVGExternalResourcesRequired::parseAttribute(name, value)
164 || SVGURIReference::parseAttribute(name, value)) {
166 ASSERT_NOT_REACHED();
168 reportAttributeParsingError(parseError, name, value);
171 static inline bool isWellFormedDocument(Document& document)
173 if (document.isSVGDocument() || document.isXHTMLDocument())
174 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 if (!m_wasInsertedByParser)
187 buildPendingResource();
188 SVGExternalResourcesRequired::insertedIntoDocument(this);
189 return InsertionDone;
192 void SVGUseElement::removedFrom(ContainerNode* rootParent)
194 SVGGraphicsElement::removedFrom(rootParent);
195 if (rootParent->inDocument())
196 clearResourceReferences();
199 Document* SVGUseElement::referencedDocument() const
201 if (!isExternalURIReference(href(), document()))
203 return externalDocument();
206 Document* SVGUseElement::externalDocument() const
208 if (m_cachedDocument && m_cachedDocument->isLoaded()) {
209 // Gracefully handle error condition.
210 if (m_cachedDocument->errorOccurred())
212 ASSERT(m_cachedDocument->document());
213 return m_cachedDocument->document();
218 void SVGUseElement::svgAttributeChanged(const QualifiedName& attrName)
220 if (!isSupportedAttribute(attrName)) {
221 SVGGraphicsElement::svgAttributeChanged(attrName);
225 SVGElementInstance::InvalidationGuard invalidationGuard(this);
227 RenderObject* renderer = this->renderer();
228 if (attrName == SVGNames::xAttr
229 || attrName == SVGNames::yAttr
230 || attrName == SVGNames::widthAttr
231 || attrName == SVGNames::heightAttr) {
232 updateRelativeLengthsInformation();
234 RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
238 if (SVGExternalResourcesRequired::handleAttributeChange(this, attrName))
241 if (SVGURIReference::isKnownAttribute(attrName)) {
242 bool isExternalReference = isExternalURIReference(href(), document());
243 if (isExternalReference) {
244 KURL url = document().completeURL(href());
245 if (url.hasFragmentIdentifier()) {
246 CachedResourceRequest request(ResourceRequest(url.string()));
247 request.setInitiator(this);
248 setCachedDocument(document().cachedResourceLoader()->requestSVGDocument(request));
251 setCachedDocument(0);
253 if (!m_wasInsertedByParser)
254 buildPendingResource();
262 if (SVGLangSpace::isKnownAttribute(attrName)
263 || SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
264 invalidateShadowTree();
268 ASSERT_NOT_REACHED();
271 bool SVGUseElement::willRecalcStyle(Style::Change)
273 if (!m_wasInsertedByParser && m_needsShadowTreeRecreation && renderer() && needsStyleRecalc())
274 buildPendingResource();
278 #ifdef DUMP_INSTANCE_TREE
279 static void dumpInstanceTree(unsigned int& depth, String& text, SVGElementInstance* targetInstance)
281 SVGElement* element = targetInstance->correspondingElement();
284 if (element->hasTagName(SVGNames::useTag)) {
285 if (toSVGUseElement(element)->cachedDocumentIsStillLoading())
289 SVGElement* shadowTreeElement = targetInstance->shadowTreeElement();
290 ASSERT(shadowTreeElement);
292 SVGUseElement* directUseElement = targetInstance->directUseElement();
293 String directUseElementName = directUseElement ? directUseElement->nodeName() : "null";
295 String elementId = element->getIdAttribute();
296 String elementNodeName = element->nodeName();
297 String shadowTreeElementNodeName = shadowTreeElement->nodeName();
298 String parentNodeName = element->parentNode() ? element->parentNode()->nodeName() : "null";
299 String firstChildNodeName = element->firstChild() ? element->firstChild()->nodeName() : "null";
301 for (unsigned int i = 0; i < depth; ++i)
304 text += String::format("SVGElementInstance this=%p, (parentNode=%s (%p), firstChild=%s (%p), correspondingElement=%s (%p), directUseElement=%s (%p), shadowTreeElement=%s (%p), id=%s)\n",
305 targetInstance, parentNodeName.latin1().data(), element->parentNode(), firstChildNodeName.latin1().data(), element->firstChild(),
306 elementNodeName.latin1().data(), element, directUseElementName.latin1().data(), directUseElement, shadowTreeElementNodeName.latin1().data(), shadowTreeElement, elementId.latin1().data());
308 for (unsigned int i = 0; i < depth; ++i)
311 const HashSet<SVGElementInstance*>& elementInstances = element->instancesForElement();
312 text += "Corresponding element is associated with " + String::number(elementInstances.size()) + " instance(s):\n";
314 const HashSet<SVGElementInstance*>::const_iterator end = elementInstances.end();
315 for (HashSet<SVGElementInstance*>::const_iterator it = elementInstances.begin(); it != end; ++it) {
316 for (unsigned int i = 0; i < depth; ++i)
319 text += String::format(" -> SVGElementInstance this=%p, (refCount: %i, shadowTreeElement in document? %i)\n",
320 *it, (*it)->refCount(), (*it)->shadowTreeElement()->inDocument());
325 for (SVGElementInstance* instance = targetInstance->firstChild(); instance; instance = instance->nextSibling())
326 dumpInstanceTree(depth, text, instance);
332 static bool isDisallowedElement(Node* node)
334 // Spec: "Any 'svg', 'symbol', 'g', graphics element or other 'use' is potentially a template object that can be re-used
335 // (i.e., "instanced") in the SVG document via a 'use' element."
336 // "Graphics Element" is defined as 'circle', 'ellipse', 'image', 'line', 'path', 'polygon', 'polyline', 'rect', 'text'
337 // Excluded are anything that is used by reference or that only make sense to appear once in a document.
338 // We must also allow the shadow roots of other use elements.
339 if (node->isShadowRoot() || node->isTextNode())
342 if (!node->isSVGElement())
345 Element* element = toElement(node);
347 DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, allowedElementTags, ());
348 if (allowedElementTags.isEmpty()) {
349 allowedElementTags.add(SVGNames::aTag);
350 allowedElementTags.add(SVGNames::circleTag);
351 allowedElementTags.add(SVGNames::descTag);
352 allowedElementTags.add(SVGNames::ellipseTag);
353 allowedElementTags.add(SVGNames::gTag);
354 allowedElementTags.add(SVGNames::imageTag);
355 allowedElementTags.add(SVGNames::lineTag);
356 allowedElementTags.add(SVGNames::metadataTag);
357 allowedElementTags.add(SVGNames::pathTag);
358 allowedElementTags.add(SVGNames::polygonTag);
359 allowedElementTags.add(SVGNames::polylineTag);
360 allowedElementTags.add(SVGNames::rectTag);
361 allowedElementTags.add(SVGNames::svgTag);
362 allowedElementTags.add(SVGNames::switchTag);
363 allowedElementTags.add(SVGNames::symbolTag);
364 allowedElementTags.add(SVGNames::textTag);
365 allowedElementTags.add(SVGNames::textPathTag);
366 allowedElementTags.add(SVGNames::titleTag);
367 allowedElementTags.add(SVGNames::trefTag);
368 allowedElementTags.add(SVGNames::tspanTag);
369 allowedElementTags.add(SVGNames::useTag);
371 return !allowedElementTags.contains<SVGAttributeHashTranslator>(element->tagQName());
374 static bool subtreeContainsDisallowedElement(Node* start)
376 if (isDisallowedElement(start))
379 for (Node* cur = start->firstChild(); cur; cur = cur->nextSibling()) {
380 if (subtreeContainsDisallowedElement(cur))
387 void SVGUseElement::clearResourceReferences()
389 // FIXME: We should try to optimize this, to at least allow partial reclones.
390 if (ShadowRoot* shadowTreeRootElement = shadowRoot())
391 shadowTreeRootElement->removeChildren();
393 if (m_targetElementInstance) {
394 m_targetElementInstance->detach();
395 m_targetElementInstance = 0;
398 m_needsShadowTreeRecreation = false;
400 document().accessSVGExtensions()->removeAllTargetReferencesForElement(this);
403 void SVGUseElement::buildPendingResource()
405 if (!referencedDocument() || isInShadowTree())
407 clearResourceReferences();
412 Element* target = SVGURIReference::targetElementFromIRIString(href(), document(), &id, externalDocument());
413 if (!target || !target->inDocument()) {
414 // If we can't find the target of an external element, just give up.
415 // We can't observe if the target somewhen enters the external document, nor should we do it.
416 if (externalDocument())
421 referencedDocument()->accessSVGExtensions()->addPendingResource(id, this);
422 ASSERT(hasPendingResources());
426 if (target->isSVGElement()) {
427 buildShadowAndInstanceTree(toSVGElement(target));
428 invalidateDependentShadowTrees();
431 ASSERT(!m_needsShadowTreeRecreation);
434 void SVGUseElement::buildShadowAndInstanceTree(SVGElement* target)
436 ASSERT(!m_targetElementInstance);
438 // Do not build the shadow/instance tree for <use> elements living in a shadow tree.
439 // The will be expanded soon anyway - see expandUseElementsInShadowTree().
440 if (isInShadowTree())
443 // Do not allow self-referencing.
444 // 'target' may be null, if it's a non SVG namespaced element.
445 if (!target || target == this)
448 // Why a seperated instance/shadow tree? SVG demands it:
449 // The instance tree is accesable from JavaScript, and has to
450 // expose a 1:1 copy of the referenced tree, whereas internally we need
451 // to alter the tree for correct "use-on-symbol", "use-on-svg" support.
453 // Build instance tree. Create root SVGElementInstance object for the first sub-tree node.
455 // Spec: If the 'use' element references a simple graphics element such as a 'rect', then there is only a
456 // single SVGElementInstance object, and the correspondingElement attribute on this SVGElementInstance object
457 // is the SVGRectElement that corresponds to the referenced 'rect' element.
458 m_targetElementInstance = SVGElementInstance::create(this, this, target);
460 // Eventually enter recursion to build SVGElementInstance objects for the sub-tree children
461 bool foundProblem = false;
462 buildInstanceTree(target, m_targetElementInstance.get(), foundProblem, false);
464 if (instanceTreeIsLoading(m_targetElementInstance.get()))
467 // SVG specification does not say a word about <use> & cycles. My view on this is: just ignore it!
468 // Non-appearing <use> content is easier to debug, then half-appearing content.
470 clearResourceReferences();
474 // Assure instance tree building was successfull
475 ASSERT(m_targetElementInstance);
476 ASSERT(!m_targetElementInstance->shadowTreeElement());
477 ASSERT(m_targetElementInstance->correspondingUseElement() == this);
478 ASSERT(m_targetElementInstance->directUseElement() == this);
479 ASSERT(m_targetElementInstance->correspondingElement() == target);
481 ShadowRoot* shadowTreeRootElement = shadowRoot();
482 ASSERT(shadowTreeRootElement);
484 // Build shadow tree from instance tree
485 // This also handles the special cases: <use> on <symbol>, <use> on <svg>.
486 buildShadowTree(target, m_targetElementInstance.get());
488 // Expand all <use> elements in the shadow tree.
489 // Expand means: replace the actual <use> element by what it references.
490 expandUseElementsInShadowTree(shadowTreeRootElement);
492 // Expand all <symbol> elements in the shadow tree.
493 // Expand means: replace the actual <symbol> element by the <svg> element.
494 expandSymbolElementsInShadowTree(shadowTreeRootElement);
496 // Now that the shadow tree is completly expanded, we can associate
497 // shadow tree elements <-> instances in the instance tree.
498 associateInstancesWithShadowTreeElements(shadowTreeRootElement->firstChild(), m_targetElementInstance.get());
500 // If no shadow tree element is present, this means that the reference root
501 // element was removed, as it is disallowed (ie. <use> on <foreignObject>)
502 // Do NOT leave an inconsistent instance tree around, instead destruct it.
503 if (!m_targetElementInstance->shadowTreeElement()) {
504 clearResourceReferences();
508 ASSERT(m_targetElementInstance->shadowTreeElement()->parentNode() == shadowTreeRootElement);
510 // Transfer event listeners assigned to the referenced element to our shadow tree elements.
511 transferEventListenersToShadowTree(m_targetElementInstance.get());
513 // Update relative length information.
514 updateRelativeLengthsInformation();
516 // Eventually dump instance tree
517 #ifdef DUMP_INSTANCE_TREE
519 unsigned int depth = 0;
521 dumpInstanceTree(depth, text, m_targetElementInstance.get());
522 fprintf(stderr, "\nDumping <use> instance tree:\n%s\n", text.latin1().data());
525 // Eventually dump shadow tree
526 #ifdef DUMP_SHADOW_TREE
527 RefPtr<XMLSerializer> serializer = XMLSerializer::create();
528 String markup = serializer->serializeToString(shadowTreeRootElement, ASSERT_NO_EXCEPTION);
529 fprintf(stderr, "Dumping <use> shadow tree markup:\n%s\n", markup.latin1().data());
533 RenderElement* SVGUseElement::createRenderer(RenderArena& arena, RenderStyle&)
535 return new (arena) RenderSVGTransformableContainer(*this);
538 static bool isDirectReference(const Node* node)
540 return node->hasTagName(SVGNames::pathTag)
541 || node->hasTagName(SVGNames::rectTag)
542 || node->hasTagName(SVGNames::circleTag)
543 || node->hasTagName(SVGNames::ellipseTag)
544 || node->hasTagName(SVGNames::polygonTag)
545 || node->hasTagName(SVGNames::polylineTag)
546 || node->hasTagName(SVGNames::textTag);
549 void SVGUseElement::toClipPath(Path& path)
551 ASSERT(path.isEmpty());
553 Node* n = m_targetElementInstance ? m_targetElementInstance->shadowTreeElement() : 0;
557 if (n->isSVGElement() && toSVGElement(n)->isSVGGraphicsElement()) {
558 if (!isDirectReference(n))
559 // Spec: Indirect references are an error (14.3.5)
560 document().accessSVGExtensions()->reportError("Not allowed to use indirect reference in <clip-path>");
562 toSVGGraphicsElement(n)->toClipPath(path);
563 // FIXME: Avoid manual resolution of x/y here. Its potentially harmful.
564 SVGLengthContext lengthContext(this);
565 path.translate(FloatSize(x().value(lengthContext), y().value(lengthContext)));
566 path.transform(animatedLocalTransform());
571 RenderObject* SVGUseElement::rendererClipChild() const
573 Node* n = m_targetElementInstance ? m_targetElementInstance->shadowTreeElement() : 0;
577 if (n->isSVGElement() && isDirectReference(n))
578 return toSVGElement(n)->renderer();
583 void SVGUseElement::buildInstanceTree(SVGElement* target, SVGElementInstance* targetInstance, bool& foundProblem, bool foundUse)
586 ASSERT(targetInstance);
588 // Spec: If the referenced object is itself a 'use', or if there are 'use' subelements within the referenced
589 // object, the instance tree will contain recursive expansion of the indirect references to form a complete tree.
590 bool targetHasUseTag = target->hasTagName(SVGNames::useTag);
591 SVGElement* newTarget = 0;
592 if (targetHasUseTag) {
593 foundProblem = hasCycleUseReferencing(toSVGUseElement(target), targetInstance, newTarget);
597 // We only need to track first degree <use> dependencies. Indirect references are handled
598 // as the invalidation bubbles up the dependency chain.
600 document().accessSVGExtensions()->addElementReferencingTarget(this, target);
603 } else if (isDisallowedElement(target)) {
608 // A general description from the SVG spec, describing what buildInstanceTree() actually does.
610 // Spec: If the 'use' element references a 'g' which contains two 'rect' elements, then the instance tree
611 // contains three SVGElementInstance objects, a root SVGElementInstance object whose correspondingElement
612 // is the SVGGElement object for the 'g', and then two child SVGElementInstance objects, each of which has
613 // its correspondingElement that is an SVGRectElement object.
615 for (Node* node = target->firstChild(); node; node = node->nextSibling()) {
616 SVGElement* element = 0;
617 if (node->isSVGElement())
618 element = toSVGElement(node);
620 // Skip any non-svg nodes or any disallowed element.
621 if (!element || isDisallowedElement(element))
624 // Create SVGElementInstance object, for both container/non-container nodes.
625 RefPtr<SVGElementInstance> instance = SVGElementInstance::create(this, 0, element);
626 SVGElementInstance* instancePtr = instance.get();
627 targetInstance->appendChild(instance.release());
629 // Enter recursion, appending new instance tree nodes to the "instance" object.
630 buildInstanceTree(element, instancePtr, foundProblem, foundUse);
635 if (!targetHasUseTag || !newTarget)
638 RefPtr<SVGElementInstance> newInstance = SVGElementInstance::create(this, toSVGUseElement(target), newTarget);
639 SVGElementInstance* newInstancePtr = newInstance.get();
640 targetInstance->appendChild(newInstance.release());
641 buildInstanceTree(newTarget, newInstancePtr, foundProblem, foundUse);
644 bool SVGUseElement::hasCycleUseReferencing(SVGUseElement* use, SVGElementInstance* targetInstance, SVGElement*& newTarget)
646 ASSERT(referencedDocument());
647 Element* targetElement = SVGURIReference::targetElementFromIRIString(use->href(), *referencedDocument());
649 if (targetElement && targetElement->isSVGElement())
650 newTarget = toSVGElement(targetElement);
655 // Shortcut for self-references
656 if (newTarget == this)
659 AtomicString targetId = newTarget->getIdAttribute();
660 SVGElementInstance* instance = targetInstance->parentNode();
662 SVGElement* element = instance->correspondingElement();
664 if (element->hasID() && element->getIdAttribute() == targetId && &element->document() == &newTarget->document())
667 instance = instance->parentNode();
672 static inline void removeDisallowedElementsFromSubtree(Element* subtree)
674 ASSERT(!subtree->inDocument());
675 Element* element = ElementTraversal::firstWithin(subtree);
677 if (isDisallowedElement(element)) {
678 Element* next = ElementTraversal::nextSkippingChildren(element, subtree);
679 // The subtree is not in document so this won't generate events that could mutate the tree.
680 element->parentNode()->removeChild(element);
683 element = ElementTraversal::next(element, subtree);
687 void SVGUseElement::buildShadowTree(SVGElement* target, SVGElementInstance* targetInstance)
689 // For instance <use> on <foreignObject> (direct case).
690 if (isDisallowedElement(target))
693 RefPtr<Element> newChild = targetInstance->correspondingElement()->cloneElementWithChildren();
695 // We don't walk the target tree element-by-element, and clone each element,
696 // but instead use cloneElementWithChildren(). This is an optimization for the common
697 // case where <use> doesn't contain disallowed elements (ie. <foreignObject>).
698 // Though if there are disallowed elements in the subtree, we have to remove them.
699 // For instance: <use> on <g> containing <foreignObject> (indirect case).
700 if (subtreeContainsDisallowedElement(newChild.get()))
701 removeDisallowedElementsFromSubtree(newChild.get());
703 shadowRoot()->appendChild(newChild.release());
706 void SVGUseElement::expandUseElementsInShadowTree(Node* element)
708 // Why expand the <use> elements in the shadow tree here, and not just
709 // do this directly in buildShadowTree, if we encounter a <use> element?
711 // Short answer: Because we may miss to expand some elements. Ie. if a <symbol>
712 // contains <use> tags, we'd miss them. So once we're done with settin' up the
713 // actual shadow tree (after the special case modification for svg/symbol) we have
714 // to walk it completely and expand all <use> elements.
715 if (element->hasTagName(SVGNames::useTag)) {
716 SVGUseElement* use = toSVGUseElement(element);
717 ASSERT(!use->cachedDocumentIsStillLoading());
719 ASSERT(referencedDocument());
720 Element* targetElement = SVGURIReference::targetElementFromIRIString(use->href(), *referencedDocument());
721 SVGElement* target = 0;
722 if (targetElement && targetElement->isSVGElement())
723 target = toSVGElement(targetElement);
725 // Don't ASSERT(target) here, it may be "pending", too.
726 // Setup sub-shadow tree root node
727 RefPtr<SVGGElement> cloneParent = SVGGElement::create(SVGNames::gTag, *referencedDocument());
728 use->cloneChildNodes(cloneParent.get());
730 // Spec: In the generated content, the 'use' will be replaced by 'g', where all attributes from the
731 // 'use' element except for x, y, width, height and xlink:href are transferred to the generated 'g' element.
732 transferUseAttributesToReplacedElement(use, cloneParent.get());
734 if (target && !isDisallowedElement(target)) {
735 RefPtr<Element> newChild = target->cloneElementWithChildren();
736 ASSERT(newChild->isSVGElement());
737 cloneParent->appendChild(newChild.release());
740 // We don't walk the target tree element-by-element, and clone each element,
741 // but instead use cloneElementWithChildren(). This is an optimization for the common
742 // case where <use> doesn't contain disallowed elements (ie. <foreignObject>).
743 // Though if there are disallowed elements in the subtree, we have to remove them.
744 // For instance: <use> on <g> containing <foreignObject> (indirect case).
745 if (subtreeContainsDisallowedElement(cloneParent.get()))
746 removeDisallowedElementsFromSubtree(cloneParent.get());
748 RefPtr<Node> replacingElement(cloneParent.get());
750 // Replace <use> with referenced content.
751 ASSERT(use->parentNode());
752 use->parentNode()->replaceChild(cloneParent.release(), use);
754 // Expand the siblings because the *element* is replaced and we will
755 // lose the sibling chain when we are back from recursion.
756 element = replacingElement.get();
757 for (RefPtr<Node> sibling = element->nextSibling(); sibling; sibling = sibling->nextSibling())
758 expandUseElementsInShadowTree(sibling.get());
761 for (RefPtr<Node> child = element->firstChild(); child; child = child->nextSibling())
762 expandUseElementsInShadowTree(child.get());
765 void SVGUseElement::expandSymbolElementsInShadowTree(Node* element)
767 if (element->hasTagName(SVGNames::symbolTag)) {
768 // Spec: The referenced 'symbol' and its contents are deep-cloned into the generated tree,
769 // with the exception that the 'symbol' is replaced by an 'svg'. This generated 'svg' will
770 // always have explicit values for attributes width and height. If attributes width and/or
771 // height are provided on the 'use' element, then these attributes will be transferred to
772 // the generated 'svg'. If attributes width and/or height are not specified, the generated
773 // 'svg' element will use values of 100% for these attributes.
774 RefPtr<SVGSVGElement> svgElement = SVGSVGElement::create(SVGNames::svgTag, *referencedDocument());
776 // Transfer all data (attributes, etc.) from <symbol> to the new <svg> element.
777 svgElement->cloneDataFromElement(*toElement(element));
779 // Only clone symbol children, and add them to the new <svg> element
780 for (Node* child = element->firstChild(); child; child = child->nextSibling()) {
781 RefPtr<Node> newChild = child->cloneNode(true);
782 svgElement->appendChild(newChild.release());
785 // We don't walk the target tree element-by-element, and clone each element,
786 // but instead use cloneNode(deep=true). This is an optimization for the common
787 // case where <use> doesn't contain disallowed elements (ie. <foreignObject>).
788 // Though if there are disallowed elements in the subtree, we have to remove them.
789 // For instance: <use> on <g> containing <foreignObject> (indirect case).
790 if (subtreeContainsDisallowedElement(svgElement.get()))
791 removeDisallowedElementsFromSubtree(svgElement.get());
793 RefPtr<Node> replacingElement(svgElement.get());
795 // Replace <symbol> with <svg>.
796 element->parentNode()->replaceChild(svgElement.release(), element);
798 // Expand the siblings because the *element* is replaced and we will
799 // lose the sibling chain when we are back from recursion.
800 element = replacingElement.get();
801 for (RefPtr<Node> sibling = element->nextSibling(); sibling; sibling = sibling->nextSibling())
802 expandSymbolElementsInShadowTree(sibling.get());
805 for (RefPtr<Node> child = element->firstChild(); child; child = child->nextSibling())
806 expandSymbolElementsInShadowTree(child.get());
809 void SVGUseElement::transferEventListenersToShadowTree(SVGElementInstance* target)
814 SVGElement* originalElement = target->correspondingElement();
815 ASSERT(originalElement);
817 if (SVGElement* shadowTreeElement = target->shadowTreeElement()) {
818 if (EventTargetData* data = originalElement->eventTargetData())
819 data->eventListenerMap.copyEventListenersNotCreatedFromMarkupToTarget(shadowTreeElement);
822 for (SVGElementInstance* instance = target->firstChild(); instance; instance = instance->nextSibling())
823 transferEventListenersToShadowTree(instance);
826 void SVGUseElement::associateInstancesWithShadowTreeElements(Node* target, SVGElementInstance* targetInstance)
828 if (!target || !targetInstance)
831 SVGElement* originalElement = targetInstance->correspondingElement();
833 if (originalElement->hasTagName(SVGNames::useTag)) {
834 // <use> gets replaced by <g>
835 ASSERT(target->nodeName() == SVGNames::gTag);
836 } else if (originalElement->hasTagName(SVGNames::symbolTag)) {
837 // <symbol> gets replaced by <svg>
838 ASSERT(target->nodeName() == SVGNames::svgTag);
840 ASSERT(target->nodeName() == originalElement->nodeName());
842 SVGElement* element = 0;
843 if (target->isSVGElement())
844 element = toSVGElement(target);
846 ASSERT(!targetInstance->shadowTreeElement());
847 targetInstance->setShadowTreeElement(element);
848 element->setCorrespondingElement(originalElement);
850 Node* node = target->firstChild();
851 for (SVGElementInstance* instance = targetInstance->firstChild(); node && instance; instance = instance->nextSibling()) {
852 // Skip any non-svg elements in shadow tree
853 while (node && !node->isSVGElement())
854 node = node->nextSibling();
859 associateInstancesWithShadowTreeElements(node, instance);
860 node = node->nextSibling();
864 SVGElementInstance* SVGUseElement::instanceForShadowTreeElement(Node* element) const
866 if (!m_targetElementInstance) {
867 ASSERT(!inDocument());
871 return instanceForShadowTreeElement(element, m_targetElementInstance.get());
874 SVGElementInstance* SVGUseElement::instanceForShadowTreeElement(Node* element, SVGElementInstance* instance) const
879 // We're dispatching a mutation event during shadow tree construction
880 // this instance hasn't yet been associated to a shadowTree element.
881 if (!instance->shadowTreeElement())
884 if (element == instance->shadowTreeElement())
887 for (SVGElementInstance* current = instance->firstChild(); current; current = current->nextSibling()) {
888 if (SVGElementInstance* search = instanceForShadowTreeElement(element, current))
895 void SVGUseElement::invalidateShadowTree()
897 if (!renderer() || m_needsShadowTreeRecreation)
899 m_needsShadowTreeRecreation = true;
900 setNeedsStyleRecalc();
901 invalidateDependentShadowTrees();
904 void SVGUseElement::invalidateDependentShadowTrees()
906 // Recursively invalidate dependent <use> shadow trees
907 const HashSet<SVGElementInstance*>& instances = instancesForElement();
908 const HashSet<SVGElementInstance*>::const_iterator end = instances.end();
909 for (HashSet<SVGElementInstance*>::const_iterator it = instances.begin(); it != end; ++it) {
910 if (SVGUseElement* element = (*it)->correspondingUseElement()) {
911 ASSERT(element->inDocument());
912 element->invalidateShadowTree();
917 void SVGUseElement::transferUseAttributesToReplacedElement(SVGElement* from, SVGElement* to) const
922 to->cloneDataFromElement(*from);
924 to->removeAttribute(SVGNames::xAttr);
925 to->removeAttribute(SVGNames::yAttr);
926 to->removeAttribute(SVGNames::widthAttr);
927 to->removeAttribute(SVGNames::heightAttr);
928 to->removeAttribute(XLinkNames::hrefAttr);
931 bool SVGUseElement::selfHasRelativeLengths() const
935 || width().isRelative()
936 || height().isRelative())
939 if (!m_targetElementInstance)
942 SVGElement* element = m_targetElementInstance->correspondingElement();
946 return element->hasRelativeLengths();
949 void SVGUseElement::notifyFinished(CachedResource* resource)
954 invalidateShadowTree();
955 if (resource->errorOccurred())
956 dispatchEvent(Event::create(eventNames().errorEvent, false, false));
957 else if (!resource->wasCanceled())
958 SVGExternalResourcesRequired::dispatchLoadEvent(this);
961 bool SVGUseElement::cachedDocumentIsStillLoading()
963 if (m_cachedDocument && m_cachedDocument->isLoading())
968 bool SVGUseElement::instanceTreeIsLoading(SVGElementInstance* targetElementInstance)
970 for (SVGElementInstance* instance = targetElementInstance->firstChild(); instance; instance = instance->nextSibling()) {
971 if (SVGUseElement* use = instance->correspondingUseElement()) {
972 if (use->cachedDocumentIsStillLoading())
975 if (instance->hasChildNodes())
976 instanceTreeIsLoading(instance);
981 void SVGUseElement::finishParsingChildren()
983 SVGGraphicsElement::finishParsingChildren();
984 SVGExternalResourcesRequired::finishParsingChildren();
985 if (m_wasInsertedByParser) {
986 buildPendingResource();
987 m_wasInsertedByParser = false;
991 void SVGUseElement::setCachedDocument(CachedResourceHandle<CachedSVGDocument> cachedDocument)
993 if (m_cachedDocument == cachedDocument)
996 if (m_cachedDocument)
997 m_cachedDocument->removeClient(this);
999 m_cachedDocument = cachedDocument;
1000 if (m_cachedDocument)
1001 m_cachedDocument->addClient(this);
1006 #endif // ENABLE(SVG)