diff options
Diffstat (limited to 'Source/WebCore/svg/SVGUseElement.cpp')
-rw-r--r-- | Source/WebCore/svg/SVGUseElement.cpp | 1048 |
1 files changed, 330 insertions, 718 deletions
diff --git a/Source/WebCore/svg/SVGUseElement.cpp b/Source/WebCore/svg/SVGUseElement.cpp index a45910643..e1a8ef787 100644 --- a/Source/WebCore/svg/SVGUseElement.cpp +++ b/Source/WebCore/svg/SVGUseElement.cpp @@ -5,6 +5,7 @@ * Copyright (C) 2011 Torch Mobile (Beijing) Co. Ltd. All rights reserved. * Copyright (C) 2012 University of Szeged * Copyright (C) 2012 Renata Hodovan <reni@webkit.org> + * Copyright (C) 2015 Apple Inc. 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 @@ -23,46 +24,23 @@ */ #include "config.h" - -#if ENABLE(SVG) #include "SVGUseElement.h" #include "CachedResourceLoader.h" -#include "CachedResourceRequest.h" #include "CachedSVGDocument.h" -#include "Document.h" #include "ElementIterator.h" #include "Event.h" -#include "EventListener.h" -#include "HTMLNames.h" -#include "NodeRenderStyle.h" -#include "RegisteredEventListener.h" +#include "EventNames.h" #include "RenderSVGResource.h" #include "RenderSVGTransformableContainer.h" #include "ShadowRoot.h" -#include "SVGElementInstance.h" -#include "SVGElementRareData.h" -#include "SVGElementInstanceList.h" #include "SVGGElement.h" -#include "SVGLengthContext.h" -#include "SVGNames.h" -#include "SVGSMILElement.h" #include "SVGSVGElement.h" #include "SVGSymbolElement.h" -#include "StyleResolver.h" #include "XLinkNames.h" -#include "XMLDocumentParser.h" -#include "XMLSerializer.h" - -// Dump SVGElementInstance object tree - useful to debug instanceRoot problems -// #define DUMP_INSTANCE_TREE - -// Dump the deep-expanded shadow tree (where the renderers are built from) -// #define DUMP_SHADOW_TREE namespace WebCore { -// Animated property definitions DEFINE_ANIMATED_LENGTH(SVGUseElement, SVGNames::xAttr, X, x) DEFINE_ANIMATED_LENGTH(SVGUseElement, SVGNames::yAttr, Y, y) DEFINE_ANIMATED_LENGTH(SVGUseElement, SVGNames::widthAttr, Width, width) @@ -80,158 +58,106 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGUseElement) REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement) END_REGISTER_ANIMATED_PROPERTIES -inline SVGUseElement::SVGUseElement(const QualifiedName& tagName, Document& document, bool wasInsertedByParser) +inline SVGUseElement::SVGUseElement(const QualifiedName& tagName, Document& document) : SVGGraphicsElement(tagName, document) , m_x(LengthModeWidth) , m_y(LengthModeHeight) , m_width(LengthModeWidth) , m_height(LengthModeHeight) - , m_wasInsertedByParser(wasInsertedByParser) - , m_haveFiredLoadEvent(false) - , m_needsShadowTreeRecreation(false) - , m_svgLoadEventTimer(this, &SVGElement::svgLoadEventTimerFired) + , m_svgLoadEventTimer(*this, &SVGElement::svgLoadEventTimerFired) { ASSERT(hasCustomStyleResolveCallbacks()); ASSERT(hasTagName(SVGNames::useTag)); registerAnimatedPropertiesForSVGUseElement(); } -PassRefPtr<SVGUseElement> SVGUseElement::create(const QualifiedName& tagName, Document& document, bool wasInsertedByParser) +Ref<SVGUseElement> SVGUseElement::create(const QualifiedName& tagName, Document& document) { - // Always build a #shadow-root for SVGUseElement. - RefPtr<SVGUseElement> use = adoptRef(new SVGUseElement(tagName, document, wasInsertedByParser)); - use->ensureUserAgentShadowRoot(); - return use.release(); + return adoptRef(*new SVGUseElement(tagName, document)); } SVGUseElement::~SVGUseElement() { - setCachedDocument(0); - - clearResourceReferences(); -} - -SVGElementInstance* SVGUseElement::instanceRoot() -{ - // If there is no element instance tree, force immediate SVGElementInstance tree - // creation by asking the document to invoke our recalcStyle function - as we can't - // wait for the lazy creation to happen if e.g. JS wants to access the instanceRoot - // object right after creating the element on-the-fly - if (!m_targetElementInstance) - document().updateLayoutIgnorePendingStylesheets(); - - return m_targetElementInstance.get(); -} - -SVGElementInstance* SVGUseElement::animatedInstanceRoot() const -{ - // FIXME: Implement me. - return 0; -} - -bool SVGUseElement::isSupportedAttribute(const QualifiedName& attrName) -{ - DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ()); - if (supportedAttributes.isEmpty()) { - SVGLangSpace::addSupportedAttributes(supportedAttributes); - SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes); - SVGURIReference::addSupportedAttributes(supportedAttributes); - supportedAttributes.add(SVGNames::xAttr); - supportedAttributes.add(SVGNames::yAttr); - supportedAttributes.add(SVGNames::widthAttr); - supportedAttributes.add(SVGNames::heightAttr); - } - return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName); + if (m_externalDocument) + m_externalDocument->removeClient(*this); } void SVGUseElement::parseAttribute(const QualifiedName& name, const AtomicString& value) { SVGParsingError parseError = NoError; - if (!isSupportedAttribute(name)) - SVGGraphicsElement::parseAttribute(name, value); - else if (name == SVGNames::xAttr) - setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError)); + if (name == SVGNames::xAttr) + setXBaseValue(SVGLengthValue::construct(LengthModeWidth, value, parseError)); else if (name == SVGNames::yAttr) - setYBaseValue(SVGLength::construct(LengthModeHeight, value, parseError)); + setYBaseValue(SVGLengthValue::construct(LengthModeHeight, value, parseError)); else if (name == SVGNames::widthAttr) - setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths)); + setWidthBaseValue(SVGLengthValue::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths)); else if (name == SVGNames::heightAttr) - setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths)); - else if (SVGLangSpace::parseAttribute(name, value) - || SVGExternalResourcesRequired::parseAttribute(name, value) - || SVGURIReference::parseAttribute(name, value)) { - } else - ASSERT_NOT_REACHED(); + setHeightBaseValue(SVGLengthValue::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths)); reportAttributeParsingError(parseError, name, value); -} -#if !ASSERT_DISABLED -static inline bool isWellFormedDocument(Document& document) -{ - if (document.isSVGDocument() || document.isXHTMLDocument()) - return static_cast<XMLDocumentParser*>(document.parser())->wellFormed(); - return true; + SVGExternalResourcesRequired::parseAttribute(name, value); + SVGGraphicsElement::parseAttribute(name, value); + SVGURIReference::parseAttribute(name, value); } -#endif Node::InsertionNotificationRequest SVGUseElement::insertedInto(ContainerNode& rootParent) { - // This functions exists to assure assumptions made in the code regarding SVGElementInstance creation/destruction are satisfied. SVGGraphicsElement::insertedInto(rootParent); - if (!rootParent.inDocument()) - return InsertionDone; - ASSERT(!m_targetElementInstance || !isWellFormedDocument(document())); - ASSERT(!hasPendingResources() || !isWellFormedDocument(document())); - if (!m_wasInsertedByParser) - buildPendingResource(); - SVGExternalResourcesRequired::insertedIntoDocument(this); + if (isConnected()) { + SVGExternalResourcesRequired::insertedIntoDocument(this); + invalidateShadowTree(); + updateExternalDocument(); + } return InsertionDone; } void SVGUseElement::removedFrom(ContainerNode& rootParent) { SVGGraphicsElement::removedFrom(rootParent); - if (rootParent.inDocument()) - clearResourceReferences(); + clearShadowTree(); + updateExternalDocument(); } -Document* SVGUseElement::referencedDocument() const +inline Document* SVGUseElement::externalDocument() const { - if (!isExternalURIReference(href(), document())) - return &document(); - return externalDocument(); + return m_externalDocument ? m_externalDocument->document() : nullptr; } -Document* SVGUseElement::externalDocument() const +void SVGUseElement::transferSizeAttributesToTargetClone(SVGElement& shadowElement) const { - if (m_cachedDocument && m_cachedDocument->isLoaded()) { - // Gracefully handle error condition. - if (m_cachedDocument->errorOccurred()) - return 0; - ASSERT(m_cachedDocument->document()); - return m_cachedDocument->document(); + // FIXME: The check for valueInSpecifiedUnits being non-zero below is a workaround for the fact + // that we currently have no good way to tell whether a particular animatable attribute is a value + // indicating it was unspecified, or specified but could not be parsed. Would be nice to fix that some day. + if (is<SVGSymbolElement>(shadowElement)) { + // Spec (<use> on <symbol>): This generated 'svg' will always have explicit values for attributes width and height. + // If attributes width and/or height are provided on the 'use' element, then these attributes + // will be transferred to the generated 'svg'. If attributes width and/or height are not specified, + // the generated 'svg' element will use values of 100% for these attributes. + shadowElement.setAttribute(SVGNames::widthAttr, (widthIsValid() && width().valueInSpecifiedUnits()) ? AtomicString(width().valueAsString()) : "100%"); + shadowElement.setAttribute(SVGNames::heightAttr, (heightIsValid() && height().valueInSpecifiedUnits()) ? AtomicString(height().valueAsString()) : "100%"); + } else if (is<SVGSVGElement>(shadowElement)) { + // Spec (<use> on <svg>): If attributes width and/or height are provided on the 'use' element, then these + // values will override the corresponding attributes on the 'svg' in the generated tree. + SVGElement* correspondingElement = shadowElement.correspondingElement(); + shadowElement.setAttribute(SVGNames::widthAttr, (widthIsValid() && width().valueInSpecifiedUnits()) ? AtomicString(width().valueAsString()) : (correspondingElement ? correspondingElement->getAttribute(SVGNames::widthAttr) : nullAtom)); + shadowElement.setAttribute(SVGNames::heightAttr, (heightIsValid() && height().valueInSpecifiedUnits()) ? AtomicString(height().valueAsString()) : (correspondingElement ? correspondingElement->getAttribute(SVGNames::heightAttr) : nullAtom)); } - return 0; } void SVGUseElement::svgAttributeChanged(const QualifiedName& attrName) { - if (!isSupportedAttribute(attrName)) { - SVGGraphicsElement::svgAttributeChanged(attrName); - return; - } + InstanceInvalidationGuard guard(*this); - SVGElementInstance::InvalidationGuard invalidationGuard(this); - - auto renderer = this->renderer(); - if (attrName == SVGNames::xAttr - || attrName == SVGNames::yAttr - || attrName == SVGNames::widthAttr - || attrName == SVGNames::heightAttr) { + if (attrName == SVGNames::xAttr || attrName == SVGNames::yAttr || attrName == SVGNames::widthAttr || attrName == SVGNames::heightAttr) { updateRelativeLengthsInformation(); - if (renderer) + if (attrName == SVGNames::widthAttr || attrName == SVGNames::heightAttr) { + // FIXME: It's unnecessarily inefficient to update both width and height each time either is changed. + if (auto* targetClone = this->targetClone()) + transferSizeAttributesToTargetClone(*targetClone); + } + if (auto* renderer = this->renderer()) RenderSVGResource::markForLayoutAndParentResourceInvalidation(*renderer); return; } @@ -240,758 +166,444 @@ void SVGUseElement::svgAttributeChanged(const QualifiedName& attrName) return; if (SVGURIReference::isKnownAttribute(attrName)) { - bool isExternalReference = isExternalURIReference(href(), document()); - if (isExternalReference) { - URL url = document().completeURL(href()); - if (url.hasFragmentIdentifier()) { - CachedResourceRequest request(ResourceRequest(url.string())); - request.setInitiator(this); - setCachedDocument(document().cachedResourceLoader()->requestSVGDocument(request)); - } - } else - setCachedDocument(0); - - if (!m_wasInsertedByParser) - buildPendingResource(); - + updateExternalDocument(); + invalidateShadowTree(); return; } - if (SVGLangSpace::isKnownAttribute(attrName) - || SVGExternalResourcesRequired::isKnownAttribute(attrName)) { + if (SVGLangSpace::isKnownAttribute(attrName) || SVGExternalResourcesRequired::isKnownAttribute(attrName)) { invalidateShadowTree(); return; } - ASSERT_NOT_REACHED(); + SVGGraphicsElement::svgAttributeChanged(attrName); } -void SVGUseElement::willAttachRenderers() +void SVGUseElement::willRecalcStyle(Style::Change change) { - if (m_needsShadowTreeRecreation) - buildPendingResource(); + // FIXME: Shadow tree should be updated before style recalc. + if (m_shadowTreeNeedsUpdate) + updateShadowTree(); + SVGGraphicsElement::willRecalcStyle(change); } -#ifdef DUMP_INSTANCE_TREE -static void dumpInstanceTree(unsigned int& depth, String& text, SVGElementInstance* targetInstance) -{ - SVGElement* element = targetInstance->correspondingElement(); - ASSERT(element); - - if (element->hasTagName(SVGNames::useTag)) { - if (toSVGUseElement(element)->cachedDocumentIsStillLoading()) - return; - } - - SVGElement* shadowTreeElement = targetInstance->shadowTreeElement(); - ASSERT(shadowTreeElement); - - SVGUseElement* directUseElement = targetInstance->directUseElement(); - String directUseElementName = directUseElement ? directUseElement->nodeName() : "null"; - - String elementId = element->getIdAttribute(); - String elementNodeName = element->nodeName(); - String shadowTreeElementNodeName = shadowTreeElement->nodeName(); - String parentNodeName = element->parentNode() ? element->parentNode()->nodeName() : "null"; - String firstChildNodeName = element->firstChild() ? element->firstChild()->nodeName() : "null"; - - for (unsigned int i = 0; i < depth; ++i) - text += " "; - - text += String::format("SVGElementInstance this=%p, (parentNode=%s (%p), firstChild=%s (%p), correspondingElement=%s (%p), directUseElement=%s (%p), shadowTreeElement=%s (%p), id=%s)\n", - targetInstance, parentNodeName.latin1().data(), element->parentNode(), firstChildNodeName.latin1().data(), element->firstChild(), - elementNodeName.latin1().data(), element, directUseElementName.latin1().data(), directUseElement, shadowTreeElementNodeName.latin1().data(), shadowTreeElement, elementId.latin1().data()); - - for (unsigned int i = 0; i < depth; ++i) - text += " "; - - const HashSet<SVGElementInstance*>& elementInstances = element->instancesForElement(); - text += "Corresponding element is associated with " + String::number(elementInstances.size()) + " instance(s):\n"; - - const HashSet<SVGElementInstance*>::const_iterator end = elementInstances.end(); - for (HashSet<SVGElementInstance*>::const_iterator it = elementInstances.begin(); it != end; ++it) { - for (unsigned int i = 0; i < depth; ++i) - text += " "; - - text += String::format(" -> SVGElementInstance this=%p, (refCount: %i, shadowTreeElement in document? %i)\n", - *it, (*it)->refCount(), (*it)->shadowTreeElement()->inDocument()); - } - - ++depth; - - for (SVGElementInstance* instance = targetInstance->firstChild(); instance; instance = instance->nextSibling()) - dumpInstanceTree(depth, text, instance); - - --depth; -} -#endif - -static bool isDisallowedElement(const Element& element) +static HashSet<AtomicString> createAllowedElementSet() { // Spec: "Any 'svg', 'symbol', 'g', graphics element or other 'use' is potentially a template object that can be re-used // (i.e., "instanced") in the SVG document via a 'use' element." // "Graphics Element" is defined as 'circle', 'ellipse', 'image', 'line', 'path', 'polygon', 'polyline', 'rect', 'text' // Excluded are anything that is used by reference or that only make sense to appear once in a document. - - if (!element.isSVGElement()) - return true; - - DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, allowedElementTags, ()); - if (allowedElementTags.isEmpty()) { - allowedElementTags.add(SVGNames::aTag); - allowedElementTags.add(SVGNames::circleTag); - allowedElementTags.add(SVGNames::descTag); - allowedElementTags.add(SVGNames::ellipseTag); - allowedElementTags.add(SVGNames::gTag); - allowedElementTags.add(SVGNames::imageTag); - allowedElementTags.add(SVGNames::lineTag); - allowedElementTags.add(SVGNames::metadataTag); - allowedElementTags.add(SVGNames::pathTag); - allowedElementTags.add(SVGNames::polygonTag); - allowedElementTags.add(SVGNames::polylineTag); - allowedElementTags.add(SVGNames::rectTag); - allowedElementTags.add(SVGNames::svgTag); - allowedElementTags.add(SVGNames::switchTag); - allowedElementTags.add(SVGNames::symbolTag); - allowedElementTags.add(SVGNames::textTag); - allowedElementTags.add(SVGNames::textPathTag); - allowedElementTags.add(SVGNames::titleTag); - allowedElementTags.add(SVGNames::trefTag); - allowedElementTags.add(SVGNames::tspanTag); - allowedElementTags.add(SVGNames::useTag); - } - return !allowedElementTags.contains<SVGAttributeHashTranslator>(element.tagQName()); + using namespace SVGNames; + HashSet<AtomicString> set; + for (auto& tag : { aTag, circleTag, descTag, ellipseTag, gTag, imageTag, lineTag, metadataTag, pathTag, polygonTag, polylineTag, rectTag, svgTag, switchTag, symbolTag, textTag, textPathTag, titleTag, trefTag, tspanTag, useTag }) + set.add(tag.localName()); + return set; } -static bool subtreeContainsDisallowedElement(SVGElement& start) +static inline bool isDisallowedElement(const SVGElement& element) { - for (auto& element : descendantsOfType<Element>(start)) { - if (isDisallowedElement(element)) - return true; - } - - return false; + static NeverDestroyed<HashSet<AtomicString>> set = createAllowedElementSet(); + return !set.get().contains(element.localName()); } -void SVGUseElement::clearResourceReferences() +static inline bool isDisallowedElement(const Element& element) { - // FIXME: We should try to optimize this, to at least allow partial reclones. - if (ShadowRoot* shadowTreeRootElement = shadowRoot()) - shadowTreeRootElement->removeChildren(); - - if (m_targetElementInstance) { - m_targetElementInstance->detach(); - m_targetElementInstance = 0; - } - - m_needsShadowTreeRecreation = false; + return !element.isSVGElement() || isDisallowedElement(downcast<SVGElement>(element)); +} - document().accessSVGExtensions()->removeAllTargetReferencesForElement(this); +void SVGUseElement::clearShadowTree() +{ + if (auto* root = userAgentShadowRoot()) + root->removeChildren(); } void SVGUseElement::buildPendingResource() { - if (!referencedDocument() || isInShadowTree()) - return; - clearResourceReferences(); - if (!inDocument()) - return; - - String id; - Element* target = SVGURIReference::targetElementFromIRIString(href(), document(), &id, externalDocument()); - if (!target || !target->inDocument()) { - // If we can't find the target of an external element, just give up. - // We can't observe if the target somewhen enters the external document, nor should we do it. - if (externalDocument()) - return; - if (id.isEmpty()) - return; - - referencedDocument()->accessSVGExtensions()->addPendingResource(id, this); - ASSERT(hasPendingResources()); - return; - } - - if (target->isSVGElement()) { - buildShadowAndInstanceTree(toSVGElement(target)); - invalidateDependentShadowTrees(); - } - - ASSERT(!m_needsShadowTreeRecreation); + invalidateShadowTree(); } -void SVGUseElement::buildShadowAndInstanceTree(SVGElement* target) +void SVGUseElement::updateShadowTree() { - ASSERT(!m_targetElementInstance); - - // Do not build the shadow/instance tree for <use> elements living in a shadow tree. - // The will be expanded soon anyway - see expandUseElementsInShadowTree(). - if (isInShadowTree()) - return; - - // Do not allow self-referencing. - // 'target' may be null, if it's a non SVG namespaced element. - if (!target || target == this) - return; - - // Why a seperated instance/shadow tree? SVG demands it: - // The instance tree is accesable from JavaScript, and has to - // expose a 1:1 copy of the referenced tree, whereas internally we need - // to alter the tree for correct "use-on-symbol", "use-on-svg" support. - - // Build instance tree. Create root SVGElementInstance object for the first sub-tree node. - // - // Spec: If the 'use' element references a simple graphics element such as a 'rect', then there is only a - // single SVGElementInstance object, and the correspondingElement attribute on this SVGElementInstance object - // is the SVGRectElement that corresponds to the referenced 'rect' element. - m_targetElementInstance = SVGElementInstance::create(this, this, target); + m_shadowTreeNeedsUpdate = false; - // Eventually enter recursion to build SVGElementInstance objects for the sub-tree children - bool foundProblem = false; - buildInstanceTree(target, m_targetElementInstance.get(), foundProblem, false); + // FIXME: It's expensive to re-clone the entire tree every time. We should find a more efficient way to handle this. + clearShadowTree(); - if (instanceTreeIsLoading(m_targetElementInstance.get())) + if (isInShadowTree() || !isConnected()) return; - // SVG specification does not say a word about <use> & cycles. My view on this is: just ignore it! - // Non-appearing <use> content is easier to debug, then half-appearing content. - if (foundProblem) { - clearResourceReferences(); + String targetID; + auto* target = findTarget(&targetID); + if (!target) { + document().accessSVGExtensions().addPendingResource(targetID, this); return; } - // Assure instance tree building was successfull - ASSERT(m_targetElementInstance); - ASSERT(!m_targetElementInstance->shadowTreeElement()); - ASSERT(m_targetElementInstance->correspondingUseElement() == this); - ASSERT(m_targetElementInstance->directUseElement() == this); - ASSERT(m_targetElementInstance->correspondingElement() == target); - - ShadowRoot* shadowTreeRootElement = shadowRoot(); - ASSERT(shadowTreeRootElement); - - // Build shadow tree from instance tree - // This also handles the special cases: <use> on <symbol>, <use> on <svg>. - buildShadowTree(target, m_targetElementInstance.get()); - - // Expand all <use> elements in the shadow tree. - // Expand means: replace the actual <use> element by what it references. - expandUseElementsInShadowTree(shadowTreeRootElement); - - // Expand all <symbol> elements in the shadow tree. - // Expand means: replace the actual <symbol> element by the <svg> element. - expandSymbolElementsInShadowTree(shadowTreeRootElement); - - // Now that the shadow tree is completly expanded, we can associate - // shadow tree elements <-> instances in the instance tree. - associateInstancesWithShadowTreeElements(shadowTreeRootElement->firstChild(), m_targetElementInstance.get()); - - // If no shadow tree element is present, this means that the reference root - // element was removed, as it is disallowed (ie. <use> on <foreignObject>) - // Do NOT leave an inconsistent instance tree around, instead destruct it. - if (!m_targetElementInstance->shadowTreeElement()) { - clearResourceReferences(); - return; - } - - ASSERT(m_targetElementInstance->shadowTreeElement()->parentNode() == shadowTreeRootElement); + cloneTarget(ensureUserAgentShadowRoot(), *target); + expandUseElementsInShadowTree(); + expandSymbolElementsInShadowTree(); + transferEventListenersToShadowTree(); - // Transfer event listeners assigned to the referenced element to our shadow tree elements. - transferEventListenersToShadowTree(m_targetElementInstance.get()); - - // Update relative length information. updateRelativeLengthsInformation(); - // Eventually dump instance tree -#ifdef DUMP_INSTANCE_TREE - String text; - unsigned int depth = 0; - - dumpInstanceTree(depth, text, m_targetElementInstance.get()); - fprintf(stderr, "\nDumping <use> instance tree:\n%s\n", text.latin1().data()); -#endif + // When we invalidate the other shadow trees, it's important that we don't + // follow any cycles and invalidate ourselves. To avoid that, we temporarily + // set m_shadowTreeNeedsUpdate to true so invalidateShadowTree will + // quickly return and do nothing. + ASSERT(!m_shadowTreeNeedsUpdate); + m_shadowTreeNeedsUpdate = true; + invalidateDependentShadowTrees(); + m_shadowTreeNeedsUpdate = false; +} - // Eventually dump shadow tree -#ifdef DUMP_SHADOW_TREE - RefPtr<XMLSerializer> serializer = XMLSerializer::create(); - String markup = serializer->serializeToString(shadowTreeRootElement, ASSERT_NO_EXCEPTION); - fprintf(stderr, "Dumping <use> shadow tree markup:\n%s\n", markup.latin1().data()); -#endif +SVGElement* SVGUseElement::targetClone() const +{ + auto* root = userAgentShadowRoot(); + if (!root) + return nullptr; + return childrenOfType<SVGElement>(*root).first(); } -RenderPtr<RenderElement> SVGUseElement::createElementRenderer(PassRef<RenderStyle> style) +RenderPtr<RenderElement> SVGUseElement::createElementRenderer(RenderStyle&& style, const RenderTreePosition&) { - return createRenderer<RenderSVGTransformableContainer>(*this, std::move(style)); + return createRenderer<RenderSVGTransformableContainer>(*this, WTFMove(style)); } -static bool isDirectReference(const Node* node) +static bool isDirectReference(const SVGElement& element) { - return node->hasTagName(SVGNames::pathTag) - || node->hasTagName(SVGNames::rectTag) - || node->hasTagName(SVGNames::circleTag) - || node->hasTagName(SVGNames::ellipseTag) - || node->hasTagName(SVGNames::polygonTag) - || node->hasTagName(SVGNames::polylineTag) - || node->hasTagName(SVGNames::textTag); + using namespace SVGNames; + return element.hasTagName(circleTag) + || element.hasTagName(ellipseTag) + || element.hasTagName(pathTag) + || element.hasTagName(polygonTag) + || element.hasTagName(polylineTag) + || element.hasTagName(rectTag) + || element.hasTagName(textTag); } void SVGUseElement::toClipPath(Path& path) { ASSERT(path.isEmpty()); - Node* n = m_targetElementInstance ? m_targetElementInstance->shadowTreeElement() : 0; - if (!n) + auto* targetClone = this->targetClone(); + if (!is<SVGGraphicsElement>(targetClone)) return; - if (n->isSVGElement() && toSVGElement(n)->isSVGGraphicsElement()) { - if (!isDirectReference(n)) - // Spec: Indirect references are an error (14.3.5) - document().accessSVGExtensions()->reportError("Not allowed to use indirect reference in <clip-path>"); - else { - toSVGGraphicsElement(n)->toClipPath(path); - // FIXME: Avoid manual resolution of x/y here. Its potentially harmful. - SVGLengthContext lengthContext(this); - path.translate(FloatSize(x().value(lengthContext), y().value(lengthContext))); - path.transform(animatedLocalTransform()); - } + if (!isDirectReference(*targetClone)) { + // Spec: Indirect references are an error (14.3.5) + document().accessSVGExtensions().reportError(ASCIILiteral("Not allowed to use indirect reference in <clip-path>")); + return; } + + downcast<SVGGraphicsElement>(*targetClone).toClipPath(path); + SVGLengthContext lengthContext(this); + // FIXME: Find a way to do this without manual resolution of x/y here. It's potentially incorrect. + path.translate(FloatSize(x().value(lengthContext), y().value(lengthContext))); + path.transform(animatedLocalTransform()); } RenderElement* SVGUseElement::rendererClipChild() const { - Node* n = m_targetElementInstance ? m_targetElementInstance->shadowTreeElement() : 0; - if (!n) - return 0; - - if (n->isSVGElement() && isDirectReference(n)) - return toSVGElement(n)->renderer(); - - return 0; + auto* targetClone = this->targetClone(); + if (!targetClone) + return nullptr; + if (!isDirectReference(*targetClone)) + return nullptr; + return targetClone->renderer(); } -void SVGUseElement::buildInstanceTree(SVGElement* target, SVGElementInstance* targetInstance, bool& foundProblem, bool foundUse) +static inline void disassociateAndRemoveClones(const Vector<Element*>& clones) { - ASSERT(target); - ASSERT(targetInstance); - - // Spec: If the referenced object is itself a 'use', or if there are 'use' subelements within the referenced - // object, the instance tree will contain recursive expansion of the indirect references to form a complete tree. - bool targetHasUseTag = target->hasTagName(SVGNames::useTag); - SVGElement* newTarget = 0; - if (targetHasUseTag) { - foundProblem = hasCycleUseReferencing(toSVGUseElement(target), targetInstance, newTarget); - if (foundProblem) - return; - - // We only need to track first degree <use> dependencies. Indirect references are handled - // as the invalidation bubbles up the dependency chain. - if (!foundUse) { - document().accessSVGExtensions()->addElementReferencingTarget(this, target); - foundUse = true; - } - } else if (isDisallowedElement(*target)) { - foundProblem = true; - return; - } - - // A general description from the SVG spec, describing what buildInstanceTree() actually does. - // - // Spec: If the 'use' element references a 'g' which contains two 'rect' elements, then the instance tree - // contains three SVGElementInstance objects, a root SVGElementInstance object whose correspondingElement - // is the SVGGElement object for the 'g', and then two child SVGElementInstance objects, each of which has - // its correspondingElement that is an SVGRectElement object. - - for (auto& element : childrenOfType<SVGElement>(*target)) { - // Skip any non-svg nodes or any disallowed element. - if (isDisallowedElement(element)) - continue; - - // Create SVGElementInstance object, for both container/non-container nodes. - RefPtr<SVGElementInstance> instance = SVGElementInstance::create(this, 0, &element); - SVGElementInstance* instancePtr = instance.get(); - targetInstance->appendChild(instance.release()); - - // Enter recursion, appending new instance tree nodes to the "instance" object. - buildInstanceTree(&element, instancePtr, foundProblem, foundUse); - if (foundProblem) - return; + for (auto& clone : clones) { + for (auto& descendant : descendantsOfType<SVGElement>(*clone)) + descendant.setCorrespondingElement(nullptr); + clone->parentNode()->removeChild(*clone); } - - if (!targetHasUseTag || !newTarget) - return; - - RefPtr<SVGElementInstance> newInstance = SVGElementInstance::create(this, toSVGUseElement(target), newTarget); - SVGElementInstance* newInstancePtr = newInstance.get(); - targetInstance->appendChild(newInstance.release()); - buildInstanceTree(newTarget, newInstancePtr, foundProblem, foundUse); } -bool SVGUseElement::hasCycleUseReferencing(SVGUseElement* use, SVGElementInstance* targetInstance, SVGElement*& newTarget) +static void removeDisallowedElementsFromSubtree(SVGElement& subtree) { - ASSERT(referencedDocument()); - Element* targetElement = SVGURIReference::targetElementFromIRIString(use->href(), *referencedDocument()); - newTarget = 0; - if (targetElement && targetElement->isSVGElement()) - newTarget = toSVGElement(targetElement); - - if (!newTarget) - return false; - - // Shortcut for self-references - if (newTarget == this) - return true; + // Remove disallowed elements after the fact rather than not cloning them in the first place. + // This optimizes for the normal case where none of those elements are present. - AtomicString targetId = newTarget->getIdAttribute(); - SVGElementInstance* instance = targetInstance->parentNode(); - while (instance) { - SVGElement* element = instance->correspondingElement(); + // This function is used only on elements in subtrees that are not yet in documents, so + // mutation events are not a factor; there are no event listeners to handle those events. + // Assert that it's not in a document to make sure callers are still using it this way. + ASSERT(!subtree.isConnected()); - if (element->hasID() && element->getIdAttribute() == targetId && &element->document() == &newTarget->document()) - return true; - - instance = instance->parentNode(); - } - return false; -} - -static inline void removeDisallowedElementsFromSubtree(SVGElement& subtree) -{ - ASSERT(!subtree.inDocument()); - Vector<Element*> toRemove; - auto it = descendantsOfType<Element>(subtree).begin(); - auto end = descendantsOfType<Element>(subtree).end(); - while (it != end) { + Vector<Element*> disallowedElements; + auto descendants = descendantsOfType<Element>(subtree); + for (auto it = descendants.begin(), end = descendants.end(); it != end; ) { if (isDisallowedElement(*it)) { - toRemove.append(&*it); + disallowedElements.append(&*it); it.traverseNextSkippingChildren(); continue; } ++it; } - // The subtree is not in document so this won't generate events that could mutate the tree. - for (unsigned i = 0; i < toRemove.size(); ++i) - toRemove[i]->parentNode()->removeChild(toRemove[i]); + + disassociateAndRemoveClones(disallowedElements); } -void SVGUseElement::buildShadowTree(SVGElement* target, SVGElementInstance* targetInstance) +static void removeSymbolElementsFromSubtree(SVGElement& subtree) { - ASSERT(target); // FIXME: Don't be a pointer! - - // For instance <use> on <foreignObject> (direct case). - if (isDisallowedElement(*target)) - return; - - RefPtr<SVGElement> newChild = static_pointer_cast<SVGElement>(targetInstance->correspondingElement()->cloneElementWithChildren()); - - // We don't walk the target tree element-by-element, and clone each element, - // but instead use cloneElementWithChildren(). This is an optimization for the common - // case where <use> doesn't contain disallowed elements (ie. <foreignObject>). - // Though if there are disallowed elements in the subtree, we have to remove them. - // For instance: <use> on <g> containing <foreignObject> (indirect case). - if (subtreeContainsDisallowedElement(*newChild)) - removeDisallowedElementsFromSubtree(*newChild); - - shadowRoot()->appendChild(newChild.release()); + // Symbol elements inside the subtree should not be cloned for two reasons: 1) They are invisible and + // don't need to be cloned to get correct rendering. 2) expandSymbolElementsInShadowTree will turn them + // into <svg> elements, which is correct for symbol elements directly referenced by use elements, + // but incorrect for ones that just happen to be in a subtree. + Vector<Element*> symbolElements; + for (auto& descendant : descendantsOfType<SVGSymbolElement>(subtree)) + symbolElements.append(&descendant); + disassociateAndRemoveClones(symbolElements); } -void SVGUseElement::expandUseElementsInShadowTree(Node* element) +static void associateClonesWithOriginals(SVGElement& clone, SVGElement& original) { - // Why expand the <use> elements in the shadow tree here, and not just - // do this directly in buildShadowTree, if we encounter a <use> element? - // - // Short answer: Because we may miss to expand some elements. Ie. if a <symbol> - // contains <use> tags, we'd miss them. So once we're done with settin' up the - // actual shadow tree (after the special case modification for svg/symbol) we have - // to walk it completely and expand all <use> elements. - if (element->hasTagName(SVGNames::useTag)) { - SVGUseElement* use = toSVGUseElement(element); - ASSERT(!use->cachedDocumentIsStillLoading()); - - ASSERT(referencedDocument()); - Element* targetElement = SVGURIReference::targetElementFromIRIString(use->href(), *referencedDocument()); - SVGElement* target = 0; - if (targetElement && targetElement->isSVGElement()) - target = toSVGElement(targetElement); + // This assertion checks that we don't call this with the arguments backwards. + // The clone is new and so it's not installed in a parent yet. + ASSERT(!clone.parentNode()); - // Don't ASSERT(target) here, it may be "pending", too. - // Setup sub-shadow tree root node - RefPtr<SVGGElement> cloneParent = SVGGElement::create(SVGNames::gTag, *referencedDocument()); - use->cloneChildNodes(cloneParent.get()); - - // Spec: In the generated content, the 'use' will be replaced by 'g', where all attributes from the - // 'use' element except for x, y, width, height and xlink:href are transferred to the generated 'g' element. - transferUseAttributesToReplacedElement(use, cloneParent.get()); + // The loop below works because we are associating these clones immediately, before + // doing transformations like removing disallowed elements or expanding elements. + clone.setCorrespondingElement(&original); + for (auto pair : descendantsOfType<SVGElement>(clone, original)) + pair.first.setCorrespondingElement(&pair.second); +} - if (target && !isDisallowedElement(*target)) { - RefPtr<Element> newChild = target->cloneElementWithChildren(); - ASSERT(newChild->isSVGElement()); - cloneParent->appendChild(newChild.release()); - } +static void associateReplacementCloneWithOriginal(SVGElement& replacementClone, SVGElement& originalClone) +{ + auto* correspondingElement = originalClone.correspondingElement(); + ASSERT(correspondingElement); + originalClone.setCorrespondingElement(nullptr); + replacementClone.setCorrespondingElement(correspondingElement); +} - // We don't walk the target tree element-by-element, and clone each element, - // but instead use cloneElementWithChildren(). This is an optimization for the common - // case where <use> doesn't contain disallowed elements (ie. <foreignObject>). - // Though if there are disallowed elements in the subtree, we have to remove them. - // For instance: <use> on <g> containing <foreignObject> (indirect case). - if (subtreeContainsDisallowedElement(*cloneParent)) - removeDisallowedElementsFromSubtree(*cloneParent); - - RefPtr<Node> replacingElement(cloneParent.get()); - - // Replace <use> with referenced content. - ASSERT(use->parentNode()); - use->parentNode()->replaceChild(cloneParent.release(), use); - - // Expand the siblings because the *element* is replaced and we will - // lose the sibling chain when we are back from recursion. - element = replacingElement.get(); - for (RefPtr<Node> sibling = element->nextSibling(); sibling; sibling = sibling->nextSibling()) - expandUseElementsInShadowTree(sibling.get()); - } +static void associateReplacementClonesWithOriginals(SVGElement& replacementClone, SVGElement& originalClone) +{ + // This assertion checks that we don't call this with the arguments backwards. + // The replacement clone is new and so it's not installed in a parent yet. + ASSERT(!replacementClone.parentNode()); - for (RefPtr<Node> child = element->firstChild(); child; child = child->nextSibling()) - expandUseElementsInShadowTree(child.get()); + // The loop below works because we are associating these clones immediately, before + // doing transformations like removing disallowed elements or expanding elements. + associateReplacementCloneWithOriginal(replacementClone, originalClone); + for (auto pair : descendantsOfType<SVGElement>(replacementClone, originalClone)) + associateReplacementCloneWithOriginal(pair.first, pair.second); } -void SVGUseElement::expandSymbolElementsInShadowTree(Node* element) +SVGElement* SVGUseElement::findTarget(String* targetID) const { - if (element->hasTagName(SVGNames::symbolTag)) { - // Spec: The referenced 'symbol' and its contents are deep-cloned into the generated tree, - // with the exception that the 'symbol' is replaced by an 'svg'. This generated 'svg' will - // always have explicit values for attributes width and height. If attributes width and/or - // height are provided on the 'use' element, then these attributes will be transferred to - // the generated 'svg'. If attributes width and/or height are not specified, the generated - // 'svg' element will use values of 100% for these attributes. - RefPtr<SVGSVGElement> svgElement = SVGSVGElement::create(SVGNames::svgTag, *referencedDocument()); - - // Transfer all data (attributes, etc.) from <symbol> to the new <svg> element. - svgElement->cloneDataFromElement(*toElement(element)); + auto* correspondingElement = this->correspondingElement(); + auto& original = correspondingElement ? downcast<SVGUseElement>(*correspondingElement) : *this; - // Only clone symbol children, and add them to the new <svg> element - for (Node* child = element->firstChild(); child; child = child->nextSibling()) { - RefPtr<Node> newChild = child->cloneNode(true); - svgElement->appendChild(newChild.release()); + auto* targetCandidate = targetElementFromIRIString(original.href(), original.document(), targetID, original.externalDocument()); + if (targetID && !targetID->isNull()) { + // If the reference is external, don't return the target ID to the caller. + // The caller would use the target ID to wait for a pending resource on the wrong document. + // If we ever want the change that and let the caller to wait on the external document, + // we should change this function so it returns the appropriate document to go with the ID. + if (isExternalURIReference(original.href(), original.document())) + *targetID = String(); + } + if (!is<SVGElement>(targetCandidate)) + return nullptr; + auto& target = downcast<SVGElement>(*targetCandidate); + + if (!target.isConnected() || isDisallowedElement(target)) + return nullptr; + + // Reject any target that has already been cloned to create one of the ancestors of this element, + // already in the shadow tree. This is sufficient to prevent cycles. + if (correspondingElement) { + for (auto& ancestor : lineageOfType<SVGElement>(*this)) { + if (ancestor.correspondingElement() == &target) + return nullptr; } - - // We don't walk the target tree element-by-element, and clone each element, - // but instead use cloneNode(deep=true). This is an optimization for the common - // case where <use> doesn't contain disallowed elements (ie. <foreignObject>). - // Though if there are disallowed elements in the subtree, we have to remove them. - // For instance: <use> on <g> containing <foreignObject> (indirect case). - if (subtreeContainsDisallowedElement(*svgElement)) - removeDisallowedElementsFromSubtree(*svgElement); - - RefPtr<Node> replacingElement(svgElement.get()); - - // Replace <symbol> with <svg>. - element->parentNode()->replaceChild(svgElement.release(), element); - - // Expand the siblings because the *element* is replaced and we will - // lose the sibling chain when we are back from recursion. - element = replacingElement.get(); - for (RefPtr<Node> sibling = element->nextSibling(); sibling; sibling = sibling->nextSibling()) - expandSymbolElementsInShadowTree(sibling.get()); } - for (RefPtr<Node> child = element->firstChild(); child; child = child->nextSibling()) - expandSymbolElementsInShadowTree(child.get()); + return ⌖ } -void SVGUseElement::transferEventListenersToShadowTree(SVGElementInstance* target) +void SVGUseElement::cloneTarget(ContainerNode& container, SVGElement& target) const { - if (!target) - return; - - SVGElement* originalElement = target->correspondingElement(); - ASSERT(originalElement); + Ref<SVGElement> targetClone = static_cast<SVGElement&>(target.cloneElementWithChildren(document()).get()); + associateClonesWithOriginals(targetClone.get(), target); + removeDisallowedElementsFromSubtree(targetClone.get()); + removeSymbolElementsFromSubtree(targetClone.get()); + transferSizeAttributesToTargetClone(targetClone.get()); + container.appendChild(targetClone); +} - if (SVGElement* shadowTreeElement = target->shadowTreeElement()) { - if (EventTargetData* data = originalElement->eventTargetData()) - data->eventListenerMap.copyEventListenersNotCreatedFromMarkupToTarget(shadowTreeElement); - } +static void cloneDataAndChildren(SVGElement& replacementClone, SVGElement& originalClone) +{ + // This assertion checks that we don't call this with the arguments backwards. + // The replacement clone is new and so it's not installed in a parent yet. + ASSERT(!replacementClone.parentNode()); - for (SVGElementInstance* instance = target->firstChild(); instance; instance = instance->nextSibling()) - transferEventListenersToShadowTree(instance); + replacementClone.cloneDataFromElement(originalClone); + originalClone.cloneChildNodes(replacementClone); + associateReplacementClonesWithOriginals(replacementClone, originalClone); + removeDisallowedElementsFromSubtree(replacementClone); } -void SVGUseElement::associateInstancesWithShadowTreeElements(Node* target, SVGElementInstance* targetInstance) +void SVGUseElement::expandUseElementsInShadowTree() const { - if (!target || !targetInstance) - return; + auto descendants = descendantsOfType<SVGUseElement>(*userAgentShadowRoot()); + for (auto it = descendants.begin(), end = descendants.end(); it != end; ) { + SVGUseElement& originalClone = *it; + it = end; // Efficiently quiets assertions due to the outstanding iterator. - SVGElement* originalElement = targetInstance->correspondingElement(); + auto* target = originalClone.findTarget(); - if (originalElement->hasTagName(SVGNames::useTag)) { - // <use> gets replaced by <g> - ASSERT(target->nodeName() == SVGNames::gTag); - } else if (originalElement->hasTagName(SVGNames::symbolTag)) { - // <symbol> gets replaced by <svg> - ASSERT(target->nodeName() == SVGNames::svgTag); - } else - ASSERT(target->nodeName() == originalElement->nodeName()); + // Spec: In the generated content, the 'use' will be replaced by 'g', where all attributes from the + // 'use' element except for x, y, width, height and xlink:href are transferred to the generated 'g' element. - SVGElement* element = 0; - if (target->isSVGElement()) - element = toSVGElement(target); + auto replacementClone = SVGGElement::create(document()); + cloneDataAndChildren(replacementClone.get(), originalClone); - ASSERT(!targetInstance->shadowTreeElement()); - targetInstance->setShadowTreeElement(element); - element->setCorrespondingElement(originalElement); + replacementClone->removeAttribute(SVGNames::xAttr); + replacementClone->removeAttribute(SVGNames::yAttr); + replacementClone->removeAttribute(SVGNames::widthAttr); + replacementClone->removeAttribute(SVGNames::heightAttr); + replacementClone->removeAttribute(XLinkNames::hrefAttr); - Node* node = target->firstChild(); - for (SVGElementInstance* instance = targetInstance->firstChild(); node && instance; instance = instance->nextSibling()) { - // Skip any non-svg elements in shadow tree - while (node && !node->isSVGElement()) - node = node->nextSibling(); + if (target) + originalClone.cloneTarget(replacementClone.get(), *target); - if (!node) - break; + originalClone.parentNode()->replaceChild(replacementClone, originalClone); - associateInstancesWithShadowTreeElements(node, instance); - node = node->nextSibling(); + // Resume iterating, starting just inside the replacement clone. + it = descendants.from(replacementClone.get()); } } -SVGElementInstance* SVGUseElement::instanceForShadowTreeElement(Node* element) const +void SVGUseElement::expandSymbolElementsInShadowTree() const { - if (!m_targetElementInstance) { - ASSERT(!inDocument()); - return 0; - } - - return instanceForShadowTreeElement(element, m_targetElementInstance.get()); -} + auto descendants = descendantsOfType<SVGSymbolElement>(*userAgentShadowRoot()); + for (auto it = descendants.begin(), end = descendants.end(); it != end; ) { + SVGSymbolElement& originalClone = *it; + it = end; // Efficiently quiets assertions due to the outstanding iterator. -SVGElementInstance* SVGUseElement::instanceForShadowTreeElement(Node* element, SVGElementInstance* instance) const -{ - ASSERT(element); - ASSERT(instance); + // Spec: The referenced 'symbol' and its contents are deep-cloned into the generated tree, + // with the exception that the 'symbol' is replaced by an 'svg'. This generated 'svg' will + // always have explicit values for attributes width and height. If attributes width and/or + // height are provided on the 'use' element, then these attributes will be transferred to + // the generated 'svg'. If attributes width and/or height are not specified, the generated + // 'svg' element will use values of 100% for these attributes. - // We're dispatching a mutation event during shadow tree construction - // this instance hasn't yet been associated to a shadowTree element. - if (!instance->shadowTreeElement()) - return 0; + auto replacementClone = SVGSVGElement::create(document()); + cloneDataAndChildren(replacementClone.get(), originalClone); - if (element == instance->shadowTreeElement()) - return instance; + originalClone.parentNode()->replaceChild(replacementClone, originalClone); - for (SVGElementInstance* current = instance->firstChild(); current; current = current->nextSibling()) { - if (SVGElementInstance* search = instanceForShadowTreeElement(element, current)) - return search; + // Resume iterating, starting just inside the replacement clone. + it = descendants.from(replacementClone.get()); } +} - return 0; +void SVGUseElement::transferEventListenersToShadowTree() const +{ + for (auto& descendant : descendantsOfType<SVGElement>(*userAgentShadowRoot())) { + if (EventTargetData* data = descendant.correspondingElement()->eventTargetData()) + data->eventListenerMap.copyEventListenersNotCreatedFromMarkupToTarget(&descendant); + } } void SVGUseElement::invalidateShadowTree() { - if (m_needsShadowTreeRecreation) + if (m_shadowTreeNeedsUpdate) return; - m_needsShadowTreeRecreation = true; - setNeedsStyleRecalc(ReconstructRenderTree); + m_shadowTreeNeedsUpdate = true; + invalidateStyleAndRenderersForSubtree(); invalidateDependentShadowTrees(); } void SVGUseElement::invalidateDependentShadowTrees() { - // Recursively invalidate dependent <use> shadow trees - const HashSet<SVGElementInstance*>& instances = instancesForElement(); - const HashSet<SVGElementInstance*>::const_iterator end = instances.end(); - for (HashSet<SVGElementInstance*>::const_iterator it = instances.begin(); it != end; ++it) { - if (SVGUseElement* element = (*it)->correspondingUseElement()) { - ASSERT(element->inDocument()); + for (auto* instance : instances()) { + if (auto* element = instance->correspondingUseElement()) element->invalidateShadowTree(); - } } } -void SVGUseElement::transferUseAttributesToReplacedElement(SVGElement* from, SVGElement* to) const -{ - ASSERT(from); - ASSERT(to); - - to->cloneDataFromElement(*from); - - to->removeAttribute(SVGNames::xAttr); - to->removeAttribute(SVGNames::yAttr); - to->removeAttribute(SVGNames::widthAttr); - to->removeAttribute(SVGNames::heightAttr); - to->removeAttribute(XLinkNames::hrefAttr); -} - bool SVGUseElement::selfHasRelativeLengths() const { - if (x().isRelative() - || y().isRelative() - || width().isRelative() - || height().isRelative()) + if (x().isRelative() || y().isRelative() || width().isRelative() || height().isRelative()) return true; - if (!m_targetElementInstance) - return false; - - SVGElement* element = m_targetElementInstance->correspondingElement(); - if (!element) - return false; - - return element->hasRelativeLengths(); + auto* targetClone = this->targetClone(); + return targetClone && targetClone->hasRelativeLengths(); } -void SVGUseElement::notifyFinished(CachedResource* resource) +void SVGUseElement::notifyFinished(CachedResource& resource) { - if (!inDocument()) - return; - invalidateShadowTree(); - if (resource->errorOccurred()) + if (resource.errorOccurred()) dispatchEvent(Event::create(eventNames().errorEvent, false, false)); - else if (!resource->wasCanceled()) + else if (!resource.wasCanceled()) SVGExternalResourcesRequired::dispatchLoadEvent(this); } -bool SVGUseElement::cachedDocumentIsStillLoading() +void SVGUseElement::finishParsingChildren() { - if (m_cachedDocument && m_cachedDocument->isLoading()) - return true; - return false; + SVGGraphicsElement::finishParsingChildren(); + SVGExternalResourcesRequired::finishParsingChildren(); } -bool SVGUseElement::instanceTreeIsLoading(SVGElementInstance* targetElementInstance) +void SVGUseElement::updateExternalDocument() { - for (SVGElementInstance* instance = targetElementInstance->firstChild(); instance; instance = instance->nextSibling()) { - if (SVGUseElement* use = instance->correspondingUseElement()) { - if (use->cachedDocumentIsStillLoading()) - return true; - } - if (instance->hasChildNodes()) - instanceTreeIsLoading(instance); + URL externalDocumentURL; + if (isConnected() && isExternalURIReference(href(), document())) { + externalDocumentURL = document().completeURL(href()); + if (!externalDocumentURL.hasFragmentIdentifier()) + externalDocumentURL = URL(); } - return false; + + if (externalDocumentURL == (m_externalDocument ? m_externalDocument->url() : URL())) + return; + + if (m_externalDocument) + m_externalDocument->removeClient(*this); + + if (externalDocumentURL.isNull()) + m_externalDocument = nullptr; + else { + ResourceLoaderOptions options = CachedResourceLoader::defaultCachedResourceOptions(); + options.contentSecurityPolicyImposition = isInUserAgentShadowTree() ? ContentSecurityPolicyImposition::SkipPolicyCheck : ContentSecurityPolicyImposition::DoPolicyCheck; + options.mode = FetchOptions::Mode::SameOrigin; + CachedResourceRequest request { ResourceRequest { externalDocumentURL }, options }; + request.setInitiator(*this); + m_externalDocument = document().cachedResourceLoader().requestSVGDocument(WTFMove(request)); + if (m_externalDocument) + m_externalDocument->addClient(*this); + } + + invalidateShadowTree(); } -void SVGUseElement::finishParsingChildren() +bool SVGUseElement::isValid() const { - SVGGraphicsElement::finishParsingChildren(); - SVGExternalResourcesRequired::finishParsingChildren(); - if (m_wasInsertedByParser) { - buildPendingResource(); - m_wasInsertedByParser = false; - } + return SVGTests::isValid(); } -void SVGUseElement::setCachedDocument(CachedResourceHandle<CachedSVGDocument> cachedDocument) +bool SVGUseElement::haveLoadedRequiredResources() { - if (m_cachedDocument == cachedDocument) - return; + return SVGExternalResourcesRequired::haveLoadedRequiredResources(); +} - if (m_cachedDocument) - m_cachedDocument->removeClient(this); +void SVGUseElement::setHaveFiredLoadEvent(bool haveFiredLoadEvent) +{ + m_haveFiredLoadEvent = haveFiredLoadEvent; +} - m_cachedDocument = cachedDocument; - if (m_cachedDocument) - m_cachedDocument->addClient(this); +bool SVGUseElement::haveFiredLoadEvent() const +{ + return m_haveFiredLoadEvent; } +Timer* SVGUseElement::svgLoadEventTimer() +{ + return &m_svgLoadEventTimer; } -#endif // ENABLE(SVG) +} |