<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Id$
 */

#include "DeepNodeListImpl.hpp"
#include "DocumentImpl.hpp"
#include "DocumentTypeImpl.hpp"
#include "DOM_DOMException.hpp"
#include "DStringPool.hpp"
#include "ElementImpl.hpp"
#include "ElementDefinitionImpl.hpp"
#include "NamedNodeMapImpl.hpp"
#include "NodeVector.hpp"

ElementImpl::ElementImpl(DocumentImpl *ownerDoc, const DOMString &eName)
    : ChildAndParentNode(ownerDoc)
{
    name = eName.clone();
    attributes = null;
	setupDefaultAttributes();
};

ElementImpl::ElementImpl(const ElementImpl &other, bool deep)
    : ChildAndParentNode(other)
{
    name = other.name.clone();
	attributes = null;
	setupDefaultAttributes();
    if (deep)
        cloneChildren(other);
	if (other.attributes != null)
		attributes = other.attributes->cloneAttrMap(this);
};

ElementImpl::~ElementImpl()
{
    if (attributes)
    {
        attributes->removeAll();
        NamedNodeMapImpl::removeRef(attributes);
    }
};

NodeImpl *ElementImpl::cloneNode(bool deep)
{
    return new ElementImpl(*this, deep);
};

/**
 * NON-DOM
 * set the ownerDocument of this node, its children, and its attributes
 */
void ElementImpl::setOwnerDocument(DocumentImpl *doc) {
    ChildAndParentNode::setOwnerDocument(doc);
	if (attributes != null)
		attributes->setOwnerDocument(doc);
}

DOMString ElementImpl::getNodeName() {
    return name;
};

short ElementImpl::getNodeType() {
    return DOM_Node::ELEMENT_NODE;
};

DOMString ElementImpl::getAttribute(const DOMString &nam)
{
    static DOMString *emptyString = 0;
    AttrImpl * attr=null;

    if (attributes != null)
	attr=(AttrImpl *)(attributes->getNamedItem(nam));

    return (attr==null) ? DStringPool::getStaticString("", &emptyString) : attr->getValue();
};

AttrImpl *ElementImpl::getAttributeNode(const DOMString &nam)
{
    return (attributes == 0) ? null : (AttrImpl *)(attributes->getNamedItem(nam));
};

NamedNodeMapImpl *ElementImpl::getAttributes()
{
    return attributes;
};

DeepNodeListImpl *ElementImpl::getElementsByTagName(const DOMString &tagname)
{
    return new DeepNodeListImpl(this,tagname);
};

DOMString ElementImpl::getTagName()
{
    return name;
}

bool ElementImpl::isElementImpl()
{
    return true;
};

void ElementImpl::removeAttribute(const DOMString &nam)
{
    if (isReadOnly())
        throw DOM_DOMException(
        DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null);

    if (attributes != null)
    {
    	AttrImpl *att = (AttrImpl *) attributes->getNamedItem(nam);
    	// Remove it
    	if (att != null)
    	{
    	    attributes->removeNamedItem(nam);
    	    if (att->nodeRefCount == 0)
    	        NodeImpl::deleteIf(att);
    	}
    }
};

AttrImpl *ElementImpl::removeAttributeNode(AttrImpl *oldAttr)
{
    if (isReadOnly())
        throw DOM_DOMException(
        DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null);

    if (attributes != null)
    {
	    AttrImpl *found = (AttrImpl *) attributes->getNamedItem(oldAttr->getName());

	    // If it is in fact the right object, remove it.

	    if (found == oldAttr)
	        attributes->removeNamedItem(oldAttr->getName());
	    else
	        throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR, null);

        return found;

	}
	return null;	// just to keep the compiler happy
};

AttrImpl *ElementImpl::setAttribute(const DOMString &nam, const DOMString &val)
{
    if (isReadOnly())
        throw DOM_DOMException(
        DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null);

    AttrImpl* newAttr = (AttrImpl*)getAttributeNode(nam);
    if (!newAttr)
    {
		if (attributes == 0)
			attributes = new AttrMapImpl(this, null);
        newAttr = (AttrImpl*)ownerDocument->createAttribute(nam);
        attributes->setNamedItem(newAttr);
    }

    newAttr->setNodeValue(val);       // Note that setNodeValue on attribute
                                      //   nodes takes care of deleting
                                      //   any previously existing children.
    return newAttr;
};

AttrImpl * ElementImpl::setAttributeNode(AttrImpl *newAttr)
{
    if (isReadOnly())
        throw DOM_DOMException(
        DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null);

    if (!(newAttr->isAttrImpl()))
        throw DOM_DOMException(DOM_DOMException::WRONG_DOCUMENT_ERR, null);
	if (attributes == 0)
		attributes = new AttrMapImpl(this, null);
    AttrImpl *oldAttr =
      (AttrImpl *) attributes->getNamedItem(newAttr->getName());
    // This will throw INUSE if necessary
    attributes->setNamedItem(newAttr);

    // Attr node reference counting note:
    // If oldAttr's refcount is zero at this point, here's what happens...
    //
    //      oldAttr is returned from this function to DOM_Attr::setAttributeNode,
    //      which wraps a DOM_Attr around the returned pointer and sends it
    //      up to application code, incrementing the reference count in the process.
    //      When the app DOM_Attr's destructor runs, the reference count is
    //      decremented back to zero and oldAttr will be deleted at that time.

    return oldAttr;
};

void ElementImpl::setNodeValue(const DOMString &x)
{
    throw DOM_DOMException(DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null);
};

void ElementImpl::setReadOnly(bool readOnl, bool deep)
{
    ChildAndParentNode::setReadOnly(readOnl,deep);
    attributes->setReadOnly(readOnl,true);
};

//Introduced in DOM Level 2
DOMString ElementImpl::getAttributeNS(const DOMString &fNamespaceURI,
	const DOMString &fLocalName)
{
    AttrImpl * attr=
      (AttrImpl *)(attributes->getNamedItemNS(fNamespaceURI, fLocalName));
    return (attr==null) ? DOMString(null) : attr->getValue();
}

AttrImpl *ElementImpl::setAttributeNS(const DOMString &fNamespaceURI,
	const DOMString &qualifiedName, const DOMString &fValue)
{
    if (isReadOnly())
        throw DOM_DOMException(
	    DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null);

    AttrImpl *newAttr =
      (AttrImpl *) ownerDocument->createAttributeNS(fNamespaceURI,
                                                    qualifiedName);
    newAttr->setNodeValue(fValue);
	if (attributes == 0)
		attributes = new AttrMapImpl(this, null);
    AttrImpl *oldAttr = (AttrImpl *)attributes->setNamedItem(newAttr);

    if (oldAttr) {
	if (oldAttr->nodeRefCount == 0)
	    NodeImpl::deleteIf(oldAttr);
    }
    return newAttr;
}

void ElementImpl::removeAttributeNS(const DOMString &fNamespaceURI,
	const DOMString &fLocalName)
{
    if (isReadOnly())
        throw DOM_DOMException(
	    DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null);

    if (attributes != null)
    {
		AttrImpl *att =
		  (AttrImpl *) attributes->getNamedItemNS(fNamespaceURI, fLocalName);
		// Remove it
		if (att != null) {
			attributes->removeNamedItemNS(fNamespaceURI, fLocalName);
			if (att->nodeRefCount == 0)
				NodeImpl::deleteIf(att);
		}
	}
}

AttrImpl *ElementImpl::getAttributeNodeNS(const DOMString &fNamespaceURI,
	const DOMString &fLocalName)
{
    return (attributes == 0) ? null : (AttrImpl *)(attributes->getNamedItemNS(fNamespaceURI, fLocalName));
}

AttrImpl *ElementImpl::setAttributeNodeNS(AttrImpl *newAttr)
{
    if (isReadOnly())
        throw DOM_DOMException(
	    DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null);

    if (newAttr -> getOwnerDocument() != this -> getOwnerDocument())
        throw DOM_DOMException(DOM_DOMException::WRONG_DOCUMENT_ERR, null);
	if (attributes == 0)
		attributes = new AttrMapImpl(this, null);
    AttrImpl *oldAttr = (AttrImpl *) attributes->getNamedItemNS(newAttr->getNamespaceURI(), newAttr->getLocalName());

    // This will throw INUSE if necessary
    attributes->setNamedItemNS(newAttr);

    // Attr node reference counting note:
    // If oldAttr's refcount is zero at this point, here's what happens...
    //
    //      oldAttr is returned from this function to DOM_Attr::setAttributeNode,
    //      which wraps a DOM_Attr around the returned pointer and sends it
    //      up to application code, incrementing the reference count in the process.
    //      When the app DOM_Attr's destructor runs, the reference count is
    //      decremented back to zero and oldAttr will be deleted at that time.

    return oldAttr;
}

DeepNodeListImpl *ElementImpl::getElementsByTagNameNS(const DOMString &fNamespaceURI,
	const DOMString &fLocalName)
{
    return new DeepNodeListImpl(this,fNamespaceURI, fLocalName);
}

// DOM_NamedNodeMap UTILITIES
NamedNodeMapImpl *ElementImpl::NNM_cloneMap(NodeImpl *nnm_ownerNode)
{
	return (getAttributes() == null) ? null : nnm_ownerNode->getAttributes()->cloneMap(nnm_ownerNode);
}

int ElementImpl::NNM_findNamePoint(const DOMString &nnm_name)
{
	return (getAttributes() == null) ? -1 : getAttributes()->findNamePoint(nnm_name);
}

unsigned int ElementImpl::NNM_getLength()
{
	return (getAttributes() == null) ? 0 : getAttributes()->getLength();
}

NodeImpl *ElementImpl::NNM_getNamedItem(const DOMString &nnm_name)
{
	return (getAttributes() == null) ? null : getAttributes()->getNamedItem(nnm_name);
}

NodeImpl *ElementImpl::NNM_item(unsigned int nnm_index)
{
	return (getAttributes() == null) ? null : getAttributes()->item(nnm_index);
}

void ElementImpl::NNM_removeAll()
{
	if (getAttributes() != null)
		getAttributes()->removeAll();
}

NodeImpl *ElementImpl::NNM_removeNamedItem(const DOMString &nnm_name)
{
	if (getAttributes() == null)
		throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR, null);
	else
		return getAttributes()->removeNamedItem(nnm_name);
	return null;
}

NodeImpl *ElementImpl::NNM_setNamedItem(NodeImpl *nnm_arg)
{
	if (getAttributes() == null)
		attributes = new AttrMapImpl(this);
	return attributes->setNamedItem(nnm_arg);
}

void ElementImpl::NNM_setReadOnly(bool nnm_readOnly, bool nnm_deep)
{
	if (getAttributes() != null)
		getAttributes()->setReadOnly(nnm_readOnly, nnm_deep);
}

int ElementImpl::NNM_findNamePoint(const DOMString &nnm_namespaceURI, const DOMString &nnm_localName)
{
	return (getAttributes() == null) ? -1 : getAttributes()->findNamePoint(nnm_namespaceURI, nnm_localName);
}

NodeImpl *ElementImpl::NNM_getNamedItemNS(const DOMString &nnm_namespaceURI, const DOMString &nnm_localName)
{
	return (getAttributes() == null) ? null : getAttributes()->getNamedItemNS(nnm_namespaceURI, nnm_localName);
}

NodeImpl *ElementImpl::NNM_setNamedItemNS(NodeImpl *nnm_arg)
{
	if (getAttributes() == null)
		attributes = new AttrMapImpl(this);
	return getAttributes()->setNamedItemNS(nnm_arg);
}

NodeImpl *ElementImpl::NNM_removeNamedItemNS(const DOMString &nnm_namespaceURI, const DOMString &nnm_localName)
{
	if (getAttributes() == null)
        throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR, null);
	else
		return getAttributes()->removeNamedItemNS(nnm_namespaceURI, nnm_localName);
	return null;
}

void ElementImpl::NNM_setOwnerDocument(DocumentImpl *nnm_doc)
{
	if (getAttributes() != null)
		getAttributes()->setOwnerDocument(nnm_doc);
}

// util functions for default attributes
// returns the default attribute map for this node from the owner document
AttrMapImpl *ElementImpl::getDefaultAttributes()
{
	if ((ownerNode == null) || (getOwnerDocument() == null))
		return null;

	DocumentImpl *tmpdoc = getOwnerDocument();
	if (tmpdoc->getDoctype() == null)
		return null;

	NodeImpl *eldef = tmpdoc->getDoctype()->getElements()->getNamedItem(getNodeName());
	return (eldef == null) ? null : (AttrMapImpl *)(eldef->getAttributes());
}

// resets all attributes for this node to their default values
void ElementImpl::setupDefaultAttributes()
{
	if ((ownerNode == null) || (getOwnerDocument() == null) || (getOwnerDocument()->getDoctype() == null))
		return;

	if (attributes != 0)
		delete attributes;

	AttrMapImpl* defAttrs = getDefaultAttributes();
	if (defAttrs)
		attributes = new AttrMapImpl(this, defAttrs);
}
<commit_msg>ElementImpl::getAttributeNS should check null pointer.  Fixed by Volker Krause.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Id$
 */

#include "DeepNodeListImpl.hpp"
#include "DocumentImpl.hpp"
#include "DocumentTypeImpl.hpp"
#include "DOM_DOMException.hpp"
#include "DStringPool.hpp"
#include "ElementImpl.hpp"
#include "ElementDefinitionImpl.hpp"
#include "NamedNodeMapImpl.hpp"
#include "NodeVector.hpp"

ElementImpl::ElementImpl(DocumentImpl *ownerDoc, const DOMString &eName)
    : ChildAndParentNode(ownerDoc)
{
    name = eName.clone();
    attributes = null;
	setupDefaultAttributes();
};

ElementImpl::ElementImpl(const ElementImpl &other, bool deep)
    : ChildAndParentNode(other)
{
    name = other.name.clone();
	attributes = null;
	setupDefaultAttributes();
    if (deep)
        cloneChildren(other);
	if (other.attributes != null)
		attributes = other.attributes->cloneAttrMap(this);
};

ElementImpl::~ElementImpl()
{
    if (attributes)
    {
        attributes->removeAll();
        NamedNodeMapImpl::removeRef(attributes);
    }
};

NodeImpl *ElementImpl::cloneNode(bool deep)
{
    return new ElementImpl(*this, deep);
};

/**
 * NON-DOM
 * set the ownerDocument of this node, its children, and its attributes
 */
void ElementImpl::setOwnerDocument(DocumentImpl *doc) {
    ChildAndParentNode::setOwnerDocument(doc);
	if (attributes != null)
		attributes->setOwnerDocument(doc);
}

DOMString ElementImpl::getNodeName() {
    return name;
};

short ElementImpl::getNodeType() {
    return DOM_Node::ELEMENT_NODE;
};

DOMString ElementImpl::getAttribute(const DOMString &nam)
{
    static DOMString *emptyString = 0;
    AttrImpl * attr=null;

    if (attributes != null)
	attr=(AttrImpl *)(attributes->getNamedItem(nam));

    return (attr==null) ? DStringPool::getStaticString("", &emptyString) : attr->getValue();
};

AttrImpl *ElementImpl::getAttributeNode(const DOMString &nam)
{
    return (attributes == 0) ? null : (AttrImpl *)(attributes->getNamedItem(nam));
};

NamedNodeMapImpl *ElementImpl::getAttributes()
{
    return attributes;
};

DeepNodeListImpl *ElementImpl::getElementsByTagName(const DOMString &tagname)
{
    return new DeepNodeListImpl(this,tagname);
};

DOMString ElementImpl::getTagName()
{
    return name;
}

bool ElementImpl::isElementImpl()
{
    return true;
};

void ElementImpl::removeAttribute(const DOMString &nam)
{
    if (isReadOnly())
        throw DOM_DOMException(
        DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null);

    if (attributes != null)
    {
    	AttrImpl *att = (AttrImpl *) attributes->getNamedItem(nam);
    	// Remove it
    	if (att != null)
    	{
    	    attributes->removeNamedItem(nam);
    	    if (att->nodeRefCount == 0)
    	        NodeImpl::deleteIf(att);
    	}
    }
};

AttrImpl *ElementImpl::removeAttributeNode(AttrImpl *oldAttr)
{
    if (isReadOnly())
        throw DOM_DOMException(
        DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null);

    if (attributes != null)
    {
	    AttrImpl *found = (AttrImpl *) attributes->getNamedItem(oldAttr->getName());

	    // If it is in fact the right object, remove it.

	    if (found == oldAttr)
	        attributes->removeNamedItem(oldAttr->getName());
	    else
	        throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR, null);

        return found;

	}
	return null;	// just to keep the compiler happy
};

AttrImpl *ElementImpl::setAttribute(const DOMString &nam, const DOMString &val)
{
    if (isReadOnly())
        throw DOM_DOMException(
        DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null);

    AttrImpl* newAttr = (AttrImpl*)getAttributeNode(nam);
    if (!newAttr)
    {
		if (attributes == 0)
			attributes = new AttrMapImpl(this, null);
        newAttr = (AttrImpl*)ownerDocument->createAttribute(nam);
        attributes->setNamedItem(newAttr);
    }

    newAttr->setNodeValue(val);       // Note that setNodeValue on attribute
                                      //   nodes takes care of deleting
                                      //   any previously existing children.
    return newAttr;
};

AttrImpl * ElementImpl::setAttributeNode(AttrImpl *newAttr)
{
    if (isReadOnly())
        throw DOM_DOMException(
        DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null);

    if (!(newAttr->isAttrImpl()))
        throw DOM_DOMException(DOM_DOMException::WRONG_DOCUMENT_ERR, null);
	if (attributes == 0)
		attributes = new AttrMapImpl(this, null);
    AttrImpl *oldAttr =
      (AttrImpl *) attributes->getNamedItem(newAttr->getName());
    // This will throw INUSE if necessary
    attributes->setNamedItem(newAttr);

    // Attr node reference counting note:
    // If oldAttr's refcount is zero at this point, here's what happens...
    //
    //      oldAttr is returned from this function to DOM_Attr::setAttributeNode,
    //      which wraps a DOM_Attr around the returned pointer and sends it
    //      up to application code, incrementing the reference count in the process.
    //      When the app DOM_Attr's destructor runs, the reference count is
    //      decremented back to zero and oldAttr will be deleted at that time.

    return oldAttr;
};

void ElementImpl::setNodeValue(const DOMString &x)
{
    throw DOM_DOMException(DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null);
};

void ElementImpl::setReadOnly(bool readOnl, bool deep)
{
    ChildAndParentNode::setReadOnly(readOnl,deep);
    attributes->setReadOnly(readOnl,true);
};

//Introduced in DOM Level 2
DOMString ElementImpl::getAttributeNS(const DOMString &fNamespaceURI,
	const DOMString &fLocalName)
{
    AttrImpl * attr= (attributes != null) ?
      (AttrImpl *)(attributes->getNamedItemNS(fNamespaceURI, fLocalName))
    : null;
    return (attr==null) ? DOMString(null) : attr->getValue();
}

AttrImpl *ElementImpl::setAttributeNS(const DOMString &fNamespaceURI,
	const DOMString &qualifiedName, const DOMString &fValue)
{
    if (isReadOnly())
        throw DOM_DOMException(
	    DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null);

    AttrImpl *newAttr =
      (AttrImpl *) ownerDocument->createAttributeNS(fNamespaceURI,
                                                    qualifiedName);
    newAttr->setNodeValue(fValue);
	if (attributes == 0)
		attributes = new AttrMapImpl(this, null);
    AttrImpl *oldAttr = (AttrImpl *)attributes->setNamedItem(newAttr);

    if (oldAttr) {
	if (oldAttr->nodeRefCount == 0)
	    NodeImpl::deleteIf(oldAttr);
    }
    return newAttr;
}

void ElementImpl::removeAttributeNS(const DOMString &fNamespaceURI,
	const DOMString &fLocalName)
{
    if (isReadOnly())
        throw DOM_DOMException(
	    DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null);

    if (attributes != null)
    {
		AttrImpl *att =
		  (AttrImpl *) attributes->getNamedItemNS(fNamespaceURI, fLocalName);
		// Remove it
		if (att != null) {
			attributes->removeNamedItemNS(fNamespaceURI, fLocalName);
			if (att->nodeRefCount == 0)
				NodeImpl::deleteIf(att);
		}
	}
}

AttrImpl *ElementImpl::getAttributeNodeNS(const DOMString &fNamespaceURI,
	const DOMString &fLocalName)
{
    return (attributes == 0) ? null : (AttrImpl *)(attributes->getNamedItemNS(fNamespaceURI, fLocalName));
}

AttrImpl *ElementImpl::setAttributeNodeNS(AttrImpl *newAttr)
{
    if (isReadOnly())
        throw DOM_DOMException(
	    DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null);

    if (newAttr -> getOwnerDocument() != this -> getOwnerDocument())
        throw DOM_DOMException(DOM_DOMException::WRONG_DOCUMENT_ERR, null);
	if (attributes == 0)
		attributes = new AttrMapImpl(this, null);
    AttrImpl *oldAttr = (AttrImpl *) attributes->getNamedItemNS(newAttr->getNamespaceURI(), newAttr->getLocalName());

    // This will throw INUSE if necessary
    attributes->setNamedItemNS(newAttr);

    // Attr node reference counting note:
    // If oldAttr's refcount is zero at this point, here's what happens...
    //
    //      oldAttr is returned from this function to DOM_Attr::setAttributeNode,
    //      which wraps a DOM_Attr around the returned pointer and sends it
    //      up to application code, incrementing the reference count in the process.
    //      When the app DOM_Attr's destructor runs, the reference count is
    //      decremented back to zero and oldAttr will be deleted at that time.

    return oldAttr;
}

DeepNodeListImpl *ElementImpl::getElementsByTagNameNS(const DOMString &fNamespaceURI,
	const DOMString &fLocalName)
{
    return new DeepNodeListImpl(this,fNamespaceURI, fLocalName);
}

// DOM_NamedNodeMap UTILITIES
NamedNodeMapImpl *ElementImpl::NNM_cloneMap(NodeImpl *nnm_ownerNode)
{
	return (getAttributes() == null) ? null : nnm_ownerNode->getAttributes()->cloneMap(nnm_ownerNode);
}

int ElementImpl::NNM_findNamePoint(const DOMString &nnm_name)
{
	return (getAttributes() == null) ? -1 : getAttributes()->findNamePoint(nnm_name);
}

unsigned int ElementImpl::NNM_getLength()
{
	return (getAttributes() == null) ? 0 : getAttributes()->getLength();
}

NodeImpl *ElementImpl::NNM_getNamedItem(const DOMString &nnm_name)
{
	return (getAttributes() == null) ? null : getAttributes()->getNamedItem(nnm_name);
}

NodeImpl *ElementImpl::NNM_item(unsigned int nnm_index)
{
	return (getAttributes() == null) ? null : getAttributes()->item(nnm_index);
}

void ElementImpl::NNM_removeAll()
{
	if (getAttributes() != null)
		getAttributes()->removeAll();
}

NodeImpl *ElementImpl::NNM_removeNamedItem(const DOMString &nnm_name)
{
	if (getAttributes() == null)
		throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR, null);
	else
		return getAttributes()->removeNamedItem(nnm_name);
	return null;
}

NodeImpl *ElementImpl::NNM_setNamedItem(NodeImpl *nnm_arg)
{
	if (getAttributes() == null)
		attributes = new AttrMapImpl(this);
	return attributes->setNamedItem(nnm_arg);
}

void ElementImpl::NNM_setReadOnly(bool nnm_readOnly, bool nnm_deep)
{
	if (getAttributes() != null)
		getAttributes()->setReadOnly(nnm_readOnly, nnm_deep);
}

int ElementImpl::NNM_findNamePoint(const DOMString &nnm_namespaceURI, const DOMString &nnm_localName)
{
	return (getAttributes() == null) ? -1 : getAttributes()->findNamePoint(nnm_namespaceURI, nnm_localName);
}

NodeImpl *ElementImpl::NNM_getNamedItemNS(const DOMString &nnm_namespaceURI, const DOMString &nnm_localName)
{
	return (getAttributes() == null) ? null : getAttributes()->getNamedItemNS(nnm_namespaceURI, nnm_localName);
}

NodeImpl *ElementImpl::NNM_setNamedItemNS(NodeImpl *nnm_arg)
{
	if (getAttributes() == null)
		attributes = new AttrMapImpl(this);
	return getAttributes()->setNamedItemNS(nnm_arg);
}

NodeImpl *ElementImpl::NNM_removeNamedItemNS(const DOMString &nnm_namespaceURI, const DOMString &nnm_localName)
{
	if (getAttributes() == null)
        throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR, null);
	else
		return getAttributes()->removeNamedItemNS(nnm_namespaceURI, nnm_localName);
	return null;
}

void ElementImpl::NNM_setOwnerDocument(DocumentImpl *nnm_doc)
{
	if (getAttributes() != null)
		getAttributes()->setOwnerDocument(nnm_doc);
}

// util functions for default attributes
// returns the default attribute map for this node from the owner document
AttrMapImpl *ElementImpl::getDefaultAttributes()
{
	if ((ownerNode == null) || (getOwnerDocument() == null))
		return null;

	DocumentImpl *tmpdoc = getOwnerDocument();
	if (tmpdoc->getDoctype() == null)
		return null;

	NodeImpl *eldef = tmpdoc->getDoctype()->getElements()->getNamedItem(getNodeName());
	return (eldef == null) ? null : (AttrMapImpl *)(eldef->getAttributes());
}

// resets all attributes for this node to their default values
void ElementImpl::setupDefaultAttributes()
{
	if ((ownerNode == null) || (getOwnerDocument() == null) || (getOwnerDocument()->getDoctype() == null))
		return;

	if (attributes != 0)
		delete attributes;

	AttrMapImpl* defAttrs = getDefaultAttributes();
	if (defAttrs)
		attributes = new AttrMapImpl(this, defAttrs);
}
<|endoftext|>


<commit_before>// Context.cpp (Oclgrind)
// Copyright (c) 2013-2015, James Price and Simon McIntosh-Smith,
// University of Bristol. All rights reserved.
//
// This program is provided under a three-clause BSD license. For full
// license terms please see the LICENSE file distributed with this
// source code.

#include "common.h"

#if defined(_WIN32) && !defined(__MINGW32__)
#include <windows.h>
#undef ERROR
#else
#include <dlfcn.h>
#endif

#include "llvm/DebugInfo.h"
#include "llvm/Instruction.h"

#include "Context.h"
#include "Kernel.h"
#include "KernelInvocation.h"
#include "Memory.h"
#include "Program.h"
#include "WorkGroup.h"
#include "WorkItem.h"

#include "plugins/InstructionCounter.h"
#include "plugins/InteractiveDebugger.h"
#include "plugins/Logger.h"
#include "plugins/MemCheck.h"
#include "plugins/RaceDetector.h"

using namespace oclgrind;
using namespace std;

Context::Context()
{
  m_globalMemory = new Memory(AddrSpaceGlobal, this);
  m_kernelInvocation = NULL;

  loadPlugins();
}

Context::~Context()
{
  delete m_globalMemory;

  unloadPlugins();
}

bool Context::isThreadSafe() const
{
  for (const PluginEntry &p : m_plugins)
  {
    if (!p.first->isThreadSafe())
      return false;
  }
  return true;
}

Memory* Context::getGlobalMemory() const
{
  return m_globalMemory;
}

void Context::loadPlugins()
{
  // Create core plugins
  m_plugins.push_back(make_pair(new Logger(this), true));
  m_plugins.push_back(make_pair(new MemCheck(this), true));

  if (checkEnv("OCLGRIND_INST_COUNTS"))
    m_plugins.push_back(make_pair(new InstructionCounter(this), true));

  if (checkEnv("OCLGRIND_DATA_RACES"))
    m_plugins.push_back(make_pair(new RaceDetector(this), true));

  if (checkEnv("OCLGRIND_INTERACTIVE"))
    m_plugins.push_back(make_pair(new InteractiveDebugger(this), true));

  // Load dynamic plugins
  const char *dynamicPlugins = getenv("OCLGRIND_PLUGINS");
  if (dynamicPlugins)
  {
    std::istringstream ss(dynamicPlugins);
    std::string libpath;
    while(std::getline(ss, libpath, ':'))
    {
#if defined(_WIN32) && !defined(__MINGW32__)
      HMODULE library = LoadLibrary(libpath.c_str());
      if (!library)
      {
        cerr << "Loading Oclgrind plugin failed (LoadLibrary): "
             << GetLastError() << endl;
        continue;
      }

      void *initialize = GetProcAddress(library, "initializePlugins");
      if (!initialize)
      {
        cerr << "Loading Oclgrind plugin failed (GetProcAddress): "
             << GetLastError() << endl;
        continue;
      }
#else
      void *library = dlopen(libpath.c_str(), RTLD_NOW);
      if (!library)
      {
        cerr << "Loading Oclgrind plugin failed (dlopen): "
             << dlerror() << endl;
        continue;
      }

      void *initialize = dlsym(library, "initializePlugins");
      if (!initialize)
      {
        cerr << "Loading Oclgrind plugin failed (dlsym): "
             << dlerror() << endl;
        continue;
      }
#endif

      ((void(*)(Context*))initialize)(this);
      m_pluginLibraries.push_back(library);
    }
  }
}

void Context::unloadPlugins()
{
  // Release dynamic plugin libraries
  list<void*>::iterator plibItr;
  for (plibItr = m_pluginLibraries.begin();
       plibItr != m_pluginLibraries.end(); plibItr++)
  {
#if defined(_WIN32) && !defined(__MINGW32__)
      void *release = GetProcAddress((HMODULE)*plibItr, "releasePlugins");
      if (release)
      {
        ((void(*)(Context*))release)(this);
      }
      FreeLibrary((HMODULE)*plibItr);
#else
      void *release = dlsym(*plibItr, "releasePlugins");
      if (release)
      {
        ((void(*)(Context*))release)(this);
      }
      dlclose(*plibItr);
#endif
  }

  // Destroy internal plugins
  PluginList::iterator pItr;
  for (pItr = m_plugins.begin(); pItr != m_plugins.end(); pItr++)
  {
    if (pItr->second)
      delete pItr->first;
  }

  m_plugins.clear();
}

void Context::registerPlugin(Plugin *plugin)
{
  m_plugins.push_back(make_pair(plugin, false));
}

void Context::unregisterPlugin(Plugin *plugin)
{
  m_plugins.remove(make_pair(plugin, false));
}

void Context::logError(const char* error) const
{
  Message msg(ERROR, this);
  msg << error << endl
      << msg.INDENT
      << "Kernel: " << msg.CURRENT_KERNEL << endl
      << "Entity: " << msg.CURRENT_ENTITY << endl
      << msg.CURRENT_LOCATION << endl;
  msg.send();
}

#define NOTIFY(function, ...)                     \
{                                                 \
  PluginList::const_iterator pluginItr;           \
  for (pluginItr = m_plugins.begin();             \
       pluginItr != m_plugins.end(); pluginItr++) \
  {                                               \
    pluginItr->first->function(__VA_ARGS__);      \
  }                                               \
}

void Context::notifyInstructionExecuted(const WorkItem *workItem,
                                        const llvm::Instruction *instruction,
                                        const TypedValue& result) const
{
  NOTIFY(instructionExecuted, workItem, instruction, result);
}

void Context::notifyKernelBegin(const KernelInvocation *kernelInvocation) const
{
  assert(m_kernelInvocation == NULL);
  m_kernelInvocation = kernelInvocation;

  NOTIFY(kernelBegin, kernelInvocation);
}

void Context::notifyKernelEnd(const KernelInvocation *kernelInvocation) const
{
  NOTIFY(kernelEnd, kernelInvocation);

  assert(m_kernelInvocation == kernelInvocation);
  m_kernelInvocation = NULL;
}

void Context::notifyMemoryAllocated(const Memory *memory, size_t address,
                                    size_t size, cl_mem_flags flags) const
{
  NOTIFY(memoryAllocated, memory, address, size, flags);
}

void Context::notifyMemoryAtomicLoad(const Memory *memory, AtomicOp op,
                                     size_t address, size_t size) const
{
  if (m_kernelInvocation && m_kernelInvocation->getCurrentWorkItem())
  {
    NOTIFY(memoryAtomicLoad, memory, m_kernelInvocation->getCurrentWorkItem(),
           op, address, size);
  }
}

void Context::notifyMemoryAtomicStore(const Memory *memory, AtomicOp op,
                                      size_t address, size_t size) const
{
  if (m_kernelInvocation && m_kernelInvocation->getCurrentWorkItem())
  {
    NOTIFY(memoryAtomicStore, memory, m_kernelInvocation->getCurrentWorkItem(),
           op, address, size);
  }
}

void Context::notifyMemoryDeallocated(const Memory *memory,
                                      size_t address) const
{
  NOTIFY(memoryDeallocated, memory, address);
}

void Context::notifyMemoryLoad(const Memory *memory, size_t address,
                               size_t size) const
{
  if (m_kernelInvocation)
  {
    if (m_kernelInvocation->getCurrentWorkItem())
    {
      NOTIFY(memoryLoad, memory, m_kernelInvocation->getCurrentWorkItem(),
             address, size);
    }
    else if (m_kernelInvocation->getCurrentWorkGroup())
    {
      NOTIFY(memoryLoad, memory, m_kernelInvocation->getCurrentWorkGroup(),
             address, size);
    }
  }
  else
  {
    NOTIFY(hostMemoryLoad, memory, address, size);
  }
}

void Context::notifyMemoryStore(const Memory *memory, size_t address,
                                size_t size, const uint8_t *storeData) const
{
  if (m_kernelInvocation)
  {
    if (m_kernelInvocation->getCurrentWorkItem())
    {
      NOTIFY(memoryStore, memory, m_kernelInvocation->getCurrentWorkItem(),
             address, size, storeData);
    }
    else if (m_kernelInvocation->getCurrentWorkGroup())
    {
      NOTIFY(memoryStore, memory, m_kernelInvocation->getCurrentWorkGroup(),
             address, size, storeData);
    }
  }
  else
  {
    NOTIFY(hostMemoryStore, memory, address, size, storeData);
  }
}

void Context::notifyMessage(MessageType type, const char *message) const
{
  NOTIFY(log, type, message);
}

void Context::notifyWorkGroupBarrier(const WorkGroup *workGroup,
                                     uint32_t flags) const
{
  NOTIFY(workGroupBarrier, workGroup, flags);
}

void Context::notifyWorkGroupBegin(const WorkGroup *workGroup) const
{
  NOTIFY(workGroupBegin, workGroup);
}

void Context::notifyWorkGroupComplete(const WorkGroup *workGroup) const
{
  NOTIFY(workGroupComplete, workGroup);
}

void Context::notifyWorkItemBegin(const WorkItem *workItem) const
{
  NOTIFY(workItemBegin, workItem);
}

void Context::notifyWorkItemComplete(const WorkItem *workItem) const
{
  NOTIFY(workItemComplete, workItem);
}

#undef NOTIFY

Context::Message::Message(MessageType type, const Context *context)
{
  m_type             = type;
  m_context          = context;
  m_kernelInvocation = context->m_kernelInvocation;
}

Context::Message& Context::Message::operator<<(const special& id)
{
  switch (id)
  {
  case INDENT:
    m_indentModifiers.push_back( m_stream.tellp());
    break;
  case UNINDENT:
    m_indentModifiers.push_back(-m_stream.tellp());
    break;
  case CURRENT_KERNEL:
    *this << m_kernelInvocation->getKernel()->getName();
    break;
  case CURRENT_WORK_ITEM_GLOBAL:
  {
    const WorkItem *workItem = m_kernelInvocation->getCurrentWorkItem();
    if (workItem)
    {
      *this << workItem->getGlobalID();
    }
    else
    {
      *this << "(none)";
    }
    break;
  }
  case CURRENT_WORK_ITEM_LOCAL:
  {
    const WorkItem *workItem = m_kernelInvocation->getCurrentWorkItem();
    if (workItem)
    {
      *this << workItem->getLocalID();
    }
    else
    {
      *this << "(none)";
    }
    break;
  }
  case CURRENT_WORK_GROUP:
  {
    const WorkGroup *workGroup = m_kernelInvocation->getCurrentWorkGroup();
    if (workGroup)
    {
      *this << workGroup->getGroupID();
    }
    else
    {
      *this << "(none)";
    }
    break;
  }
  case CURRENT_ENTITY:
  {
    const WorkItem *workItem = m_kernelInvocation->getCurrentWorkItem();
    const WorkGroup *workGroup = m_kernelInvocation->getCurrentWorkGroup();
    if (workItem)
    {
      *this << "Global" << workItem->getGlobalID()
            << " Local" << workItem->getLocalID() << " ";
    }
    if (workGroup)
    {
      *this << "Group" << workGroup->getGroupID();
    }
    if (!workItem && ! workGroup)
    {
      *this << "(unknown)";
    }
    break;
  }
  case CURRENT_LOCATION:
  {
    const llvm::Instruction *instruction = NULL;
    const WorkItem *workItem = m_kernelInvocation->getCurrentWorkItem();
    const WorkGroup *workGroup = m_kernelInvocation->getCurrentWorkGroup();
    if (workItem)
    {
      instruction = workItem->getCurrentInstruction();
    }
    else if (workGroup)
    {
      instruction = workGroup->getCurrentBarrier();
    }

    *this << instruction;
    break;
  }
  }
  return *this;
}

Context::Message& Context::Message::operator<<(
  const llvm::Instruction *instruction)
{
  if (instruction)
  {
    // Output instruction
    dumpInstruction(m_stream, instruction);
    *this << endl;

    // Output debug information
    llvm::MDNode *md = instruction->getMetadata("dbg");
    if (!md)
    {
      *this << "Debugging information not available." << endl;
    }
    else
    {
      llvm::DILocation loc(md);

      *this << "At line " << dec << loc.getLineNumber()
           << " of " << loc.getFilename().str() << ":" << endl;

      // Get source line
      const Program *program = m_kernelInvocation->getKernel()->getProgram();
      const char *line = program->getSourceLine(loc.getLineNumber());
      if (line)
      {
        while (isspace(line[0]))
          line++;
        *this << "  " << line;
      }
      else
        *this << "  (source not available)";

    }
  }
  else
  {
    *this << "(location unknown)";
  }

  return *this;
}

Context::Message& Context::Message::operator<<(
  std::ostream& (*t)(std::ostream&))
{
  m_stream << t;
  return *this;
}

Context::Message& Context::Message::operator<<(
  std::ios& (*t)(std::ios&))
{
  m_stream << t;
  return *this;
}

Context::Message& Context::Message::operator<<(
  std::ios_base& (*t)(std::ios_base&))
{
  m_stream << t;
  return *this;
}

void Context::Message::send() const
{
  string msg;

  string line;
  int currentIndent = 0;
  list<int>::const_iterator itr = m_indentModifiers.begin();

  m_stream.clear();
  m_stream.seekg(0);
  while (m_stream.good())
  {
    getline(m_stream, line);

    // TODO: Wrap long lines
    msg += line;

    // Check for indentation modifiers
    long pos = m_stream.tellg();
    if (itr != m_indentModifiers.end() && pos >= abs(*itr))
    {
      if (*itr >= 0)
        currentIndent++;
      else
        currentIndent--;
      itr++;
    }

    if (!m_stream.eof())
    {
      // Add newline and indentation
      msg += '\n';
      for (int i = 0; i < currentIndent; i++)
        msg += '\t';
    }
  }

  m_context->notifyMessage(m_type, msg.c_str());
}
<commit_msg>Apply mutex when dumping instruction in Context::Message.<commit_after>// Context.cpp (Oclgrind)
// Copyright (c) 2013-2015, James Price and Simon McIntosh-Smith,
// University of Bristol. All rights reserved.
//
// This program is provided under a three-clause BSD license. For full
// license terms please see the LICENSE file distributed with this
// source code.

#include "common.h"

#if defined(_WIN32) && !defined(__MINGW32__)
#include <windows.h>
#undef ERROR
#else
#include <dlfcn.h>
#endif

#include <mutex>

#include "llvm/DebugInfo.h"
#include "llvm/Instruction.h"

#include "Context.h"
#include "Kernel.h"
#include "KernelInvocation.h"
#include "Memory.h"
#include "Program.h"
#include "WorkGroup.h"
#include "WorkItem.h"

#include "plugins/InstructionCounter.h"
#include "plugins/InteractiveDebugger.h"
#include "plugins/Logger.h"
#include "plugins/MemCheck.h"
#include "plugins/RaceDetector.h"

using namespace oclgrind;
using namespace std;

Context::Context()
{
  m_globalMemory = new Memory(AddrSpaceGlobal, this);
  m_kernelInvocation = NULL;

  loadPlugins();
}

Context::~Context()
{
  delete m_globalMemory;

  unloadPlugins();
}

bool Context::isThreadSafe() const
{
  for (const PluginEntry &p : m_plugins)
  {
    if (!p.first->isThreadSafe())
      return false;
  }
  return true;
}

Memory* Context::getGlobalMemory() const
{
  return m_globalMemory;
}

void Context::loadPlugins()
{
  // Create core plugins
  m_plugins.push_back(make_pair(new Logger(this), true));
  m_plugins.push_back(make_pair(new MemCheck(this), true));

  if (checkEnv("OCLGRIND_INST_COUNTS"))
    m_plugins.push_back(make_pair(new InstructionCounter(this), true));

  if (checkEnv("OCLGRIND_DATA_RACES"))
    m_plugins.push_back(make_pair(new RaceDetector(this), true));

  if (checkEnv("OCLGRIND_INTERACTIVE"))
    m_plugins.push_back(make_pair(new InteractiveDebugger(this), true));

  // Load dynamic plugins
  const char *dynamicPlugins = getenv("OCLGRIND_PLUGINS");
  if (dynamicPlugins)
  {
    std::istringstream ss(dynamicPlugins);
    std::string libpath;
    while(std::getline(ss, libpath, ':'))
    {
#if defined(_WIN32) && !defined(__MINGW32__)
      HMODULE library = LoadLibrary(libpath.c_str());
      if (!library)
      {
        cerr << "Loading Oclgrind plugin failed (LoadLibrary): "
             << GetLastError() << endl;
        continue;
      }

      void *initialize = GetProcAddress(library, "initializePlugins");
      if (!initialize)
      {
        cerr << "Loading Oclgrind plugin failed (GetProcAddress): "
             << GetLastError() << endl;
        continue;
      }
#else
      void *library = dlopen(libpath.c_str(), RTLD_NOW);
      if (!library)
      {
        cerr << "Loading Oclgrind plugin failed (dlopen): "
             << dlerror() << endl;
        continue;
      }

      void *initialize = dlsym(library, "initializePlugins");
      if (!initialize)
      {
        cerr << "Loading Oclgrind plugin failed (dlsym): "
             << dlerror() << endl;
        continue;
      }
#endif

      ((void(*)(Context*))initialize)(this);
      m_pluginLibraries.push_back(library);
    }
  }
}

void Context::unloadPlugins()
{
  // Release dynamic plugin libraries
  list<void*>::iterator plibItr;
  for (plibItr = m_pluginLibraries.begin();
       plibItr != m_pluginLibraries.end(); plibItr++)
  {
#if defined(_WIN32) && !defined(__MINGW32__)
      void *release = GetProcAddress((HMODULE)*plibItr, "releasePlugins");
      if (release)
      {
        ((void(*)(Context*))release)(this);
      }
      FreeLibrary((HMODULE)*plibItr);
#else
      void *release = dlsym(*plibItr, "releasePlugins");
      if (release)
      {
        ((void(*)(Context*))release)(this);
      }
      dlclose(*plibItr);
#endif
  }

  // Destroy internal plugins
  PluginList::iterator pItr;
  for (pItr = m_plugins.begin(); pItr != m_plugins.end(); pItr++)
  {
    if (pItr->second)
      delete pItr->first;
  }

  m_plugins.clear();
}

void Context::registerPlugin(Plugin *plugin)
{
  m_plugins.push_back(make_pair(plugin, false));
}

void Context::unregisterPlugin(Plugin *plugin)
{
  m_plugins.remove(make_pair(plugin, false));
}

void Context::logError(const char* error) const
{
  Message msg(ERROR, this);
  msg << error << endl
      << msg.INDENT
      << "Kernel: " << msg.CURRENT_KERNEL << endl
      << "Entity: " << msg.CURRENT_ENTITY << endl
      << msg.CURRENT_LOCATION << endl;
  msg.send();
}

#define NOTIFY(function, ...)                     \
{                                                 \
  PluginList::const_iterator pluginItr;           \
  for (pluginItr = m_plugins.begin();             \
       pluginItr != m_plugins.end(); pluginItr++) \
  {                                               \
    pluginItr->first->function(__VA_ARGS__);      \
  }                                               \
}

void Context::notifyInstructionExecuted(const WorkItem *workItem,
                                        const llvm::Instruction *instruction,
                                        const TypedValue& result) const
{
  NOTIFY(instructionExecuted, workItem, instruction, result);
}

void Context::notifyKernelBegin(const KernelInvocation *kernelInvocation) const
{
  assert(m_kernelInvocation == NULL);
  m_kernelInvocation = kernelInvocation;

  NOTIFY(kernelBegin, kernelInvocation);
}

void Context::notifyKernelEnd(const KernelInvocation *kernelInvocation) const
{
  NOTIFY(kernelEnd, kernelInvocation);

  assert(m_kernelInvocation == kernelInvocation);
  m_kernelInvocation = NULL;
}

void Context::notifyMemoryAllocated(const Memory *memory, size_t address,
                                    size_t size, cl_mem_flags flags) const
{
  NOTIFY(memoryAllocated, memory, address, size, flags);
}

void Context::notifyMemoryAtomicLoad(const Memory *memory, AtomicOp op,
                                     size_t address, size_t size) const
{
  if (m_kernelInvocation && m_kernelInvocation->getCurrentWorkItem())
  {
    NOTIFY(memoryAtomicLoad, memory, m_kernelInvocation->getCurrentWorkItem(),
           op, address, size);
  }
}

void Context::notifyMemoryAtomicStore(const Memory *memory, AtomicOp op,
                                      size_t address, size_t size) const
{
  if (m_kernelInvocation && m_kernelInvocation->getCurrentWorkItem())
  {
    NOTIFY(memoryAtomicStore, memory, m_kernelInvocation->getCurrentWorkItem(),
           op, address, size);
  }
}

void Context::notifyMemoryDeallocated(const Memory *memory,
                                      size_t address) const
{
  NOTIFY(memoryDeallocated, memory, address);
}

void Context::notifyMemoryLoad(const Memory *memory, size_t address,
                               size_t size) const
{
  if (m_kernelInvocation)
  {
    if (m_kernelInvocation->getCurrentWorkItem())
    {
      NOTIFY(memoryLoad, memory, m_kernelInvocation->getCurrentWorkItem(),
             address, size);
    }
    else if (m_kernelInvocation->getCurrentWorkGroup())
    {
      NOTIFY(memoryLoad, memory, m_kernelInvocation->getCurrentWorkGroup(),
             address, size);
    }
  }
  else
  {
    NOTIFY(hostMemoryLoad, memory, address, size);
  }
}

void Context::notifyMemoryStore(const Memory *memory, size_t address,
                                size_t size, const uint8_t *storeData) const
{
  if (m_kernelInvocation)
  {
    if (m_kernelInvocation->getCurrentWorkItem())
    {
      NOTIFY(memoryStore, memory, m_kernelInvocation->getCurrentWorkItem(),
             address, size, storeData);
    }
    else if (m_kernelInvocation->getCurrentWorkGroup())
    {
      NOTIFY(memoryStore, memory, m_kernelInvocation->getCurrentWorkGroup(),
             address, size, storeData);
    }
  }
  else
  {
    NOTIFY(hostMemoryStore, memory, address, size, storeData);
  }
}

void Context::notifyMessage(MessageType type, const char *message) const
{
  NOTIFY(log, type, message);
}

void Context::notifyWorkGroupBarrier(const WorkGroup *workGroup,
                                     uint32_t flags) const
{
  NOTIFY(workGroupBarrier, workGroup, flags);
}

void Context::notifyWorkGroupBegin(const WorkGroup *workGroup) const
{
  NOTIFY(workGroupBegin, workGroup);
}

void Context::notifyWorkGroupComplete(const WorkGroup *workGroup) const
{
  NOTIFY(workGroupComplete, workGroup);
}

void Context::notifyWorkItemBegin(const WorkItem *workItem) const
{
  NOTIFY(workItemBegin, workItem);
}

void Context::notifyWorkItemComplete(const WorkItem *workItem) const
{
  NOTIFY(workItemComplete, workItem);
}

#undef NOTIFY

Context::Message::Message(MessageType type, const Context *context)
{
  m_type             = type;
  m_context          = context;
  m_kernelInvocation = context->m_kernelInvocation;
}

Context::Message& Context::Message::operator<<(const special& id)
{
  switch (id)
  {
  case INDENT:
    m_indentModifiers.push_back( m_stream.tellp());
    break;
  case UNINDENT:
    m_indentModifiers.push_back(-m_stream.tellp());
    break;
  case CURRENT_KERNEL:
    *this << m_kernelInvocation->getKernel()->getName();
    break;
  case CURRENT_WORK_ITEM_GLOBAL:
  {
    const WorkItem *workItem = m_kernelInvocation->getCurrentWorkItem();
    if (workItem)
    {
      *this << workItem->getGlobalID();
    }
    else
    {
      *this << "(none)";
    }
    break;
  }
  case CURRENT_WORK_ITEM_LOCAL:
  {
    const WorkItem *workItem = m_kernelInvocation->getCurrentWorkItem();
    if (workItem)
    {
      *this << workItem->getLocalID();
    }
    else
    {
      *this << "(none)";
    }
    break;
  }
  case CURRENT_WORK_GROUP:
  {
    const WorkGroup *workGroup = m_kernelInvocation->getCurrentWorkGroup();
    if (workGroup)
    {
      *this << workGroup->getGroupID();
    }
    else
    {
      *this << "(none)";
    }
    break;
  }
  case CURRENT_ENTITY:
  {
    const WorkItem *workItem = m_kernelInvocation->getCurrentWorkItem();
    const WorkGroup *workGroup = m_kernelInvocation->getCurrentWorkGroup();
    if (workItem)
    {
      *this << "Global" << workItem->getGlobalID()
            << " Local" << workItem->getLocalID() << " ";
    }
    if (workGroup)
    {
      *this << "Group" << workGroup->getGroupID();
    }
    if (!workItem && ! workGroup)
    {
      *this << "(unknown)";
    }
    break;
  }
  case CURRENT_LOCATION:
  {
    const llvm::Instruction *instruction = NULL;
    const WorkItem *workItem = m_kernelInvocation->getCurrentWorkItem();
    const WorkGroup *workGroup = m_kernelInvocation->getCurrentWorkGroup();
    if (workItem)
    {
      instruction = workItem->getCurrentInstruction();
    }
    else if (workGroup)
    {
      instruction = workGroup->getCurrentBarrier();
    }

    *this << instruction;
    break;
  }
  }
  return *this;
}

Context::Message& Context::Message::operator<<(
  const llvm::Instruction *instruction)
{
  // Use mutex as some part of LLVM used by dumpInstruction() is not thread-safe
  static std::mutex mtx;
  std::lock_guard<std::mutex> lock(mtx);

  if (instruction)
  {
    // Output instruction
    dumpInstruction(m_stream, instruction);
    *this << endl;

    // Output debug information
    llvm::MDNode *md = instruction->getMetadata("dbg");
    if (!md)
    {
      *this << "Debugging information not available." << endl;
    }
    else
    {
      llvm::DILocation loc(md);

      *this << "At line " << dec << loc.getLineNumber()
           << " of " << loc.getFilename().str() << ":" << endl;

      // Get source line
      const Program *program = m_kernelInvocation->getKernel()->getProgram();
      const char *line = program->getSourceLine(loc.getLineNumber());
      if (line)
      {
        while (isspace(line[0]))
          line++;
        *this << "  " << line;
      }
      else
        *this << "  (source not available)";

    }
  }
  else
  {
    *this << "(location unknown)";
  }

  return *this;
}

Context::Message& Context::Message::operator<<(
  std::ostream& (*t)(std::ostream&))
{
  m_stream << t;
  return *this;
}

Context::Message& Context::Message::operator<<(
  std::ios& (*t)(std::ios&))
{
  m_stream << t;
  return *this;
}

Context::Message& Context::Message::operator<<(
  std::ios_base& (*t)(std::ios_base&))
{
  m_stream << t;
  return *this;
}

void Context::Message::send() const
{
  string msg;

  string line;
  int currentIndent = 0;
  list<int>::const_iterator itr = m_indentModifiers.begin();

  m_stream.clear();
  m_stream.seekg(0);
  while (m_stream.good())
  {
    getline(m_stream, line);

    // TODO: Wrap long lines
    msg += line;

    // Check for indentation modifiers
    long pos = m_stream.tellg();
    if (itr != m_indentModifiers.end() && pos >= abs(*itr))
    {
      if (*itr >= 0)
        currentIndent++;
      else
        currentIndent--;
      itr++;
    }

    if (!m_stream.eof())
    {
      // Add newline and indentation
      msg += '\n';
      for (int i = 0; i < currentIndent; i++)
        msg += '\t';
    }
  }

  m_context->notifyMessage(m_type, msg.c_str());
}
<|endoftext|>


<commit_before>
/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkBBoxRecord.h"

void SkBBoxRecord::drawOval(const SkRect& rect, const SkPaint& paint) {
    if (this->transformBounds(rect, &paint)) {
        INHERITED::drawOval(rect, paint);
    }
}

void SkBBoxRecord::drawRRect(const SkRRect& rrect, const SkPaint& paint) {
    if (this->transformBounds(rrect.rect(), &paint)) {
        INHERITED::drawRRect(rrect, paint);
    }
}

void SkBBoxRecord::drawRect(const SkRect& rect, const SkPaint& paint) {
    if (this->transformBounds(rect, &paint)) {
        INHERITED::drawRect(rect, paint);
    }
}

void SkBBoxRecord::drawPath(const SkPath& path, const SkPaint& paint) {
    if (path.isInverseFillType()) {
        // If path is inverse filled, use the current clip bounds as the
        // path's device-space bounding box.
        SkIRect clipBounds;
        if (this->getClipDeviceBounds(&clipBounds)) {
            this->handleBBox(SkRect::MakeFromIRect(clipBounds));
            INHERITED::drawPath(path, paint);
        }
    } else if (this->transformBounds(path.getBounds(), &paint)) {
        INHERITED::drawPath(path, paint);
    }
}

void SkBBoxRecord::drawPoints(PointMode mode, size_t count, const SkPoint pts[],
                              const SkPaint& paint) {
    SkRect bbox;
    bbox.set(pts, count);
    // Small min width value, just to ensure hairline point bounding boxes aren't empty.
    // Even though we know hairline primitives are drawn one pixel wide, we do not use a
    // minimum of 1 because the playback scale factor is unknown at record time. Later
    // outsets will take care of adding additional padding for antialiasing and rounding out
    // to integer device coordinates, guaranteeing that the rasterized pixels will be included
    // in the computed bounds.
    // Note: The device coordinate outset in SkBBoxHierarchyRecord::handleBBox is currently
    // done in the recording coordinate space, which is wrong.
    // http://code.google.com/p/skia/issues/detail?id=1021
    static const SkScalar kMinWidth = SkFloatToScalar(0.01f);
    SkScalar halfStrokeWidth = SkMaxScalar(paint.getStrokeWidth(), kMinWidth) / 2;
    bbox.outset(halfStrokeWidth, halfStrokeWidth);
    if (this->transformBounds(bbox, &paint)) {
        INHERITED::drawPoints(mode, count, pts, paint);
    }
}

void SkBBoxRecord::drawPaint(const SkPaint& paint) {
    SkRect bbox;
    if (this->getClipBounds(&bbox)) {
        if (this->transformBounds(bbox, &paint)) {
            INHERITED::drawPaint(paint);
        }
    }
}

void SkBBoxRecord::clear(SkColor color) {
    SkISize size = this->getDeviceSize();
    SkRect bbox = {0, 0, SkIntToScalar(size.width()), SkIntToScalar(size.height())};
    this->handleBBox(bbox);
    INHERITED::clear(color);
}

void SkBBoxRecord::drawText(const void* text, size_t byteLength, SkScalar x, SkScalar y,
                            const SkPaint& paint) {
    SkRect bbox;
    paint.measureText(text, byteLength, &bbox);
    SkPaint::FontMetrics metrics;
    paint.getFontMetrics(&metrics);

    // Vertical and aligned text need to be offset
    if (paint.isVerticalText()) {
        SkScalar h = bbox.fBottom - bbox.fTop;
        if (paint.getTextAlign() == SkPaint::kCenter_Align) {
            bbox.fTop    -= h / 2;
            bbox.fBottom -= h / 2;
        }
        // Pad top and bottom with max extents from FontMetrics
        bbox.fBottom += metrics.fBottom;
        bbox.fTop += metrics.fTop;
    } else {
        SkScalar w = bbox.fRight - bbox.fLeft;
        if (paint.getTextAlign() == SkPaint::kCenter_Align) {
            bbox.fLeft  -= w / 2;
            bbox.fRight -= w / 2;
        } else if (paint.getTextAlign() == SkPaint::kRight_Align) {
            bbox.fLeft  -= w;
            bbox.fRight -= w;
        }
        // Set vertical bounds to max extents from font metrics
        bbox.fTop = metrics.fTop;
        bbox.fBottom = metrics.fBottom;
    }

    // Pad horizontal bounds on each side by half of max vertical extents (this is sort of
    // arbitrary, but seems to produce reasonable results, if there were a way of getting max
    // glyph X-extents to pad by, that may be better here, but FontMetrics fXMin and fXMax seem
    // incorrect on most platforms (too small in Linux, never even set in Windows).
    SkScalar pad = (metrics.fBottom - metrics.fTop) / 2;
    bbox.fLeft  -= pad;
    bbox.fRight += pad;

    bbox.fLeft += x;
    bbox.fRight += x;
    bbox.fTop += y;
    bbox.fBottom += y;
    if (this->transformBounds(bbox, &paint)) {
        INHERITED::drawText(text, byteLength, x, y, paint);
    }
}

void SkBBoxRecord::drawBitmap(const SkBitmap& bitmap, SkScalar left, SkScalar top,
                              const SkPaint* paint) {
    SkRect bbox = {left, top, left + bitmap.width(), top + bitmap.height()};
    if (this->transformBounds(bbox, paint)) {
        INHERITED::drawBitmap(bitmap, left, top, paint);
    }
}

void SkBBoxRecord::drawBitmapRectToRect(const SkBitmap& bitmap, const SkRect* src,
                                  const SkRect& dst, const SkPaint* paint) {
    if (this->transformBounds(dst, paint)) {
        INHERITED::drawBitmapRectToRect(bitmap, src, dst, paint);
    }
}

void SkBBoxRecord::drawBitmapMatrix(const SkBitmap& bitmap, const SkMatrix& mat,
                                    const SkPaint* paint) {
    SkMatrix m = mat;
    SkRect bbox = {0, 0, SkIntToScalar(bitmap.width()), SkIntToScalar(bitmap.height())};
    m.mapRect(&bbox);
    if (this->transformBounds(bbox, paint)) {
        INHERITED::drawBitmapMatrix(bitmap, mat, paint);
    }
}

void SkBBoxRecord::drawBitmapNine(const SkBitmap& bitmap, const SkIRect& center,
                                  const SkRect& dst, const SkPaint* paint) {
    if (this->transformBounds(dst, paint)) {
        INHERITED::drawBitmapNine(bitmap, center, dst, paint);
    }
}

void SkBBoxRecord::drawPosText(const void* text, size_t byteLength,
                               const SkPoint pos[], const SkPaint& paint) {
    SkRect bbox;
    bbox.set(pos, paint.countText(text, byteLength));
    SkPaint::FontMetrics metrics;
    paint.getFontMetrics(&metrics);
    bbox.fTop += metrics.fTop;
    bbox.fBottom += metrics.fBottom;

    // pad on left and right by half of max vertical glyph extents
    SkScalar pad = (metrics.fTop - metrics.fBottom) / 2;
    bbox.fLeft += pad;
    bbox.fRight -= pad;

    if (this->transformBounds(bbox, &paint)) {
        INHERITED::drawPosText(text, byteLength, pos, paint);
    }
}

void SkBBoxRecord::drawPosTextH(const void* text, size_t byteLength, const SkScalar xpos[],
                                SkScalar constY, const SkPaint& paint) {
    SkRect bbox;
    size_t numChars = paint.countText(text, byteLength);
    if (numChars > 0) {
        bbox.fLeft  = xpos[0];
        bbox.fRight = xpos[numChars - 1];
        // if we had a guarantee that these will be monotonically increasing, this could be sped up
        for (size_t i = 1; i < numChars; ++i) {
            if (xpos[i] < bbox.fLeft) {
                bbox.fLeft = xpos[i];
            }
            if (xpos[i] > bbox.fRight) {
                bbox.fRight = xpos[i];
            }
        }
        SkPaint::FontMetrics metrics;
        paint.getFontMetrics(&metrics);

        // pad horizontally by max glyph height
        SkScalar pad = (metrics.fTop - metrics.fBottom);
        bbox.fLeft  += pad;
        bbox.fRight -= pad;

        bbox.fTop    = metrics.fTop + constY;
        bbox.fBottom = metrics.fBottom + constY;
        if (!this->transformBounds(bbox, &paint)) {
            return;
        }
    }
    INHERITED::drawPosTextH(text, byteLength, xpos, constY, paint);
}

void SkBBoxRecord::drawSprite(const SkBitmap& bitmap, int left, int top,
                              const SkPaint* paint) {
    SkRect bbox;
    bbox.set(SkIRect::MakeXYWH(left, top, bitmap.width(), bitmap.height()));
    this->handleBBox(bbox); // directly call handleBBox, matrix is ignored
    INHERITED::drawSprite(bitmap, left, top, paint);
}

void SkBBoxRecord::drawTextOnPath(const void* text, size_t byteLength,
                                  const SkPath& path, const SkMatrix* matrix,
                                  const SkPaint& paint) {
    SkRect bbox = path.getBounds();
    SkPaint::FontMetrics metrics;
    paint.getFontMetrics(&metrics);

    // pad out all sides by the max glyph height above baseline
    SkScalar pad = metrics.fTop;
    bbox.fLeft += pad;
    bbox.fRight -= pad;
    bbox.fTop += pad;
    bbox.fBottom -= pad;

    if (this->transformBounds(bbox, &paint)) {
        INHERITED::drawTextOnPath(text, byteLength, path, matrix, paint);
    }
}

void SkBBoxRecord::drawVertices(VertexMode mode, int vertexCount,
                                const SkPoint vertices[], const SkPoint texs[],
                                const SkColor colors[], SkXfermode* xfer,
                                const uint16_t indices[], int indexCount,
                                const SkPaint& paint) {
    SkRect bbox;
    bbox.set(vertices, vertexCount);
    if (this->transformBounds(bbox, &paint)) {
        INHERITED::drawVertices(mode, vertexCount, vertices, texs,
                                colors, xfer, indices, indexCount, paint);
    }
}

void SkBBoxRecord::drawPicture(SkPicture& picture) {
    if (picture.width() > 0 && picture.height() > 0 &&
        this->transformBounds(SkRect::MakeWH(picture.width(), picture.height()), NULL)) {
        INHERITED::drawPicture(picture);
    }
}

bool SkBBoxRecord::transformBounds(const SkRect& bounds, const SkPaint* paint) {
    SkRect outBounds = bounds;
    outBounds.sort();

    if (paint) {
        // account for stroking, path effects, shadows, etc
        if (paint->canComputeFastBounds()) {
            SkRect temp;
            outBounds = paint->computeFastBounds(outBounds, &temp);
        } else {
            // set bounds to current clip
            if (!this->getClipBounds(&outBounds)) {
                // current clip is empty
                return false;
            }
        }
    }

    SkRect clip;

    if (this->getClipBounds(&clip) && outBounds.intersect(clip)) {
        this->getTotalMatrix().mapRect(&outBounds);
        this->handleBBox(outBounds);
        return true;
    }

    return false;
}

<commit_msg>Properly reject clipped out draws in BBox pictures. https://codereview.appspot.com/7057065/<commit_after>
/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkBBoxRecord.h"

void SkBBoxRecord::drawOval(const SkRect& rect, const SkPaint& paint) {
    if (this->transformBounds(rect, &paint)) {
        INHERITED::drawOval(rect, paint);
    }
}

void SkBBoxRecord::drawRRect(const SkRRect& rrect, const SkPaint& paint) {
    if (this->transformBounds(rrect.rect(), &paint)) {
        INHERITED::drawRRect(rrect, paint);
    }
}

void SkBBoxRecord::drawRect(const SkRect& rect, const SkPaint& paint) {
    if (this->transformBounds(rect, &paint)) {
        INHERITED::drawRect(rect, paint);
    }
}

void SkBBoxRecord::drawPath(const SkPath& path, const SkPaint& paint) {
    if (path.isInverseFillType()) {
        // If path is inverse filled, use the current clip bounds as the
        // path's device-space bounding box.
        SkIRect clipBounds;
        if (this->getClipDeviceBounds(&clipBounds)) {
            this->handleBBox(SkRect::MakeFromIRect(clipBounds));
            INHERITED::drawPath(path, paint);
        }
    } else if (this->transformBounds(path.getBounds(), &paint)) {
        INHERITED::drawPath(path, paint);
    }
}

void SkBBoxRecord::drawPoints(PointMode mode, size_t count, const SkPoint pts[],
                              const SkPaint& paint) {
    SkRect bbox;
    bbox.set(pts, count);
    // Small min width value, just to ensure hairline point bounding boxes aren't empty.
    // Even though we know hairline primitives are drawn one pixel wide, we do not use a
    // minimum of 1 because the playback scale factor is unknown at record time. Later
    // outsets will take care of adding additional padding for antialiasing and rounding out
    // to integer device coordinates, guaranteeing that the rasterized pixels will be included
    // in the computed bounds.
    // Note: The device coordinate outset in SkBBoxHierarchyRecord::handleBBox is currently
    // done in the recording coordinate space, which is wrong.
    // http://code.google.com/p/skia/issues/detail?id=1021
    static const SkScalar kMinWidth = SkFloatToScalar(0.01f);
    SkScalar halfStrokeWidth = SkMaxScalar(paint.getStrokeWidth(), kMinWidth) / 2;
    bbox.outset(halfStrokeWidth, halfStrokeWidth);
    if (this->transformBounds(bbox, &paint)) {
        INHERITED::drawPoints(mode, count, pts, paint);
    }
}

void SkBBoxRecord::drawPaint(const SkPaint& paint) {
    SkRect bbox;
    if (this->getClipBounds(&bbox)) {
        if (this->transformBounds(bbox, &paint)) {
            INHERITED::drawPaint(paint);
        }
    }
}

void SkBBoxRecord::clear(SkColor color) {
    SkISize size = this->getDeviceSize();
    SkRect bbox = {0, 0, SkIntToScalar(size.width()), SkIntToScalar(size.height())};
    this->handleBBox(bbox);
    INHERITED::clear(color);
}

void SkBBoxRecord::drawText(const void* text, size_t byteLength, SkScalar x, SkScalar y,
                            const SkPaint& paint) {
    SkRect bbox;
    paint.measureText(text, byteLength, &bbox);
    SkPaint::FontMetrics metrics;
    paint.getFontMetrics(&metrics);

    // Vertical and aligned text need to be offset
    if (paint.isVerticalText()) {
        SkScalar h = bbox.fBottom - bbox.fTop;
        if (paint.getTextAlign() == SkPaint::kCenter_Align) {
            bbox.fTop    -= h / 2;
            bbox.fBottom -= h / 2;
        }
        // Pad top and bottom with max extents from FontMetrics
        bbox.fBottom += metrics.fBottom;
        bbox.fTop += metrics.fTop;
    } else {
        SkScalar w = bbox.fRight - bbox.fLeft;
        if (paint.getTextAlign() == SkPaint::kCenter_Align) {
            bbox.fLeft  -= w / 2;
            bbox.fRight -= w / 2;
        } else if (paint.getTextAlign() == SkPaint::kRight_Align) {
            bbox.fLeft  -= w;
            bbox.fRight -= w;
        }
        // Set vertical bounds to max extents from font metrics
        bbox.fTop = metrics.fTop;
        bbox.fBottom = metrics.fBottom;
    }

    // Pad horizontal bounds on each side by half of max vertical extents (this is sort of
    // arbitrary, but seems to produce reasonable results, if there were a way of getting max
    // glyph X-extents to pad by, that may be better here, but FontMetrics fXMin and fXMax seem
    // incorrect on most platforms (too small in Linux, never even set in Windows).
    SkScalar pad = (metrics.fBottom - metrics.fTop) / 2;
    bbox.fLeft  -= pad;
    bbox.fRight += pad;

    bbox.fLeft += x;
    bbox.fRight += x;
    bbox.fTop += y;
    bbox.fBottom += y;
    if (this->transformBounds(bbox, &paint)) {
        INHERITED::drawText(text, byteLength, x, y, paint);
    }
}

void SkBBoxRecord::drawBitmap(const SkBitmap& bitmap, SkScalar left, SkScalar top,
                              const SkPaint* paint) {
    SkRect bbox = {left, top, left + bitmap.width(), top + bitmap.height()};
    if (this->transformBounds(bbox, paint)) {
        INHERITED::drawBitmap(bitmap, left, top, paint);
    }
}

void SkBBoxRecord::drawBitmapRectToRect(const SkBitmap& bitmap, const SkRect* src,
                                  const SkRect& dst, const SkPaint* paint) {
    if (this->transformBounds(dst, paint)) {
        INHERITED::drawBitmapRectToRect(bitmap, src, dst, paint);
    }
}

void SkBBoxRecord::drawBitmapMatrix(const SkBitmap& bitmap, const SkMatrix& mat,
                                    const SkPaint* paint) {
    SkMatrix m = mat;
    SkRect bbox = {0, 0, SkIntToScalar(bitmap.width()), SkIntToScalar(bitmap.height())};
    m.mapRect(&bbox);
    if (this->transformBounds(bbox, paint)) {
        INHERITED::drawBitmapMatrix(bitmap, mat, paint);
    }
}

void SkBBoxRecord::drawBitmapNine(const SkBitmap& bitmap, const SkIRect& center,
                                  const SkRect& dst, const SkPaint* paint) {
    if (this->transformBounds(dst, paint)) {
        INHERITED::drawBitmapNine(bitmap, center, dst, paint);
    }
}

void SkBBoxRecord::drawPosText(const void* text, size_t byteLength,
                               const SkPoint pos[], const SkPaint& paint) {
    SkRect bbox;
    bbox.set(pos, paint.countText(text, byteLength));
    SkPaint::FontMetrics metrics;
    paint.getFontMetrics(&metrics);
    bbox.fTop += metrics.fTop;
    bbox.fBottom += metrics.fBottom;

    // pad on left and right by half of max vertical glyph extents
    SkScalar pad = (metrics.fTop - metrics.fBottom) / 2;
    bbox.fLeft += pad;
    bbox.fRight -= pad;

    if (this->transformBounds(bbox, &paint)) {
        INHERITED::drawPosText(text, byteLength, pos, paint);
    }
}

void SkBBoxRecord::drawPosTextH(const void* text, size_t byteLength, const SkScalar xpos[],
                                SkScalar constY, const SkPaint& paint) {
    SkRect bbox;
    size_t numChars = paint.countText(text, byteLength);
    if (numChars > 0) {
        bbox.fLeft  = xpos[0];
        bbox.fRight = xpos[numChars - 1];
        // if we had a guarantee that these will be monotonically increasing, this could be sped up
        for (size_t i = 1; i < numChars; ++i) {
            if (xpos[i] < bbox.fLeft) {
                bbox.fLeft = xpos[i];
            }
            if (xpos[i] > bbox.fRight) {
                bbox.fRight = xpos[i];
            }
        }
        SkPaint::FontMetrics metrics;
        paint.getFontMetrics(&metrics);

        // pad horizontally by max glyph height
        SkScalar pad = (metrics.fTop - metrics.fBottom);
        bbox.fLeft  += pad;
        bbox.fRight -= pad;

        bbox.fTop    = metrics.fTop + constY;
        bbox.fBottom = metrics.fBottom + constY;
        if (!this->transformBounds(bbox, &paint)) {
            return;
        }
    }
    INHERITED::drawPosTextH(text, byteLength, xpos, constY, paint);
}

void SkBBoxRecord::drawSprite(const SkBitmap& bitmap, int left, int top,
                              const SkPaint* paint) {
    SkRect bbox;
    bbox.set(SkIRect::MakeXYWH(left, top, bitmap.width(), bitmap.height()));
    this->handleBBox(bbox); // directly call handleBBox, matrix is ignored
    INHERITED::drawSprite(bitmap, left, top, paint);
}

void SkBBoxRecord::drawTextOnPath(const void* text, size_t byteLength,
                                  const SkPath& path, const SkMatrix* matrix,
                                  const SkPaint& paint) {
    SkRect bbox = path.getBounds();
    SkPaint::FontMetrics metrics;
    paint.getFontMetrics(&metrics);

    // pad out all sides by the max glyph height above baseline
    SkScalar pad = metrics.fTop;
    bbox.fLeft += pad;
    bbox.fRight -= pad;
    bbox.fTop += pad;
    bbox.fBottom -= pad;

    if (this->transformBounds(bbox, &paint)) {
        INHERITED::drawTextOnPath(text, byteLength, path, matrix, paint);
    }
}

void SkBBoxRecord::drawVertices(VertexMode mode, int vertexCount,
                                const SkPoint vertices[], const SkPoint texs[],
                                const SkColor colors[], SkXfermode* xfer,
                                const uint16_t indices[], int indexCount,
                                const SkPaint& paint) {
    SkRect bbox;
    bbox.set(vertices, vertexCount);
    if (this->transformBounds(bbox, &paint)) {
        INHERITED::drawVertices(mode, vertexCount, vertices, texs,
                                colors, xfer, indices, indexCount, paint);
    }
}

void SkBBoxRecord::drawPicture(SkPicture& picture) {
    if (picture.width() > 0 && picture.height() > 0 &&
        this->transformBounds(SkRect::MakeWH(picture.width(), picture.height()), NULL)) {
        INHERITED::drawPicture(picture);
    }
}

bool SkBBoxRecord::transformBounds(const SkRect& bounds, const SkPaint* paint) {
    SkRect outBounds = bounds;
    outBounds.sort();

    if (paint) {
        // account for stroking, path effects, shadows, etc
        if (paint->canComputeFastBounds()) {
            SkRect temp;
            outBounds = paint->computeFastBounds(outBounds, &temp);
        } else {
            // set bounds to current clip
            if (!this->getClipBounds(&outBounds)) {
                // current clip is empty
                return false;
            }
        }
    }

    if (!this->quickReject(outBounds)) {
        this->getTotalMatrix().mapRect(&outBounds);
        this->handleBBox(outBounds);
        return true;
    }

    return false;
}

<|endoftext|>


<commit_before>/**********************************************************************************

 Infomap software package for multi-level network clustering

 Copyright (c) 2013, 2014 Daniel Edler, Martin Rosvall

 For more information, see <http://www.mapequation.org>

 This file is part of Infomap software package.

 Infomap software package is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 Infomap software package is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with Infomap software package.  If not, see <http://www.gnu.org/licenses/>.

**********************************************************************************/

#include "StateNetwork.h"
#include "../utils/FlowCalculator.h"
#include "../utils/Log.h"

namespace infomap {

std::pair<StateNetwork::NodeMap::iterator, bool> StateNetwork::addStateNode(StateNode node)
{
	addPhysicalNode(node.physicalId);
	if (node.id != node.physicalId) {
		m_haveMemoryInput = true;
	}
	// return m_nodes.emplace(node.id, node);
	auto ret = m_nodes.insert(StateNetwork::NodeMap::value_type(node.id, node));
	return ret;
}

std::pair<StateNetwork::NodeMap::iterator, bool> StateNetwork::addStateNode(unsigned int id, unsigned int physId)
{
	return addStateNode(StateNode(id, physId));
}

std::pair<StateNetwork::NodeMap::iterator, bool> StateNetwork::addNode(unsigned int id)
{
	return addStateNode(StateNode(id));
}

std::pair<StateNetwork::NodeMap::iterator, bool> StateNetwork::addNode(unsigned int id, double weight)
{
	auto ret = addNode(id);
	auto& node = ret.first->second;
	node.weight = weight;
	return ret;
}

std::pair<StateNetwork::NodeMap::iterator, bool> StateNetwork::addNode(unsigned int id, std::string name)
{
	m_names[id] = name;
	return addNode(id);
}

std::pair<StateNetwork::NodeMap::iterator, bool> StateNetwork::addNode(unsigned int id, std::string name, double weight)
{
	m_names[id] = name;
	return addNode(id, weight);
}

StateNetwork::PhysNode& StateNetwork::addPhysicalNode(unsigned int physId)
{
	auto& physNode = m_physNodes[physId];
	physNode.physId = physId;
	return physNode;
}

StateNetwork::PhysNode& StateNetwork::addPhysicalNode(unsigned int physId, double weight)
{
	auto& physNode = addPhysicalNode(physId);
	physNode.weight = weight;
	return physNode;
}

StateNetwork::PhysNode& StateNetwork::addPhysicalNode(unsigned int physId, const std::string& name)
{
	auto& physNode = addPhysicalNode(physId);
	physNode.name = name;
	return physNode;
}

StateNetwork::PhysNode& StateNetwork::addPhysicalNode(unsigned int physId, double weight, const std::string& name)
{
	auto& physNode = addPhysicalNode(physId);
	physNode.weight = weight;
	physNode.name = name;
	return physNode;
}

std::pair<std::map<unsigned int, std::string>::iterator, bool> StateNetwork::addName(unsigned int id, std::string name)
{
	// m_names[id] = name;
	return m_names.insert(std::make_pair(id, name));
}

bool StateNetwork::addLink(unsigned int sourceId, unsigned int targetId, double weight)
{
	if (sourceId == targetId) {
		++m_numSelfLinksFound;
		if (!m_config.includeSelfLinks) {
			return false;
		}
		m_sumSelfLinkWeight += weight;
	}
	// const auto& sourceNode = m_nodes.emplace(sourceId, StateNode(sourceId)).first;
	// const auto& targetNode = m_nodes.emplace(targetId, StateNode(targetId)).first;
	// m_nodes.emplace(sourceId, StateNode(sourceId));
	// m_nodes.emplace(targetId, StateNode(targetId));
	addNode(sourceId);
	addNode(targetId);

	++m_numLinks;
	m_sumLinkWeight += weight;

	bool addedNewLink = true;

	// Log() << "Add link " << sourceId << " -> " << targetId << ", weight: " << weight << "\n";
	// Aggregate link weights if they are definied more than once
	auto& outLinks = m_nodeLinkMap[sourceId];
	if (outLinks.empty()) {
		outLinks[targetId] = weight;
		// Log() << "  -> new source link!\n";
	}
	else {
		// auto& ret = outLinks.emplace(targetNode, weight);
		// if (!ret.second)
			// auto& linkData = ret.first;
		auto& linkData = outLinks[targetId];
		++linkData.count;
		if (linkData.count != 1) {
			// Log() << "  -> existing weight: " << linkData.weight;
			linkData.weight += weight;
			// Log() << " -> weight: " << linkData.weight << "\n";
			// Log() << "    -> count: " << linkData.count << ", weight: " << linkData.weight << "\n";
			++m_numAggregatedLinks;
			--m_numLinks;
			addedNewLink = false;
		}
		else {
			// Log() << "  -> new target link!\n";
			linkData.weight = weight;
		}
	}
	m_outWeights[sourceId] += weight;
	// printNetwork();
	return addedNewLink;
	// auto& ret = m_nodeLinkMap.emplace(sourceId, std::make_pair(StateNode(), LinkData()));
	// if (!ret.second) {
	// 	ret.first[targetId] = weight;
	// }
	// else {
	// 	auto& ret2 = ret.first.emplace(targetId, weight);
	// 	if (!ret2.second) {
	// 		ret2.first += weight;
	// 		++m_numAggregatedLinks;
	// 		--m_numLinks;
	// 		return false;
	// 	}
	// }
	// return true;

	// LinkMap::iterator firstIt = m_links.lower_bound(sourceId);
	// if (firstIt != m_links.end() && firstIt->first == sourceId) // First linkEnd already exists, check second linkEnd
	// {
	// 	std::pair<std::map<unsigned int, double>::iterator, bool> ret2 = firstIt->second.insert(std::make_pair(targetId, weight));
	// 	if (!ret2.second)
	// 	{
	// 		ret2.first->second += weight;
	// 		++m_numAggregatedLinks;
	// 		--m_numLinks;
	// 		return false;
	// 	}
	// }
	// else
	// {
	// 	m_links.insert(firstIt, std::make_pair(sourceId, std::map<unsigned int, double>()))->second.insert(std::make_pair(targetId, weight));
	// }

	// return true;
}

void StateNetwork::calculateFlow()
{
	FlowCalculator flowCalculator;
	flowCalculator.calculateFlow(*this, m_config);
}

void StateNetwork::dispose()
{
	m_nodeLinkMap.clear();
	m_physNodes.clear();
	m_nodes.clear();
}

void StateNetwork::printNetwork() const
{
	Log() << "----------------\n";
	Log() << "Current network:\n";
	for (auto& linkIt : m_nodeLinkMap) {
		for (auto& subIt : linkIt.second)
		{
			Log() << "  " << linkIt.first.id << " -> " << subIt.first.id << ", weight: " << subIt.second.weight << "\n";
		}
	}
	Log() << "----------------\n";
}

std::pair<StateNetwork::NodeMap::iterator, bool> StateNetwork::addStateNodeWithAutogeneratedId(unsigned int physId)
{
	// Keys sorted with std::less comparator, so last key is the largest
	unsigned int stateId = m_nodes.empty() ? 0 : m_nodes.crbegin()->first + 1;
	return addStateNode(stateId, physId);
}

}
<commit_msg>Fix don't add default physical node if memory state node exist<commit_after>/**********************************************************************************

 Infomap software package for multi-level network clustering

 Copyright (c) 2013, 2014 Daniel Edler, Martin Rosvall

 For more information, see <http://www.mapequation.org>

 This file is part of Infomap software package.

 Infomap software package is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 Infomap software package is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with Infomap software package.  If not, see <http://www.gnu.org/licenses/>.

**********************************************************************************/

#include "StateNetwork.h"
#include "../utils/FlowCalculator.h"
#include "../utils/Log.h"

namespace infomap {

std::pair<StateNetwork::NodeMap::iterator, bool> StateNetwork::addStateNode(StateNode node)
{
	// return m_nodes.emplace(node.id, node);
	auto ret = m_nodes.insert(StateNetwork::NodeMap::value_type(node.id, node));
	if (ret.second) {
		// If state node didn't exist, also create the associated physical node
		addPhysicalNode(node.physicalId);
		if (node.id != node.physicalId) {
			m_haveMemoryInput = true;
		}
	}
	return ret;
}

std::pair<StateNetwork::NodeMap::iterator, bool> StateNetwork::addStateNode(unsigned int id, unsigned int physId)
{
	return addStateNode(StateNode(id, physId));
}

std::pair<StateNetwork::NodeMap::iterator, bool> StateNetwork::addNode(unsigned int id)
{
	return addStateNode(StateNode(id));
}

std::pair<StateNetwork::NodeMap::iterator, bool> StateNetwork::addNode(unsigned int id, double weight)
{
	auto ret = addNode(id);
	auto& node = ret.first->second;
	node.weight = weight;
	return ret;
}

std::pair<StateNetwork::NodeMap::iterator, bool> StateNetwork::addNode(unsigned int id, std::string name)
{
	m_names[id] = name;
	return addNode(id);
}

std::pair<StateNetwork::NodeMap::iterator, bool> StateNetwork::addNode(unsigned int id, std::string name, double weight)
{
	m_names[id] = name;
	return addNode(id, weight);
}

StateNetwork::PhysNode& StateNetwork::addPhysicalNode(unsigned int physId)
{
	auto& physNode = m_physNodes[physId];
	physNode.physId = physId;
	return physNode;
}

StateNetwork::PhysNode& StateNetwork::addPhysicalNode(unsigned int physId, double weight)
{
	auto& physNode = addPhysicalNode(physId);
	physNode.weight = weight;
	return physNode;
}

StateNetwork::PhysNode& StateNetwork::addPhysicalNode(unsigned int physId, const std::string& name)
{
	auto& physNode = addPhysicalNode(physId);
	physNode.name = name;
	return physNode;
}

StateNetwork::PhysNode& StateNetwork::addPhysicalNode(unsigned int physId, double weight, const std::string& name)
{
	auto& physNode = addPhysicalNode(physId);
	physNode.weight = weight;
	physNode.name = name;
	return physNode;
}

std::pair<std::map<unsigned int, std::string>::iterator, bool> StateNetwork::addName(unsigned int id, std::string name)
{
	// m_names[id] = name;
	return m_names.insert(std::make_pair(id, name));
}

bool StateNetwork::addLink(unsigned int sourceId, unsigned int targetId, double weight)
{
	if (sourceId == targetId) {
		++m_numSelfLinksFound;
		if (!m_config.includeSelfLinks) {
			return false;
		}
		m_sumSelfLinkWeight += weight;
	}
	// const auto& sourceNode = m_nodes.emplace(sourceId, StateNode(sourceId)).first;
	// const auto& targetNode = m_nodes.emplace(targetId, StateNode(targetId)).first;
	// m_nodes.emplace(sourceId, StateNode(sourceId));
	// m_nodes.emplace(targetId, StateNode(targetId));
	addNode(sourceId);
	addNode(targetId);

	++m_numLinks;
	m_sumLinkWeight += weight;

	bool addedNewLink = true;

	// Log() << "Add link " << sourceId << " -> " << targetId << ", weight: " << weight << "\n";
	// Aggregate link weights if they are definied more than once
	auto& outLinks = m_nodeLinkMap[sourceId];
	if (outLinks.empty()) {
		outLinks[targetId] = weight;
		// Log() << "  -> new source link!\n";
	}
	else {
		// auto& ret = outLinks.emplace(targetNode, weight);
		// if (!ret.second)
			// auto& linkData = ret.first;
		auto& linkData = outLinks[targetId];
		++linkData.count;
		if (linkData.count != 1) {
			// Log() << "  -> existing weight: " << linkData.weight;
			linkData.weight += weight;
			// Log() << " -> weight: " << linkData.weight << "\n";
			// Log() << "    -> count: " << linkData.count << ", weight: " << linkData.weight << "\n";
			++m_numAggregatedLinks;
			--m_numLinks;
			addedNewLink = false;
		}
		else {
			// Log() << "  -> new target link!\n";
			linkData.weight = weight;
		}
	}
	m_outWeights[sourceId] += weight;
	// printNetwork();
	return addedNewLink;
	// auto& ret = m_nodeLinkMap.emplace(sourceId, std::make_pair(StateNode(), LinkData()));
	// if (!ret.second) {
	// 	ret.first[targetId] = weight;
	// }
	// else {
	// 	auto& ret2 = ret.first.emplace(targetId, weight);
	// 	if (!ret2.second) {
	// 		ret2.first += weight;
	// 		++m_numAggregatedLinks;
	// 		--m_numLinks;
	// 		return false;
	// 	}
	// }
	// return true;

	// LinkMap::iterator firstIt = m_links.lower_bound(sourceId);
	// if (firstIt != m_links.end() && firstIt->first == sourceId) // First linkEnd already exists, check second linkEnd
	// {
	// 	std::pair<std::map<unsigned int, double>::iterator, bool> ret2 = firstIt->second.insert(std::make_pair(targetId, weight));
	// 	if (!ret2.second)
	// 	{
	// 		ret2.first->second += weight;
	// 		++m_numAggregatedLinks;
	// 		--m_numLinks;
	// 		return false;
	// 	}
	// }
	// else
	// {
	// 	m_links.insert(firstIt, std::make_pair(sourceId, std::map<unsigned int, double>()))->second.insert(std::make_pair(targetId, weight));
	// }

	// return true;
}

void StateNetwork::calculateFlow()
{
	FlowCalculator flowCalculator;
	flowCalculator.calculateFlow(*this, m_config);
}

void StateNetwork::dispose()
{
	m_nodeLinkMap.clear();
	m_physNodes.clear();
	m_nodes.clear();
}

void StateNetwork::printNetwork() const
{
	Log() << "----------------\n";
	Log() << "Current network:\n";
	for (auto& linkIt : m_nodeLinkMap) {
		for (auto& subIt : linkIt.second)
		{
			Log() << "  " << linkIt.first.id << " -> " << subIt.first.id << ", weight: " << subIt.second.weight << "\n";
		}
	}
	Log() << "----------------\n";
}

std::pair<StateNetwork::NodeMap::iterator, bool> StateNetwork::addStateNodeWithAutogeneratedId(unsigned int physId)
{
	// Keys sorted with std::less comparator, so last key is the largest
	unsigned int stateId = m_nodes.empty() ? 0 : m_nodes.crbegin()->first + 1;
	return addStateNode(stateId, physId);
}

}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
 * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
 * Copyright (C) 2008 Alp Toker <alp@atoker.com>
 * Copyright (C) Research In Motion Limited 2009. All rights reserved.
 * Copyright (C) 2011 Kris Jordan <krisjordan@gmail.com>
 * Copyright (C) 2011 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "core/loader/IconController.h"

#include "core/dom/Document.h"
#include "core/dom/IconURL.h"
#include "core/page/Frame.h"

namespace WebCore {

IconController::IconController(Frame* frame)
    : m_frame(frame)
{
}

IconController::~IconController()
{
}

KURL IconController::url()
{
    IconURLs iconURLs = urlsForTypes(Favicon);
    return iconURLs.isEmpty() ? KURL() : iconURLs[0].m_iconURL;
}

IconURL IconController::iconURL(IconType iconType) const
{
    IconURL result;
    const Vector<IconURL>& iconURLs = m_frame->document()->iconURLs(iconType);
    Vector<IconURL>::const_iterator iter(iconURLs.begin());
    for (; iter != iconURLs.end(); ++iter) {
        if (result.m_iconURL.isEmpty() || !iter->m_mimeType.isEmpty())
            result = *iter;
    }

    return result;
}

IconURLs IconController::urlsForTypes(int iconTypesMask)
{
    IconURLs iconURLs;
    if (m_frame->tree() && m_frame->tree()->parent())
        return iconURLs;

    if (iconTypesMask & Favicon && !appendToIconURLs(Favicon, &iconURLs))
        iconURLs.append(defaultURL(Favicon));

#if ENABLE(TOUCH_ICON_LOADING)
    appendToIconURLs(TouchPrecomposedIcon, &iconURLs);
    appendToIconURLs(TouchIcon, &iconURLs);
#endif

    // Finally, append all remaining icons of this type.
    const Vector<IconURL>& allIconURLs = m_frame->document()->iconURLs(iconTypesMask);
    for (Vector<IconURL>::const_iterator iter = allIconURLs.begin(); iter != allIconURLs.end(); ++iter) {
        int i;
        int iconCount = iconURLs.size();
        for (i = 0; i < iconCount; ++i) {
            if (*iter == iconURLs.at(i))
                break;
        }
        if (i == iconCount)
            iconURLs.append(*iter);
    }

    return iconURLs;
}

bool IconController::appendToIconURLs(IconType iconType, IconURLs* iconURLs)
{
    IconURL faviconURL = iconURL(iconType);
    if (faviconURL.m_iconURL.isEmpty())
        return false;

    iconURLs->append(faviconURL);
    return true;
}

IconURL IconController::defaultURL(IconType iconType)
{
    // Don't return a favicon iconURL unless we're http or https
    KURL documentURL = m_frame->document()->url();
    if (!documentURL.protocolIsInHTTPFamily())
        return IconURL();

    KURL url;
    bool couldSetProtocol = url.setProtocol(documentURL.protocol());
    ASSERT_UNUSED(couldSetProtocol, couldSetProtocol);
    url.setHost(documentURL.host());
    if (documentURL.hasPort())
        url.setPort(documentURL.port());

    if (iconType == Favicon) {
        url.setPath("/favicon.ico");
        return IconURL::defaultIconURL(url, Favicon);
    }
    return IconURL();
}

}
<commit_msg>Revert "Disable default touch icons handling."<commit_after>/*
 * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
 * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
 * Copyright (C) 2008 Alp Toker <alp@atoker.com>
 * Copyright (C) Research In Motion Limited 2009. All rights reserved.
 * Copyright (C) 2011 Kris Jordan <krisjordan@gmail.com>
 * Copyright (C) 2011 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "core/loader/IconController.h"

#include "core/dom/Document.h"
#include "core/dom/IconURL.h"
#include "core/page/Frame.h"

namespace WebCore {

IconController::IconController(Frame* frame)
    : m_frame(frame)
{
}

IconController::~IconController()
{
}

KURL IconController::url()
{
    IconURLs iconURLs = urlsForTypes(Favicon);
    return iconURLs.isEmpty() ? KURL() : iconURLs[0].m_iconURL;
}

IconURL IconController::iconURL(IconType iconType) const
{
    IconURL result;
    const Vector<IconURL>& iconURLs = m_frame->document()->iconURLs(iconType);
    Vector<IconURL>::const_iterator iter(iconURLs.begin());
    for (; iter != iconURLs.end(); ++iter) {
        if (result.m_iconURL.isEmpty() || !iter->m_mimeType.isEmpty())
            result = *iter;
    }

    return result;
}

IconURLs IconController::urlsForTypes(int iconTypesMask)
{
    IconURLs iconURLs;
    if (m_frame->tree() && m_frame->tree()->parent())
        return iconURLs;

    if (iconTypesMask & Favicon && !appendToIconURLs(Favicon, &iconURLs))
        iconURLs.append(defaultURL(Favicon));

#if ENABLE(TOUCH_ICON_LOADING)
    int missedIcons = 0;
    if (iconTypesMask & TouchPrecomposedIcon)
        missedIcons += appendToIconURLs(TouchPrecomposedIcon, &iconURLs) ? 0:1;

    if (iconTypesMask & TouchIcon)
      missedIcons += appendToIconURLs(TouchIcon, &iconURLs) ? 0:1;

    // Only return the default touch icons when the both were required and neither was gotten.
    if (missedIcons == 2) {
        iconURLs.append(defaultURL(TouchPrecomposedIcon));
        iconURLs.append(defaultURL(TouchIcon));
    }
#endif

    // Finally, append all remaining icons of this type.
    const Vector<IconURL>& allIconURLs = m_frame->document()->iconURLs(iconTypesMask);
    for (Vector<IconURL>::const_iterator iter = allIconURLs.begin(); iter != allIconURLs.end(); ++iter) {
        int i;
        int iconCount = iconURLs.size();
        for (i = 0; i < iconCount; ++i) {
            if (*iter == iconURLs.at(i))
                break;
        }
        if (i == iconCount)
            iconURLs.append(*iter);
    }

    return iconURLs;
}

bool IconController::appendToIconURLs(IconType iconType, IconURLs* iconURLs)
{
    IconURL faviconURL = iconURL(iconType);
    if (faviconURL.m_iconURL.isEmpty())
        return false;

    iconURLs->append(faviconURL);
    return true;
}

IconURL IconController::defaultURL(IconType iconType)
{
    // Don't return a favicon iconURL unless we're http or https
    KURL documentURL = m_frame->document()->url();
    if (!documentURL.protocolIsInHTTPFamily())
        return IconURL();

    KURL url;
    bool couldSetProtocol = url.setProtocol(documentURL.protocol());
    ASSERT_UNUSED(couldSetProtocol, couldSetProtocol);
    url.setHost(documentURL.host());
    if (documentURL.hasPort())
        url.setPort(documentURL.port());

    if (iconType == Favicon) {
        url.setPath("/favicon.ico");
        return IconURL::defaultIconURL(url, Favicon);
    }
#if ENABLE(TOUCH_ICON_LOADING)
    if (iconType == TouchPrecomposedIcon) {
        url.setPath("/apple-touch-icon-precomposed.png");
        return IconURL::defaultIconURL(url, TouchPrecomposedIcon);
    }
    if (iconType == TouchIcon) {
        url.setPath("/apple-touch-icon.png");
        return IconURL::defaultIconURL(url, TouchIcon);
    }
#endif
    return IconURL();
}

}
<|endoftext|>