#include "config.h"
#include "SVGUseElement.h"
#include "CachedResourceLoader.h"
#include "CachedSVGDocument.h"
#include "ElementIterator.h"
#include "Event.h"
#include "EventNames.h"
#include "RenderSVGResource.h"
#include "RenderSVGTransformableContainer.h"
#include "ShadowRoot.h"
#include "SVGGElement.h"
#include "SVGSVGElement.h"
#include "SVGSymbolElement.h"
#include "XLinkNames.h"
namespace WebCore {
DEFINE_ANIMATED_LENGTH(SVGUseElement, SVGNames::xAttr, X, x)
DEFINE_ANIMATED_LENGTH(SVGUseElement, SVGNames::yAttr, Y, y)
DEFINE_ANIMATED_LENGTH(SVGUseElement, SVGNames::widthAttr, Width, width)
DEFINE_ANIMATED_LENGTH(SVGUseElement, SVGNames::heightAttr, Height, height)
DEFINE_ANIMATED_STRING(SVGUseElement, XLinkNames::hrefAttr, Href, href)
DEFINE_ANIMATED_BOOLEAN(SVGUseElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGUseElement)
REGISTER_LOCAL_ANIMATED_PROPERTY(x)
REGISTER_LOCAL_ANIMATED_PROPERTY(y)
REGISTER_LOCAL_ANIMATED_PROPERTY(width)
REGISTER_LOCAL_ANIMATED_PROPERTY(height)
REGISTER_LOCAL_ANIMATED_PROPERTY(href)
REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
END_REGISTER_ANIMATED_PROPERTIES
inline SVGUseElement::SVGUseElement(const QualifiedName& tagName, Document& document)
: SVGGraphicsElement(tagName, document)
, m_x(LengthModeWidth)
, m_y(LengthModeHeight)
, m_width(LengthModeWidth)
, m_height(LengthModeHeight)
, m_svgLoadEventTimer(*this, &SVGElement::svgLoadEventTimerFired)
{
ASSERT(hasCustomStyleResolveCallbacks());
ASSERT(hasTagName(SVGNames::useTag));
registerAnimatedPropertiesForSVGUseElement();
}
Ref<SVGUseElement> SVGUseElement::create(const QualifiedName& tagName, Document& document)
{
return adoptRef(*new SVGUseElement(tagName, document));
}
SVGUseElement::~SVGUseElement()
{
if (m_externalDocument)
m_externalDocument->removeClient(this);
}
void SVGUseElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
SVGParsingError parseError = NoError;
if (name == SVGNames::xAttr)
setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
else if (name == SVGNames::yAttr)
setYBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
else if (name == SVGNames::widthAttr)
setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths));
else if (name == SVGNames::heightAttr)
setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths));
reportAttributeParsingError(parseError, name, value);
SVGExternalResourcesRequired::parseAttribute(name, value);
SVGGraphicsElement::parseAttribute(name, value);
SVGURIReference::parseAttribute(name, value);
}
Node::InsertionNotificationRequest SVGUseElement::insertedInto(ContainerNode& rootParent)
{
SVGGraphicsElement::insertedInto(rootParent);
if (inDocument()) {
SVGExternalResourcesRequired::insertedIntoDocument(this);
invalidateShadowTree();
updateExternalDocument();
}
return InsertionDone;
}
void SVGUseElement::removedFrom(ContainerNode& rootParent)
{
SVGGraphicsElement::removedFrom(rootParent);
clearShadowTree();
updateExternalDocument();
}
inline Document* SVGUseElement::externalDocument() const
{
return m_externalDocument ? m_externalDocument->document() : nullptr;
}
void SVGUseElement::transferSizeAttributesToTargetClone(SVGElement& shadowElement) const
{
if (is<SVGSymbolElement>(shadowElement)) {
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)) {
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));
}
}
void SVGUseElement::svgAttributeChanged(const QualifiedName& attrName)
{
InstanceInvalidationGuard guard(*this);
if (attrName == SVGNames::xAttr || attrName == SVGNames::yAttr || attrName == SVGNames::widthAttr || attrName == SVGNames::heightAttr) {
updateRelativeLengthsInformation();
if (attrName == SVGNames::widthAttr || attrName == SVGNames::heightAttr) {
if (auto* targetClone = this->targetClone())
transferSizeAttributesToTargetClone(*targetClone);
}
if (auto* renderer = this->renderer())
RenderSVGResource::markForLayoutAndParentResourceInvalidation(*renderer);
return;
}
if (SVGExternalResourcesRequired::handleAttributeChange(this, attrName))
return;
if (SVGURIReference::isKnownAttribute(attrName)) {
updateExternalDocument();
invalidateShadowTree();
return;
}
if (SVGLangSpace::isKnownAttribute(attrName) || SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
invalidateShadowTree();
return;
}
SVGGraphicsElement::svgAttributeChanged(attrName);
}
bool SVGUseElement::willRecalcStyle(Style::Change change)
{
if (m_shadowTreeNeedsUpdate)
updateShadowTree();
return SVGGraphicsElement::willRecalcStyle(change);
}
static HashSet<AtomicString> createAllowedElementSet()
{
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 inline bool isDisallowedElement(const SVGElement& element)
{
static NeverDestroyed<HashSet<AtomicString>> set = createAllowedElementSet();
return !set.get().contains(element.localName());
}
static inline bool isDisallowedElement(const Element& element)
{
return !element.isSVGElement() || isDisallowedElement(downcast<SVGElement>(element));
}
void SVGUseElement::clearShadowTree()
{
if (auto* root = userAgentShadowRoot())
root->removeChildren();
}
void SVGUseElement::buildPendingResource()
{
invalidateShadowTree();
}
void SVGUseElement::updateShadowTree()
{
m_shadowTreeNeedsUpdate = false;
clearShadowTree();
if (isInShadowTree() || !inDocument())
return;
String targetID;
auto* target = findTarget(&targetID);
if (!target) {
document().accessSVGExtensions().addPendingResource(targetID, this);
return;
}
cloneTarget(ensureUserAgentShadowRoot(), *target);
expandUseElementsInShadowTree();
expandSymbolElementsInShadowTree();
transferEventListenersToShadowTree();
updateRelativeLengthsInformation();
ASSERT(!m_shadowTreeNeedsUpdate);
m_shadowTreeNeedsUpdate = true;
invalidateDependentShadowTrees();
m_shadowTreeNeedsUpdate = false;
}
SVGElement* SVGUseElement::targetClone() const
{
auto* root = userAgentShadowRoot();
if (!root)
return nullptr;
return downcast<SVGElement>(root->firstChild());
}
RenderPtr<RenderElement> SVGUseElement::createElementRenderer(RenderStyle&& style, const RenderTreePosition&)
{
return createRenderer<RenderSVGTransformableContainer>(*this, WTFMove(style));
}
static bool isDirectReference(const SVGElement& element)
{
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());
auto* targetClone = this->targetClone();
if (!is<SVGGraphicsElement>(targetClone))
return;
if (!isDirectReference(*targetClone)) {
document().accessSVGExtensions().reportError(ASCIILiteral("Not allowed to use indirect reference in <clip-path>"));
return;
}
downcast<SVGGraphicsElement>(*targetClone).toClipPath(path);
SVGLengthContext lengthContext(this);
path.translate(FloatSize(x().value(lengthContext), y().value(lengthContext)));
path.transform(animatedLocalTransform());
}
RenderElement* SVGUseElement::rendererClipChild() const
{
auto* targetClone = this->targetClone();
if (!targetClone)
return nullptr;
if (!isDirectReference(*targetClone))
return nullptr;
return targetClone->renderer();
}
static inline void disassociateAndRemoveClones(const Vector<Element*>& clones)
{
for (auto& clone : clones) {
for (auto& descendant : descendantsOfType<SVGElement>(*clone))
descendant.setCorrespondingElement(nullptr);
clone->parentNode()->removeChild(*clone);
}
}
static void removeDisallowedElementsFromSubtree(SVGElement& subtree)
{
ASSERT(!subtree.inDocument());
Vector<Element*> disallowedElements;
auto descendants = descendantsOfType<Element>(subtree);
for (auto it = descendants.begin(), end = descendants.end(); it != end; ) {
if (isDisallowedElement(*it)) {
disallowedElements.append(&*it);
it.traverseNextSkippingChildren();
continue;
}
++it;
}
disassociateAndRemoveClones(disallowedElements);
}
static void removeSymbolElementsFromSubtree(SVGElement& subtree)
{
Vector<Element*> symbolElements;
for (auto& descendant : descendantsOfType<SVGSymbolElement>(subtree))
symbolElements.append(&descendant);
disassociateAndRemoveClones(symbolElements);
}
static void associateClonesWithOriginals(SVGElement& clone, SVGElement& original)
{
ASSERT(!clone.parentNode());
clone.setCorrespondingElement(&original);
for (auto pair : descendantsOfType<SVGElement>(clone, original))
pair.first.setCorrespondingElement(&pair.second);
}
static void associateReplacementCloneWithOriginal(SVGElement& replacementClone, SVGElement& originalClone)
{
auto* correspondingElement = originalClone.correspondingElement();
ASSERT(correspondingElement);
originalClone.setCorrespondingElement(nullptr);
replacementClone.setCorrespondingElement(correspondingElement);
}
static void associateReplacementClonesWithOriginals(SVGElement& replacementClone, SVGElement& originalClone)
{
ASSERT(!replacementClone.parentNode());
associateReplacementCloneWithOriginal(replacementClone, originalClone);
for (auto pair : descendantsOfType<SVGElement>(replacementClone, originalClone))
associateReplacementCloneWithOriginal(pair.first, pair.second);
}
SVGElement* SVGUseElement::findTarget(String* targetID) const
{
auto* correspondingElement = this->correspondingElement();
auto& original = correspondingElement ? downcast<SVGUseElement>(*correspondingElement) : *this;
auto* targetCandidate = targetElementFromIRIString(original.href(), original.document(), targetID, original.externalDocument());
if (targetID && !targetID->isNull()) {
if (isExternalURIReference(original.href(), original.document()))
*targetID = String();
}
if (!is<SVGElement>(targetCandidate))
return nullptr;
auto& target = downcast<SVGElement>(*targetCandidate);
if (!target.inDocument() || isDisallowedElement(target))
return nullptr;
if (correspondingElement) {
for (auto& ancestor : lineageOfType<SVGElement>(*this)) {
if (ancestor.correspondingElement() == &target)
return nullptr;
}
}
return ⌖
}
void SVGUseElement::cloneTarget(ContainerNode& container, SVGElement& target) const
{
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);
}
static void cloneDataAndChildren(SVGElement& replacementClone, SVGElement& originalClone)
{
ASSERT(!replacementClone.parentNode());
replacementClone.cloneDataFromElement(originalClone);
originalClone.cloneChildNodes(replacementClone);
associateReplacementClonesWithOriginals(replacementClone, originalClone);
removeDisallowedElementsFromSubtree(replacementClone);
}
void SVGUseElement::expandUseElementsInShadowTree() const
{
auto descendants = descendantsOfType<SVGUseElement>(*userAgentShadowRoot());
for (auto it = descendants.begin(), end = descendants.end(); it != end; ) {
SVGUseElement& originalClone = *it;
it = end;
auto* target = originalClone.findTarget();
auto replacementClone = SVGGElement::create(document());
cloneDataAndChildren(replacementClone.get(), originalClone);
replacementClone->removeAttribute(SVGNames::xAttr);
replacementClone->removeAttribute(SVGNames::yAttr);
replacementClone->removeAttribute(SVGNames::widthAttr);
replacementClone->removeAttribute(SVGNames::heightAttr);
replacementClone->removeAttribute(XLinkNames::hrefAttr);
if (target)
originalClone.cloneTarget(replacementClone.get(), *target);
originalClone.parentNode()->replaceChild(replacementClone, originalClone);
it = descendants.from(replacementClone.get());
}
}
void SVGUseElement::expandSymbolElementsInShadowTree() const
{
auto descendants = descendantsOfType<SVGSymbolElement>(*userAgentShadowRoot());
for (auto it = descendants.begin(), end = descendants.end(); it != end; ) {
SVGSymbolElement& originalClone = *it;
it = end;
auto replacementClone = SVGSVGElement::create(document());
cloneDataAndChildren(replacementClone.get(), originalClone);
originalClone.parentNode()->replaceChild(replacementClone, originalClone);
it = descendants.from(replacementClone.get());
}
}
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_shadowTreeNeedsUpdate)
return;
m_shadowTreeNeedsUpdate = true;
setNeedsStyleRecalc(ReconstructRenderTree);
invalidateDependentShadowTrees();
}
void SVGUseElement::invalidateDependentShadowTrees()
{
for (auto* instance : instances()) {
if (auto* element = instance->correspondingUseElement())
element->invalidateShadowTree();
}
}
bool SVGUseElement::selfHasRelativeLengths() const
{
if (x().isRelative() || y().isRelative() || width().isRelative() || height().isRelative())
return true;
auto* targetClone = this->targetClone();
return targetClone && targetClone->hasRelativeLengths();
}
void SVGUseElement::notifyFinished(CachedResource* resource)
{
invalidateShadowTree();
if (resource->errorOccurred())
dispatchEvent(Event::create(eventNames().errorEvent, false, false));
else if (!resource->wasCanceled())
SVGExternalResourcesRequired::dispatchLoadEvent(this);
}
void SVGUseElement::finishParsingChildren()
{
SVGGraphicsElement::finishParsingChildren();
SVGExternalResourcesRequired::finishParsingChildren();
}
void SVGUseElement::updateExternalDocument()
{
URL externalDocumentURL;
if (inDocument() && isExternalURIReference(href(), document())) {
externalDocumentURL = document().completeURL(href());
if (!externalDocumentURL.hasFragmentIdentifier())
externalDocumentURL = URL();
}
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.setContentSecurityPolicyImposition(isInUserAgentShadowTree() ? ContentSecurityPolicyImposition::SkipPolicyCheck : ContentSecurityPolicyImposition::DoPolicyCheck);
CachedResourceRequest request { ResourceRequest { externalDocumentURL }, options };
request.setInitiator(this);
m_externalDocument = document().cachedResourceLoader().requestSVGDocument(request);
if (m_externalDocument)
m_externalDocument->addClient(this);
}
invalidateShadowTree();
}
bool SVGUseElement::isValid() const
{
return SVGTests::isValid();
}
bool SVGUseElement::haveLoadedRequiredResources()
{
return SVGExternalResourcesRequired::haveLoadedRequiredResources();
}
void SVGUseElement::setHaveFiredLoadEvent(bool haveFiredLoadEvent)
{
m_haveFiredLoadEvent = haveFiredLoadEvent;
}
bool SVGUseElement::haveFiredLoadEvent() const
{
return m_haveFiredLoadEvent;
}
Timer* SVGUseElement::svgLoadEventTimer()
{
return &m_svgLoadEventTimer;
}
}