#include "config.h"
#if ENABLE(SVG)
#include "SVGUseElement.h"
#include "CSSStyleSelector.h"
#include "CString.h"
#include "Document.h"
#include "Event.h"
#include "EventListener.h"
#include "HTMLNames.h"
#include "NodeRenderStyle.h"
#include "RegisteredEventListener.h"
#include "RenderSVGTransformableContainer.h"
#include "SVGElementInstance.h"
#include "SVGElementInstanceList.h"
#include "SVGGElement.h"
#include "SVGLength.h"
#include "SVGPreserveAspectRatio.h"
#include "SVGSMILElement.h"
#include "SVGSVGElement.h"
#include "SVGSymbolElement.h"
#include "XLinkNames.h"
#include "XMLSerializer.h"
namespace WebCore {
SVGUseElement::SVGUseElement(const QualifiedName& tagName, Document* doc)
: SVGStyledTransformableElement(tagName, doc)
, SVGTests()
, SVGLangSpace()
, SVGExternalResourcesRequired()
, SVGURIReference()
, m_x(this, SVGNames::xAttr, LengthModeWidth)
, m_y(this, SVGNames::yAttr, LengthModeHeight)
, m_width(this, SVGNames::widthAttr, LengthModeWidth)
, m_height(this, SVGNames::heightAttr, LengthModeHeight)
{
}
SVGUseElement::~SVGUseElement()
{
}
SVGElementInstance* SVGUseElement::instanceRoot() const
{
return m_targetElementInstance.get();
}
SVGElementInstance* SVGUseElement::animatedInstanceRoot() const
{
return 0;
}
void SVGUseElement::parseMappedAttribute(MappedAttribute* attr)
{
if (attr->name() == SVGNames::xAttr)
setXBaseValue(SVGLength(LengthModeWidth, attr->value()));
else if (attr->name() == SVGNames::yAttr)
setYBaseValue(SVGLength(LengthModeHeight, attr->value()));
else if (attr->name() == SVGNames::widthAttr) {
setWidthBaseValue(SVGLength(LengthModeWidth, attr->value()));
if (widthBaseValue().value(this) < 0.0)
document()->accessSVGExtensions()->reportError("A negative value for use attribute <width> is not allowed");
} else if (attr->name() == SVGNames::heightAttr) {
setHeightBaseValue(SVGLength(LengthModeHeight, attr->value()));
if (heightBaseValue().value(this) < 0.0)
document()->accessSVGExtensions()->reportError("A negative value for use attribute <height> is not allowed");
} else {
if (SVGTests::parseMappedAttribute(attr))
return;
if (SVGLangSpace::parseMappedAttribute(attr))
return;
if (SVGExternalResourcesRequired::parseMappedAttribute(attr))
return;
if (SVGURIReference::parseMappedAttribute(attr))
return;
SVGStyledTransformableElement::parseMappedAttribute(attr);
}
}
void SVGUseElement::insertedIntoDocument()
{
SVGElement::insertedIntoDocument();
buildPendingResource();
}
void SVGUseElement::removedFromDocument()
{
m_targetElementInstance = 0;
m_shadowTreeRootElement = 0;
SVGElement::removedFromDocument();
}
void SVGUseElement::svgAttributeChanged(const QualifiedName& attrName)
{
SVGStyledTransformableElement::svgAttributeChanged(attrName);
if (!attached())
return;
if (attrName == SVGNames::xAttr || attrName == SVGNames::yAttr ||
attrName == SVGNames::widthAttr || attrName == SVGNames::heightAttr ||
SVGTests::isKnownAttribute(attrName) ||
SVGLangSpace::isKnownAttribute(attrName) ||
SVGExternalResourcesRequired::isKnownAttribute(attrName) ||
SVGURIReference::isKnownAttribute(attrName) ||
SVGStyledTransformableElement::isKnownAttribute(attrName)) {
buildPendingResource();
if (m_shadowTreeRootElement)
m_shadowTreeRootElement->setChanged();
}
}
void SVGUseElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
{
SVGElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
if (!attached())
return;
buildPendingResource();
if (m_shadowTreeRootElement)
m_shadowTreeRootElement->setChanged();
}
static bool shadowTreeContainsChangedNodes(SVGElementInstance* target)
{
if (target->needsUpdate())
return true;
for (SVGElementInstance* instance = target->firstChild(); instance; instance = instance->nextSibling())
if (shadowTreeContainsChangedNodes(instance))
return true;
return false;
}
void SVGUseElement::recalcStyle(StyleChange change)
{
if (attached() && changed() && shadowTreeContainsChangedNodes(m_targetElementInstance.get())) {
buildPendingResource();
if (m_shadowTreeRootElement)
m_shadowTreeRootElement->setChanged();
}
SVGStyledElement::recalcStyle(change);
if (!m_shadowTreeRootElement || !m_shadowTreeRootElement->attached())
return;
if (change >= Inherit || m_shadowTreeRootElement->changed()) {
RefPtr<RenderStyle> newStyle = document()->styleSelector()->styleForElement(m_shadowTreeRootElement.get());
StyleChange ch = Node::diff(m_shadowTreeRootElement->renderStyle(), newStyle.get());
if (ch == Detach) {
ASSERT(m_shadowTreeRootElement->attached());
m_shadowTreeRootElement->detach();
attachShadowTree();
m_shadowTreeRootElement->setChanged(NoStyleChange);
m_shadowTreeRootElement->setHasChangedChild(false);
return;
}
}
m_shadowTreeRootElement->recalcStyle(change);
}
#ifdef DUMP_INSTANCE_TREE
void dumpInstanceTree(unsigned int& depth, String& text, SVGElementInstance* targetInstance)
{
SVGElement* element = targetInstance->correspondingElement();
ASSERT(element);
String elementId = element->getIDAttribute();
String elementNodeName = element->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, firstChild=%s, correspondingElement=%s (%p), shadowTreeElement=%p, id=%s)\n",
targetInstance, parentNodeName.latin1().data(), firstChildNodeName.latin1().data(), elementNodeName.latin1().data(),
element, targetInstance->shadowTreeElement(), elementId.latin1().data());
for (unsigned int i = 0; i < depth; ++i)
text += " ";
HashSet<SVGElementInstance*> elementInstances = element->instancesForElement();
text += String::format("Corresponding element is associated with %i instance(s):\n", elementInstances.size());
HashSet<SVGElementInstance*>::iterator end = elementInstances.end();
for (HashSet<SVGElementInstance*>::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(Node* element)
{
#if ENABLE(SVG_FOREIGN_OBJECT)
if (element->hasTagName(SVGNames::foreignObjectTag))
return true;
#endif
#if ENABLE(SVG_ANIMATION)
if (SVGSMILElement::isSMILElement(element))
return true;
#endif
return false;
}
static bool subtreeContainsDisallowedElement(Node* start)
{
if (isDisallowedElement(start))
return true;
for (Node* cur = start->firstChild(); cur; cur = cur->nextSibling()) {
if (subtreeContainsDisallowedElement(cur))
return true;
}
return false;
}
void SVGUseElement::buildPendingResource()
{
String id = SVGURIReference::getTarget(href());
Element* targetElement = document()->getElementById(id);
if (!targetElement) {
document()->accessSVGExtensions()->addPendingResource(id, this);
return;
}
Node* parent = parentNode();
while (parent) {
if (parent->isShadowNode())
return;
parent = parent->parentNode();
}
SVGElement* target = 0;
if (targetElement && targetElement->isSVGElement())
target = static_cast<SVGElement*>(targetElement);
if (m_targetElementInstance) {
m_targetElementInstance->forgetWrapper();
m_targetElementInstance = 0;
}
if (!target || target == this) {
m_shadowTreeRootElement = 0;
return;
}
m_targetElementInstance = new SVGElementInstance(this, target);
bool foundProblem = false;
buildInstanceTree(target, m_targetElementInstance.get(), foundProblem);
if (foundProblem) {
m_targetElementInstance = 0;
m_shadowTreeRootElement = 0;
return;
}
ASSERT(m_targetElementInstance);
ASSERT(m_targetElementInstance->correspondingUseElement() == this);
m_shadowTreeRootElement = new SVGGElement(SVGNames::gTag, document());
m_shadowTreeRootElement->setInDocument();
m_shadowTreeRootElement->setShadowParentNode(this);
if (x().value(this) != 0.0 || y().value(this) != 0.0) {
String transformString = String::format("translate(%f, %f)", x().value(this), y().value(this));
m_shadowTreeRootElement->setAttribute(SVGNames::transformAttr, transformString);
}
buildShadowTree(target, m_targetElementInstance.get());
#if ENABLE(SVG) && ENABLE(SVG_USE)
expandUseElementsInShadowTree(m_shadowTreeRootElement.get());
expandSymbolElementsInShadowTree(m_shadowTreeRootElement.get());
#endif
associateInstancesWithShadowTreeElements(m_shadowTreeRootElement->firstChild(), m_targetElementInstance.get());
#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
#ifdef DUMP_SHADOW_TREE
ExceptionCode ec = 0;
PassRefPtr<XMLSerializer> serializer = XMLSerializer::create();
String markup = serializer->serializeToString(m_shadowTreeRootElement.get(), ec);
ASSERT(ec == 0);
fprintf(stderr, "Dumping <use> shadow tree markup:\n%s\n", markup.latin1().data());
#endif
transferEventListenersToShadowTree(m_targetElementInstance.get());
attachShadowTree();
}
RenderObject* SVGUseElement::createRenderer(RenderArena* arena, RenderStyle*)
{
return new (arena) RenderSVGTransformableContainer(this);
}
void SVGUseElement::attach()
{
SVGStyledTransformableElement::attach();
attachShadowTree();
}
void SVGUseElement::detach()
{
SVGStyledTransformableElement::detach();
if (m_shadowTreeRootElement)
m_shadowTreeRootElement->detach();
}
static bool isDirectReference(Node* n)
{
return n->hasTagName(SVGNames::pathTag) ||
n->hasTagName(SVGNames::rectTag) ||
n->hasTagName(SVGNames::circleTag) ||
n->hasTagName(SVGNames::ellipseTag) ||
n->hasTagName(SVGNames::polygonTag) ||
n->hasTagName(SVGNames::polylineTag) ||
n->hasTagName(SVGNames::textTag);
}
Path SVGUseElement::toClipPath() const
{
if (!m_shadowTreeRootElement)
const_cast<SVGUseElement*>(this)->buildPendingResource();
Node* n = m_shadowTreeRootElement->firstChild();
if (n->isSVGElement() && static_cast<SVGElement*>(n)->isStyledTransformable()) {
if (!isDirectReference(n))
document()->accessSVGExtensions()->reportError("Not allowed to use indirect reference in <clip-path>");
else
return static_cast<SVGStyledTransformableElement*>(n)->toClipPath();
}
return Path();
}
void SVGUseElement::buildInstanceTree(SVGElement* target, SVGElementInstance* targetInstance, bool& foundProblem)
{
ASSERT(target);
ASSERT(targetInstance);
for (Node* node = target->firstChild(); node; node = node->nextSibling()) {
SVGElement* element = 0;
if (node->isSVGElement())
element = static_cast<SVGElement*>(node);
if (!element || isDisallowedElement(element))
continue;
SVGElementInstance* instancePtr = new SVGElementInstance(this, element);
targetInstance->appendChild(instancePtr);
if (element->hasChildNodes())
buildInstanceTree(element, instancePtr, foundProblem);
if (element->hasTagName(SVGNames::useTag))
handleDeepUseReferencing(static_cast<SVGUseElement*>(element), instancePtr, foundProblem);
}
if (target->hasTagName(SVGNames::useTag))
handleDeepUseReferencing(static_cast<SVGUseElement*>(target), targetInstance, foundProblem);
}
void SVGUseElement::handleDeepUseReferencing(SVGUseElement* use, SVGElementInstance* targetInstance, bool& foundProblem)
{
String id = SVGURIReference::getTarget(use->href());
Element* targetElement = document()->getElementById(id);
SVGElement* target = 0;
if (targetElement && targetElement->isSVGElement())
target = static_cast<SVGElement*>(targetElement);
if (!target)
return;
foundProblem = (target == this);
if (foundProblem)
return;
SVGElementInstance* instance = targetInstance->parentNode();
while (instance) {
SVGElement* element = instance->correspondingElement();
if (element->getIDAttribute() == id) {
foundProblem = true;
return;
}
instance = instance->parentNode();
}
SVGElementInstance* newInstance = new SVGElementInstance(this, target);
targetInstance->appendChild(newInstance);
buildInstanceTree(target, newInstance, foundProblem);
}
void SVGUseElement::alterShadowTreeForSVGTag(SVGElement* target)
{
String widthString = String::number(width().value(this));
String heightString = String::number(height().value(this));
if (hasAttribute(SVGNames::widthAttr))
target->setAttribute(SVGNames::widthAttr, widthString);
if (hasAttribute(SVGNames::heightAttr))
target->setAttribute(SVGNames::heightAttr, heightString);
}
void SVGUseElement::removeDisallowedElementsFromSubtree(Node* subtree)
{
ASSERT(!subtree->inDocument());
ExceptionCode ec;
Node* node = subtree->firstChild();
while (node) {
if (isDisallowedElement(node)) {
Node* next = node->traverseNextSibling(subtree);
node->parent()->removeChild(node, ec);
node = next;
} else
node = node->traverseNextNode(subtree);
}
}
void SVGUseElement::buildShadowTree(SVGElement* target, SVGElementInstance* targetInstance)
{
if (isDisallowedElement(target))
return;
RefPtr<Node> newChild = targetInstance->correspondingElement()->cloneNode(true);
if (subtreeContainsDisallowedElement(newChild.get()))
removeDisallowedElementsFromSubtree(newChild.get());
SVGElement* newChildPtr = 0;
if (newChild->isSVGElement())
newChildPtr = static_cast<SVGElement*>(newChild.get());
ASSERT(newChildPtr);
ExceptionCode ec = 0;
m_shadowTreeRootElement->appendChild(newChild.release(), ec);
ASSERT(ec == 0);
if (target->hasTagName(SVGNames::svgTag))
alterShadowTreeForSVGTag(newChildPtr);
}
#if ENABLE(SVG) && ENABLE(SVG_USE)
void SVGUseElement::expandUseElementsInShadowTree(Node* element)
{
if (element->hasTagName(SVGNames::useTag)) {
SVGUseElement* use = static_cast<SVGUseElement*>(element);
String id = SVGURIReference::getTarget(use->href());
Element* targetElement = document()->getElementById(id);
SVGElement* target = 0;
if (targetElement && targetElement->isSVGElement())
target = static_cast<SVGElement*>(targetElement);
if (target) {
RefPtr<SVGElement> cloneParent = new SVGGElement(SVGNames::gTag, document());
transferUseAttributesToReplacedElement(use, cloneParent.get());
if (use->x().value(this) != 0.0 || use->y().value(this) != 0.0) {
if (!cloneParent->hasAttribute(SVGNames::transformAttr)) {
String transformString = String::format("translate(%f, %f)", use->x().value(this), use->y().value(this));
cloneParent->setAttribute(SVGNames::transformAttr, transformString);
} else {
String transformString = String::format(" translate(%f, %f)", use->x().value(this), use->y().value(this));
const AtomicString& transformAttribute = cloneParent->getAttribute(SVGNames::transformAttr);
cloneParent->setAttribute(SVGNames::transformAttr, transformAttribute + transformString);
}
}
ExceptionCode ec = 0;
if (isDisallowedElement(target)) {
ASSERT(use->parentNode());
use->parentNode()->replaceChild(cloneParent.release(), use, ec);
ASSERT(ec == 0);
return;
}
RefPtr<Node> newChild = target->cloneNode(true);
if (subtreeContainsDisallowedElement(newChild.get()))
removeDisallowedElementsFromSubtree(newChild.get());
SVGElement* newChildPtr = 0;
if (newChild->isSVGElement())
newChildPtr = static_cast<SVGElement*>(newChild.get());
ASSERT(newChildPtr);
cloneParent->appendChild(newChild.release(), ec);
ASSERT(ec == 0);
ASSERT(use->parentNode());
use->parentNode()->replaceChild(cloneParent.release(), use, ec);
ASSERT(ec == 0);
if (target->hasTagName(SVGNames::svgTag))
alterShadowTreeForSVGTag(newChildPtr);
expandUseElementsInShadowTree(m_shadowTreeRootElement.get());
return;
}
}
for (RefPtr<Node> child = element->firstChild(); child; child = child->nextSibling())
expandUseElementsInShadowTree(child.get());
}
void SVGUseElement::expandSymbolElementsInShadowTree(Node* element)
{
if (element->hasTagName(SVGNames::symbolTag)) {
RefPtr<SVGSVGElement> svgElement = new SVGSVGElement(SVGNames::svgTag, document());
svgElement->attributes()->setAttributes(*element->attributes());
String widthString = String::number(width().value(this));
String heightString = String::number(height().value(this));
svgElement->setAttribute(SVGNames::widthAttr, hasAttribute(SVGNames::widthAttr) ? widthString : "100%");
svgElement->setAttribute(SVGNames::heightAttr, hasAttribute(SVGNames::heightAttr) ? heightString : "100%");
ExceptionCode ec = 0;
for (Node* child = element->firstChild(); child; child = child->nextSibling()) {
RefPtr<Node> newChild = child->cloneNode(true);
svgElement->appendChild(newChild.release(), ec);
ASSERT(ec == 0);
}
if (subtreeContainsDisallowedElement(svgElement.get()))
removeDisallowedElementsFromSubtree(svgElement.get());
ASSERT(element->parentNode());
element->parentNode()->replaceChild(svgElement.release(), element, ec);
ASSERT(ec == 0);
expandSymbolElementsInShadowTree(m_shadowTreeRootElement.get());
return;
}
for (RefPtr<Node> child = element->firstChild(); child; child = child->nextSibling())
expandSymbolElementsInShadowTree(child.get());
}
#endif
void SVGUseElement::attachShadowTree()
{
if (!m_shadowTreeRootElement || m_shadowTreeRootElement->attached() || !document()->shouldCreateRenderers() || !attached() || !renderer())
return;
if (renderer()->canHaveChildren() && childShouldCreateRenderer(m_shadowTreeRootElement.get())) {
RefPtr<RenderStyle> style = m_shadowTreeRootElement->styleForRenderer();
if (m_shadowTreeRootElement->rendererIsNeeded(style.get())) {
m_shadowTreeRootElement->setRenderer(m_shadowTreeRootElement->createRenderer(document()->renderArena(), style.get()));
if (RenderObject* shadowRenderer = m_shadowTreeRootElement->renderer()) {
shadowRenderer->setStyle(style.release());
renderer()->addChild(shadowRenderer, m_shadowTreeRootElement->nextRenderer());
m_shadowTreeRootElement->setAttached();
}
}
for (Node* child = m_shadowTreeRootElement->firstChild(); child; child = child->nextSibling())
child->attach();
}
}
void SVGUseElement::transferEventListenersToShadowTree(SVGElementInstance* target)
{
if (!target)
return;
SVGElement* originalElement = target->correspondingElement();
ASSERT(originalElement);
if (SVGElement* shadowTreeElement = target->shadowTreeElement()) {
const RegisteredEventListenerVector& listeners = originalElement->eventListeners();
size_t size = listeners.size();
for (size_t i = 0; i < size; ++i) {
const RegisteredEventListener& r = *listeners[i];
EventListener* listener = r.listener();
ASSERT(listener);
if (listener->wasCreatedFromMarkup())
continue;
shadowTreeElement->addEventListener(r.eventType(), listener, r.useCapture());
}
}
for (SVGElementInstance* instance = target->firstChild(); instance; instance = instance->nextSibling())
transferEventListenersToShadowTree(instance);
}
void SVGUseElement::associateInstancesWithShadowTreeElements(Node* target, SVGElementInstance* targetInstance)
{
if (!target || !targetInstance)
return;
SVGElement* originalElement = targetInstance->correspondingElement();
if (originalElement->hasTagName(SVGNames::useTag)) {
#if ENABLE(SVG) && ENABLE(SVG_USE)
ASSERT(target->nodeName() == SVGNames::gTag);
#else
ASSERT(target->nodeName() == SVGNames::gTag || target->nodeName() == SVGNames::useTag);
#endif
} else if (originalElement->hasTagName(SVGNames::symbolTag)) {
#if ENABLE(SVG) && ENABLE(SVG_USE) && ENABLE(SVG_FOREIGN_OBJECT)
ASSERT(target->nodeName() == SVGNames::svgTag);
#endif
} else
ASSERT(target->nodeName() == originalElement->nodeName());
SVGElement* element = 0;
if (target->isSVGElement())
element = static_cast<SVGElement*>(target);
ASSERT(!targetInstance->shadowTreeElement());
targetInstance->setShadowTreeElement(element);
Node* node = target->firstChild();
for (SVGElementInstance* instance = targetInstance->firstChild(); node && instance; instance = instance->nextSibling()) {
while (node && !node->isSVGElement())
node = node->nextSibling();
associateInstancesWithShadowTreeElements(node, instance);
node = node->nextSibling();
}
}
SVGElementInstance* SVGUseElement::instanceForShadowTreeElement(Node* element) const
{
return instanceForShadowTreeElement(element, m_targetElementInstance.get());
}
SVGElementInstance* SVGUseElement::instanceForShadowTreeElement(Node* element, SVGElementInstance* instance) const
{
ASSERT(element);
ASSERT(instance);
ASSERT(instance->shadowTreeElement());
if (element == instance->shadowTreeElement())
return instance;
for (SVGElementInstance* current = instance->firstChild(); current; current = current->nextSibling()) {
SVGElementInstance* search = instanceForShadowTreeElement(element, current);
if (search)
return search;
}
return 0;
}
void SVGUseElement::transferUseAttributesToReplacedElement(SVGElement* from, SVGElement* to) const
{
ASSERT(from);
ASSERT(to);
to->attributes()->setAttributes(*from->attributes());
ExceptionCode ec = 0;
to->removeAttribute(SVGNames::xAttr, ec);
ASSERT(ec == 0);
to->removeAttribute(SVGNames::yAttr, ec);
ASSERT(ec == 0);
to->removeAttribute(SVGNames::widthAttr, ec);
ASSERT(ec == 0);
to->removeAttribute(SVGNames::heightAttr, ec);
ASSERT(ec == 0);
to->removeAttribute(XLinkNames::hrefAttr, ec);
ASSERT(ec == 0);
}
}
#endif // ENABLE(SVG)