<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 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 "Xalan" 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/>.
 */

#include "FunctionNormalizeSpace.hpp"

#include <DOMSupport/DOMServices.hpp>

#include "XObjectFactory.hpp"

FunctionNormalizeSpace::FunctionNormalizeSpace()
{
}

FunctionNormalizeSpace::~FunctionNormalizeSpace()
{
}

XObjectPtr
FunctionNormalizeSpace::execute(
		XPathExecutionContext&	executionContext,
		XalanNode*				context)
{
	if (context == 0)
	{
		executionContext.error("The normalize-space() function requires a non-null context node!",
							   context);

		// Dummy return value...
		return XObjectPtr(0);
	}
	else
	{
		// The XPath standard says that if there are no arguments,
		// the default is to turn the context node into a string value.
		// DOMServices::getNodeData() will give us the data.

		// Get a cached string...
		XPathExecutionContext::GetAndReleaseCachedString	theData(executionContext);

		XalanDOMString&		theString = theData.get();

		DOMServices::getNodeData(*context, theString);

		return normalize(executionContext, theString);
	}
}

XObjectPtr
FunctionNormalizeSpace::execute(
		XPathExecutionContext&	executionContext,
		XalanNode*				/* context */,
		const XObjectPtr		arg1)
{
	assert(arg1.null() == false);

	return normalize(executionContext, arg1);
}

XObjectPtr
FunctionNormalizeSpace::execute(
			XPathExecutionContext&	executionContext,
			XalanNode*				context,
			const XObjectPtr		/* arg1 */,
			const XObjectPtr		/* arg2 */)
{
	executionContext.error(getError(), context);

	return XObjectPtr(0);
}

XObjectPtr
FunctionNormalizeSpace::execute(
			XPathExecutionContext&	executionContext,
			XalanNode*				context,
			const XObjectPtr		/* arg1 */,
			const XObjectPtr		/* arg2 */,
			const XObjectPtr		/* arg3 */)
{
	executionContext.error(getError(), context);

	return XObjectPtr(0);
}

XObjectPtr
FunctionNormalizeSpace::execute(
			XPathExecutionContext&			executionContext,
			XalanNode*						context,
			int								/* opPos */,
			const XObjectArgVectorType&		/* args */)
{
	executionContext.error(getError(), context);

	return XObjectPtr(0);
}

XObjectPtr
FunctionNormalizeSpace::normalize(
		XPathExecutionContext&	executionContext,
		const XalanDOMString&	theString) const
{
	const unsigned int	theStringLength = length(theString);

	// A string contain the result...
	XPathExecutionContext::GetAndReleaseCachedString	theResult(executionContext);

	XalanDOMString&		theNewString = theResult.get();
	assert(length(theNewString) == 0);

	// The result string can only be as large as the source string, so
	// just reserve the space now.
	reserve(theNewString, theStringLength);

	bool	fPreviousIsSpace = false;

	// OK, strip out any multiple spaces...
	for (unsigned int i = 0; i < theStringLength; i++)
	{
		const XalanDOMChar	theCurrentChar = charAt(theString, i);

		if (isXMLWhitespace(theCurrentChar) == true)
		{
			// If the previous character wasn't a space, and we've
			// encountered some non-space characters, and it's not
			// the last character in the string, then push the
			// space character (not the original character).
			if (fPreviousIsSpace == false)
			{
				if (length(theNewString) > 0 &&
					i < theStringLength - 1)
				{
					append(theNewString, XalanDOMChar(XalanUnicode::charSpace));
				}

				fPreviousIsSpace = true;
			}
		}
		else
		{
			append(theNewString, theCurrentChar);

			fPreviousIsSpace = false;
		}
	}

	const unsigned int	theNewStringLength = length(theNewString);

	if (theNewStringLength == 0)
	{
		return executionContext.getXObjectFactory().createString(XalanDOMString());
	}
	else
	{
		// We may have a space character at end, since we don't look ahead,
		// so removed it now...
		if (charAt(theNewString, theNewStringLength - 1) ==
				XalanDOMChar(XalanUnicode::charSpace))
		{
			theNewString.erase(theNewStringLength - 1, 1);
		}

		return executionContext.getXObjectFactory().createString(theResult);
	}
}

XObjectPtr
FunctionNormalizeSpace::normalize(
		XPathExecutionContext&	executionContext,
		const XObjectPtr&		theArg) const
{
	const XalanDOMString&	theString = theArg->str();

	if (needsNormalization(theString) == false)
	{
		return theArg;
	}
	else
	{
		return normalize(executionContext, theString);
	}
}

#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)
Function*
#else
FunctionNormalizeSpace*
#endif
FunctionNormalizeSpace::clone() const
{
	return new FunctionNormalizeSpace(*this);
}

const XalanDOMString
FunctionNormalizeSpace::getError() const
{
	return XALAN_STATIC_UCODE_STRING("The normalize-space() function takes zero arguments or one argument!");
}

bool
FunctionNormalizeSpace::needsNormalization(const XalanDOMString&	theString) const
{
	const unsigned int	theStringLength = length(theString);

	bool	fNormalize = false;

	bool	fPreviousIsSpace = false;

	// OK, search for multiple spaces, or whitespace that is not the
	// space character...
	for (unsigned int i = 0; i < theStringLength && fNormalize == false; ++i)
	{
		const XalanDOMChar	theCurrentChar = charAt(theString, i);

		if (isXMLWhitespace(theCurrentChar) == false)
		{
			++i;

			fPreviousIsSpace = false;
		}
		else
		{
			if (i == 0 ||
				i == theStringLength - 1 ||
				theCurrentChar != XalanDOMChar(XalanUnicode::charSpace) ||
				fPreviousIsSpace == true)
			{
				fNormalize = true;
			}
			else
			{
				fPreviousIsSpace = true;

				++i;
			}
		}
	}

	return fNormalize;
}
<commit_msg>Fixed bug with incrementing loop variable.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 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 "Xalan" 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/>.
 */

#include "FunctionNormalizeSpace.hpp"

#include <DOMSupport/DOMServices.hpp>

#include "XObjectFactory.hpp"

FunctionNormalizeSpace::FunctionNormalizeSpace()
{
}

FunctionNormalizeSpace::~FunctionNormalizeSpace()
{
}

XObjectPtr
FunctionNormalizeSpace::execute(
		XPathExecutionContext&	executionContext,
		XalanNode*				context)
{
	if (context == 0)
	{
		executionContext.error("The normalize-space() function requires a non-null context node!",
							   context);

		// Dummy return value...
		return XObjectPtr(0);
	}
	else
	{
		// The XPath standard says that if there are no arguments,
		// the default is to turn the context node into a string value.
		// DOMServices::getNodeData() will give us the data.

		// Get a cached string...
		XPathExecutionContext::GetAndReleaseCachedString	theData(executionContext);

		XalanDOMString&		theString = theData.get();

		DOMServices::getNodeData(*context, theString);

		return normalize(executionContext, theString);
	}
}

XObjectPtr
FunctionNormalizeSpace::execute(
		XPathExecutionContext&	executionContext,
		XalanNode*				/* context */,
		const XObjectPtr		arg1)
{
	assert(arg1.null() == false);

	return normalize(executionContext, arg1);
}

XObjectPtr
FunctionNormalizeSpace::execute(
			XPathExecutionContext&	executionContext,
			XalanNode*				context,
			const XObjectPtr		/* arg1 */,
			const XObjectPtr		/* arg2 */)
{
	executionContext.error(getError(), context);

	return XObjectPtr(0);
}

XObjectPtr
FunctionNormalizeSpace::execute(
			XPathExecutionContext&	executionContext,
			XalanNode*				context,
			const XObjectPtr		/* arg1 */,
			const XObjectPtr		/* arg2 */,
			const XObjectPtr		/* arg3 */)
{
	executionContext.error(getError(), context);

	return XObjectPtr(0);
}

XObjectPtr
FunctionNormalizeSpace::execute(
			XPathExecutionContext&			executionContext,
			XalanNode*						context,
			int								/* opPos */,
			const XObjectArgVectorType&		/* args */)
{
	executionContext.error(getError(), context);

	return XObjectPtr(0);
}

XObjectPtr
FunctionNormalizeSpace::normalize(
		XPathExecutionContext&	executionContext,
		const XalanDOMString&	theString) const
{
	const unsigned int	theStringLength = length(theString);

	// A string contain the result...
	XPathExecutionContext::GetAndReleaseCachedString	theResult(executionContext);

	XalanDOMString&		theNewString = theResult.get();
	assert(length(theNewString) == 0);

	// The result string can only be as large as the source string, so
	// just reserve the space now.
	reserve(theNewString, theStringLength);

	bool	fPreviousIsSpace = false;

	// OK, strip out any multiple spaces...
	for (unsigned int i = 0; i < theStringLength; i++)
	{
		const XalanDOMChar	theCurrentChar = charAt(theString, i);

		if (isXMLWhitespace(theCurrentChar) == true)
		{
			// If the previous character wasn't a space, and we've
			// encountered some non-space characters, and it's not
			// the last character in the string, then push the
			// space character (not the original character).
			if (fPreviousIsSpace == false)
			{
				if (length(theNewString) > 0 &&
					i < theStringLength - 1)
				{
					append(theNewString, XalanDOMChar(XalanUnicode::charSpace));
				}

				fPreviousIsSpace = true;
			}
		}
		else
		{
			append(theNewString, theCurrentChar);

			fPreviousIsSpace = false;
		}
	}

	const unsigned int	theNewStringLength = length(theNewString);

	if (theNewStringLength == 0)
	{
		return executionContext.getXObjectFactory().createString(XalanDOMString());
	}
	else
	{
		// We may have a space character at end, since we don't look ahead,
		// so removed it now...
		if (charAt(theNewString, theNewStringLength - 1) ==
				XalanDOMChar(XalanUnicode::charSpace))
		{
			theNewString.erase(theNewStringLength - 1, 1);
		}

		return executionContext.getXObjectFactory().createString(theResult);
	}
}

XObjectPtr
FunctionNormalizeSpace::normalize(
		XPathExecutionContext&	executionContext,
		const XObjectPtr&		theArg) const
{
	const XalanDOMString&	theString = theArg->str();

	if (needsNormalization(theString) == false)
	{
		return theArg;
	}
	else
	{
		return normalize(executionContext, theString);
	}
}

#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)
Function*
#else
FunctionNormalizeSpace*
#endif
FunctionNormalizeSpace::clone() const
{
	return new FunctionNormalizeSpace(*this);
}

const XalanDOMString
FunctionNormalizeSpace::getError() const
{
	return XALAN_STATIC_UCODE_STRING("The normalize-space() function takes zero arguments or one argument!");
}

bool
FunctionNormalizeSpace::needsNormalization(const XalanDOMString&	theString) const
{
	const unsigned int	theStringLength = length(theString);

	bool	fNormalize = false;

	bool	fPreviousIsSpace = false;

	// OK, search for multiple spaces, or whitespace that is not the
	// space character...
	for (unsigned int i = 0; i < theStringLength && fNormalize == false; ++i)
	{
		const XalanDOMChar	theCurrentChar = charAt(theString, i);

		if (isXMLWhitespace(theCurrentChar) == false)
		{
			fPreviousIsSpace = false;
		}
		else
		{
			if (i == 0 ||
				i == theStringLength - 1 ||
				theCurrentChar != XalanDOMChar(XalanUnicode::charSpace) ||
				fPreviousIsSpace == true)
			{
				fNormalize = true;
			}
			else
			{
				fPreviousIsSpace = true;
			}
		}
	}

	return fNormalize;
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 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 "Xalan" 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/>.
 *
 * @author David N. Bertoni
 */

#include "XPathEnvSupportDefault.hpp"

#include <algorithm>

#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#else
#include <iostream>
#endif

#include <Include/STLHelper.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>

#include <DOMSupport/DOMServices.hpp>

#include "XObject.hpp"
#include "XObjectFactory.hpp"
#include "XPath.hpp"
#include "XPathExecutionContext.hpp"

#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::endl;
using std::for_each;
#endif

XPathEnvSupportDefault::NamespaceFunctionTablesType		XPathEnvSupportDefault::s_externalFunctions;

void
XPathEnvSupportDefault::initialize()
{
}

void
XPathEnvSupportDefault::terminate()
{
	// Clean up the extension namespaces vector
	for_each(s_externalFunctions.begin(),
			 s_externalFunctions.end(),
			 NamespaceFunctionTableDeleteFunctor());

	NamespaceFunctionTablesType().swap(s_externalFunctions);
}

XPathEnvSupportDefault::XPathEnvSupportDefault() :
	XPathEnvSupport(),
	m_sourceDocs(),
	m_externalFunctions()
{
}

XPathEnvSupportDefault::~XPathEnvSupportDefault()
{
	// Clean up the extension namespaces vector
	for_each(m_externalFunctions.begin(),
			 m_externalFunctions.end(),
			 NamespaceFunctionTableDeleteFunctor());

	NamespaceFunctionTablesType().swap(m_externalFunctions);
}

void
XPathEnvSupportDefault::updateFunctionTable(
			NamespaceFunctionTablesType&	theTable,
			const XalanDOMString&			theNamespace,
			const XalanDOMString&			functionName,
			const Function*					function)
{
	// See if there's a table for that namespace...
	const NamespaceFunctionTablesType::iterator		i =
		theTable.find(theNamespace);

	if (i == theTable.end())
	{
		// The namespace was not found.  If function is not
		// 0, then add a clone of the function.
		if (function != 0)
		{
			theTable[theNamespace][functionName] =
				function->clone();
		}
	}
	else
	{
		// There is already a table for the namespace,
		// so look for the function...
		const FunctionTableType::iterator	j =
			(*i).second.find(functionName);

		if (j == (*i).second.end())
		{
			// The function was not found.  If function is not
			// 0, then add a clone of the function.
			if (function != 0)
			{
				(*i).second[functionName] = function->clone();
			}
		}
		else
		{
			// Found it, so delete the function...
#if defined(XALAN_CANNOT_DELETE_CONST)
			delete (Function*)(*j).second;
#else
			delete (*j).second;
#endif

			// If function is not 0, then we update
			// the entry.  Otherwise, we erase it...
			if (function != 0)
			{
				// Update it...
				(*j).second = function->clone();
			}
			else
			{
				// Erase it...
				(*i).second.erase(j);
			}
		}
	}
}

void
XPathEnvSupportDefault::installExternalFunctionGlobal(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	functionName,
			const Function&			function)
{
	updateFunctionTable(s_externalFunctions, theNamespace, functionName, &function);
}

void
XPathEnvSupportDefault::uninstallExternalFunctionGlobal(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	functionName)
{
	updateFunctionTable(s_externalFunctions, theNamespace, functionName, 0);
}

void
XPathEnvSupportDefault::installExternalFunctionLocal(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	functionName,
			const Function&			function)
{
	updateFunctionTable(m_externalFunctions, theNamespace, functionName, &function);
}

void
XPathEnvSupportDefault::uninstallExternalFunctionLocal(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	functionName)
{
	updateFunctionTable(m_externalFunctions, theNamespace, functionName, 0);
}

void
XPathEnvSupportDefault::reset()
{
	m_sourceDocs.clear();
}

XalanDocument*
XPathEnvSupportDefault::parseXML(
			const XalanDOMString&	/* urlString */,
			const XalanDOMString&	/* base */)
{
	return 0;
}

XalanDocument*
XPathEnvSupportDefault::getSourceDocument(const XalanDOMString&		theURI) const
{
	const SourceDocsTableType::const_iterator	i =
			m_sourceDocs.find(theURI);

	if (i == m_sourceDocs.end())
	{
		return 0;
	}
	else
	{
		return (*i).second;
	}
}

void
XPathEnvSupportDefault::setSourceDocument(
			const XalanDOMString&	theURI,
			XalanDocument*			theDocument)
{
	m_sourceDocs[theURI] = theDocument;
}

XalanDOMString
XPathEnvSupportDefault::findURIFromDoc(const XalanDocument*		owner) const
{
	SourceDocsTableType::const_iterator	i =
			m_sourceDocs.begin();

	bool	fFound = false;

	while(i != m_sourceDocs.end() && fFound == false)
	{
		if ((*i).second == owner)
		{
			fFound = true;
		}
		else
		{
			++i;
		}
	}

	return fFound == false ? XalanDOMString() : (*i).first;
}

bool
XPathEnvSupportDefault::elementAvailable(
			const XalanDOMString&	/* theNamespace */,
			const XalanDOMString&	/* elementName */) const
{
	return false;
}

bool
XPathEnvSupportDefault::functionAvailable(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	functionName) const
{
	bool	theResult = false;

	// Any function without a namespace prefix is considered
	// to be an intrinsic function.
	if (isEmpty(theNamespace) == true)
	{
		theResult = XPath::isInstalledFunction(functionName);
	}
	else
	{
		const Function* const	theFunction =
			findFunction(
				theNamespace,
				functionName);

		if (theFunction != 0)
		{
			theResult = true;
		}
	}

	return theResult;
}

const Function*
XPathEnvSupportDefault::findFunction(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	functionName) const
{
	// First, look locally...
	const Function*		theFunction = findFunction(
			m_externalFunctions,
			theNamespace,
			functionName);

	if (theFunction == 0)
	{
		// Not found, so look in the global space...
		theFunction = findFunction(
			s_externalFunctions,
			theNamespace,
			functionName);
	}

	return theFunction;
}

const Function*
XPathEnvSupportDefault::findFunction(
			const NamespaceFunctionTablesType&	theTable,
			const XalanDOMString&				theNamespace,
			const XalanDOMString&				functionName) const
{
	const Function*	theFunction = 0;

	// See if there's a table for that namespace...
	const NamespaceFunctionTablesType::const_iterator	i =
		theTable.find(theNamespace);

	if (i != theTable.end())
	{
		// There is a table for the namespace,
		// so look for the function...
		const FunctionTableType::const_iterator		j =
			(*i).second.find(functionName);

		if (j != (*i).second.end())
		{
			// Found the function...
			assert((*j).second != 0);

			theFunction = (*j).second;
		}
	}

	return theFunction;
}

XObjectPtr
XPathEnvSupportDefault::extFunction(
			XPathExecutionContext&			executionContext,
			const XalanDOMString&			theNamespace,
			const XalanDOMString&			functionName,
			XalanNode*						context,
			const XObjectArgVectorType&		argVec,
			const Locator*					locator) const
{
	const Function* const	theFunction = findFunction(theNamespace, functionName);

	if (theFunction != 0)
	{
		return theFunction->execute(
					executionContext,
					context,
					argVec,
					locator);
	}
	else
	{
		XalanDOMString	theFunctionName;

		if(length(theNamespace) > 0)
		{
			theFunctionName += theNamespace;
			theFunctionName += DOMServices::s_XMLNamespaceSeparatorString;
		}

		theFunctionName += functionName;

		throw XPathExceptionFunctionNotAvailable(theFunctionName);

		// dummy return value...
		return XObjectPtr();
	}
}

bool
XPathEnvSupportDefault::problem(
			eSource					/* where */,
			eClassification			classification,
			const XalanNode*		/* styleNode */,
			const XalanNode*		/* sourceNode */,
			const XalanDOMString&	msg,
			const XalanDOMChar*		uri,
			int						lineNo,
			int						charOffset) const
{
	cerr << msg;

	if (uri != 0)
	{
		cerr << ",in " << uri;
	}

	cerr << ", at line number "
		 << lineNo
		 << " at offset "
		 << charOffset
		 << endl;

	return classification == XPathEnvSupport::eError ? true : false;
}

bool
XPathEnvSupportDefault::problem(
			eSource					/* where */,
			eClassification			classification,
			const PrefixResolver*	/* resolver */,
			const XalanNode*		/* sourceNode */,
			const XalanDOMString&	msg,
			const XalanDOMChar*		uri,
			int						lineNo,
			int						charOffset) const
{
	cerr << msg;

	if (uri != 0)
	{
		cerr << ",in " << uri;
	}

	cerr << ", at line number "
		 << lineNo
		 << " at offset "
		 << charOffset
		 << endl;

	return classification == XPathEnvSupport::eError ? true : false;
}

void
XPathEnvSupportDefault::NamespaceFunctionTableDeleteFunctor::operator()(const NamespaceFunctionTablesInnerType::value_type&	thePair) const
{
	// Clean up the extension namespaces vector
	for_each(thePair.second.begin(),
			 thePair.second.end(),
			 MapValueDeleteFunctor<FunctionTableInnerType>());
}
<commit_msg>Don't use MapValueDeleteFunctor on certain platforms.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 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 "Xalan" 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/>.
 *
 * @author David N. Bertoni
 */

#include "XPathEnvSupportDefault.hpp"

#include <algorithm>

#if defined(XALAN_OLD_STREAM_HEADERS)
#include <iostream.h>
#else
#include <iostream>
#endif

#include <Include/STLHelper.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>

#include <DOMSupport/DOMServices.hpp>

#include "XObject.hpp"
#include "XObjectFactory.hpp"
#include "XPath.hpp"
#include "XPathExecutionContext.hpp"

#if !defined(XALAN_NO_NAMESPACES)
using std::cerr;
using std::endl;
using std::for_each;
#endif

XPathEnvSupportDefault::NamespaceFunctionTablesType		XPathEnvSupportDefault::s_externalFunctions;

void
XPathEnvSupportDefault::initialize()
{
}

void
XPathEnvSupportDefault::terminate()
{
	// Clean up the extension namespaces vector
	for_each(s_externalFunctions.begin(),
			 s_externalFunctions.end(),
			 NamespaceFunctionTableDeleteFunctor());

	NamespaceFunctionTablesType().swap(s_externalFunctions);
}

XPathEnvSupportDefault::XPathEnvSupportDefault() :
	XPathEnvSupport(),
	m_sourceDocs(),
	m_externalFunctions()
{
}

XPathEnvSupportDefault::~XPathEnvSupportDefault()
{
	// Clean up the extension namespaces vector
	for_each(m_externalFunctions.begin(),
			 m_externalFunctions.end(),
			 NamespaceFunctionTableDeleteFunctor());

	NamespaceFunctionTablesType().swap(m_externalFunctions);
}

void
XPathEnvSupportDefault::updateFunctionTable(
			NamespaceFunctionTablesType&	theTable,
			const XalanDOMString&			theNamespace,
			const XalanDOMString&			functionName,
			const Function*					function)
{
	// See if there's a table for that namespace...
	const NamespaceFunctionTablesType::iterator		i =
		theTable.find(theNamespace);

	if (i == theTable.end())
	{
		// The namespace was not found.  If function is not
		// 0, then add a clone of the function.
		if (function != 0)
		{
			theTable[theNamespace][functionName] =
				function->clone();
		}
	}
	else
	{
		// There is already a table for the namespace,
		// so look for the function...
		const FunctionTableType::iterator	j =
			(*i).second.find(functionName);

		if (j == (*i).second.end())
		{
			// The function was not found.  If function is not
			// 0, then add a clone of the function.
			if (function != 0)
			{
				(*i).second[functionName] = function->clone();
			}
		}
		else
		{
			// Found it, so delete the function...
#if defined(XALAN_CANNOT_DELETE_CONST)
			delete (Function*)(*j).second;
#else
			delete (*j).second;
#endif

			// If function is not 0, then we update
			// the entry.  Otherwise, we erase it...
			if (function != 0)
			{
				// Update it...
				(*j).second = function->clone();
			}
			else
			{
				// Erase it...
				(*i).second.erase(j);
			}
		}
	}
}

void
XPathEnvSupportDefault::installExternalFunctionGlobal(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	functionName,
			const Function&			function)
{
	updateFunctionTable(s_externalFunctions, theNamespace, functionName, &function);
}

void
XPathEnvSupportDefault::uninstallExternalFunctionGlobal(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	functionName)
{
	updateFunctionTable(s_externalFunctions, theNamespace, functionName, 0);
}

void
XPathEnvSupportDefault::installExternalFunctionLocal(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	functionName,
			const Function&			function)
{
	updateFunctionTable(m_externalFunctions, theNamespace, functionName, &function);
}

void
XPathEnvSupportDefault::uninstallExternalFunctionLocal(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	functionName)
{
	updateFunctionTable(m_externalFunctions, theNamespace, functionName, 0);
}

void
XPathEnvSupportDefault::reset()
{
	m_sourceDocs.clear();
}

XalanDocument*
XPathEnvSupportDefault::parseXML(
			const XalanDOMString&	/* urlString */,
			const XalanDOMString&	/* base */)
{
	return 0;
}

XalanDocument*
XPathEnvSupportDefault::getSourceDocument(const XalanDOMString&		theURI) const
{
	const SourceDocsTableType::const_iterator	i =
			m_sourceDocs.find(theURI);

	if (i == m_sourceDocs.end())
	{
		return 0;
	}
	else
	{
		return (*i).second;
	}
}

void
XPathEnvSupportDefault::setSourceDocument(
			const XalanDOMString&	theURI,
			XalanDocument*			theDocument)
{
	m_sourceDocs[theURI] = theDocument;
}

XalanDOMString
XPathEnvSupportDefault::findURIFromDoc(const XalanDocument*		owner) const
{
	SourceDocsTableType::const_iterator	i =
			m_sourceDocs.begin();

	bool	fFound = false;

	while(i != m_sourceDocs.end() && fFound == false)
	{
		if ((*i).second == owner)
		{
			fFound = true;
		}
		else
		{
			++i;
		}
	}

	return fFound == false ? XalanDOMString() : (*i).first;
}

bool
XPathEnvSupportDefault::elementAvailable(
			const XalanDOMString&	/* theNamespace */,
			const XalanDOMString&	/* elementName */) const
{
	return false;
}

bool
XPathEnvSupportDefault::functionAvailable(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	functionName) const
{
	bool	theResult = false;

	// Any function without a namespace prefix is considered
	// to be an intrinsic function.
	if (isEmpty(theNamespace) == true)
	{
		theResult = XPath::isInstalledFunction(functionName);
	}
	else
	{
		const Function* const	theFunction =
			findFunction(
				theNamespace,
				functionName);

		if (theFunction != 0)
		{
			theResult = true;
		}
	}

	return theResult;
}

const Function*
XPathEnvSupportDefault::findFunction(
			const XalanDOMString&	theNamespace,
			const XalanDOMString&	functionName) const
{
	// First, look locally...
	const Function*		theFunction = findFunction(
			m_externalFunctions,
			theNamespace,
			functionName);

	if (theFunction == 0)
	{
		// Not found, so look in the global space...
		theFunction = findFunction(
			s_externalFunctions,
			theNamespace,
			functionName);
	}

	return theFunction;
}

const Function*
XPathEnvSupportDefault::findFunction(
			const NamespaceFunctionTablesType&	theTable,
			const XalanDOMString&				theNamespace,
			const XalanDOMString&				functionName) const
{
	const Function*	theFunction = 0;

	// See if there's a table for that namespace...
	const NamespaceFunctionTablesType::const_iterator	i =
		theTable.find(theNamespace);

	if (i != theTable.end())
	{
		// There is a table for the namespace,
		// so look for the function...
		const FunctionTableType::const_iterator		j =
			(*i).second.find(functionName);

		if (j != (*i).second.end())
		{
			// Found the function...
			assert((*j).second != 0);

			theFunction = (*j).second;
		}
	}

	return theFunction;
}

XObjectPtr
XPathEnvSupportDefault::extFunction(
			XPathExecutionContext&			executionContext,
			const XalanDOMString&			theNamespace,
			const XalanDOMString&			functionName,
			XalanNode*						context,
			const XObjectArgVectorType&		argVec,
			const Locator*					locator) const
{
	const Function* const	theFunction = findFunction(theNamespace, functionName);

	if (theFunction != 0)
	{
		return theFunction->execute(
					executionContext,
					context,
					argVec,
					locator);
	}
	else
	{
		XalanDOMString	theFunctionName;

		if(length(theNamespace) > 0)
		{
			theFunctionName += theNamespace;
			theFunctionName += DOMServices::s_XMLNamespaceSeparatorString;
		}

		theFunctionName += functionName;

		throw XPathExceptionFunctionNotAvailable(theFunctionName);

		// dummy return value...
		return XObjectPtr();
	}
}

bool
XPathEnvSupportDefault::problem(
			eSource					/* where */,
			eClassification			classification,
			const XalanNode*		/* styleNode */,
			const XalanNode*		/* sourceNode */,
			const XalanDOMString&	msg,
			const XalanDOMChar*		uri,
			int						lineNo,
			int						charOffset) const
{
	cerr << msg;

	if (uri != 0)
	{
		cerr << ",in " << uri;
	}

	cerr << ", at line number "
		 << lineNo
		 << " at offset "
		 << charOffset
		 << endl;

	return classification == XPathEnvSupport::eError ? true : false;
}

bool
XPathEnvSupportDefault::problem(
			eSource					/* where */,
			eClassification			classification,
			const PrefixResolver*	/* resolver */,
			const XalanNode*		/* sourceNode */,
			const XalanDOMString&	msg,
			const XalanDOMChar*		uri,
			int						lineNo,
			int						charOffset) const
{
	cerr << msg;

	if (uri != 0)
	{
		cerr << ",in " << uri;
	}

	cerr << ", at line number "
		 << lineNo
		 << " at offset "
		 << charOffset
		 << endl;

	return classification == XPathEnvSupport::eError ? true : false;
}

void
XPathEnvSupportDefault::NamespaceFunctionTableDeleteFunctor::operator()(const NamespaceFunctionTablesInnerType::value_type&	thePair) const
{
#if defined(XALAN_CANNOT_DELETE_CONST)
	FunctionTableInnerType::const_iterator	i = thePair.second.begin();

	while(i != thePair.second.end())
	{
		delete (Function*) (*i).second;

		++i;
	}
#else
	// Clean up the extension namespaces vector
	for_each(thePair.second.begin(),
			 thePair.second.end(),
			 MapValueDeleteFunctor<FunctionTableInnerType>());
#endif
}
<|endoftext|>


<commit_before>/******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * 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.
**   * Neither the name of the chemkit project 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 THE COPYRIGHT HOLDERS AND 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 THE COPYRIGHT
** OWNER OR 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 "bondtest.h"

#include <chemkit/chemkit.h>
#include <chemkit/molecule.h>
#include <chemkit/lineformat.h>

void BondTest::atoms()
{
    chemkit::Molecule molecule;
    chemkit::Atom *H1 = molecule.addAtom("H");
    chemkit::Atom *H2 = molecule.addAtom("H");
    chemkit::Bond *bond = molecule.addBond(H1, H2);
    QVERIFY(bond->atom1() == H1);
    QVERIFY(bond->atom2() == H2);
    QCOMPARE(bond->atoms().size(), 2UL);
    QVERIFY(bond->atoms()[0] == H1);
    QVERIFY(bond->atoms()[1] == H2);
}

void BondTest::otherAtom()
{
    chemkit::Molecule molecule;
    chemkit::Atom *H1 = molecule.addAtom("H");
    chemkit::Atom *H2 = molecule.addAtom("H");
    chemkit::Bond *bond = molecule.addBond(H1, H2);
    QVERIFY(bond->otherAtom(H1) == H2);
    QVERIFY(bond->otherAtom(H2) == H1);
}

void BondTest::order()
{
    chemkit::Molecule molecule;
    chemkit::Atom *H1 = molecule.addAtom("H");
    chemkit::Atom *H2 = molecule.addAtom("H");
    chemkit::Bond *bond = molecule.addBond(H1, H2);
    QCOMPARE(bond->order(), 1);

    bond->setOrder(chemkit::Bond::Double);
    QCOMPARE(bond->order(), 2);

    bond->setOrder(chemkit::Bond::Triple);
    QCOMPARE(bond->order(), 3);

    bond->setOrder(chemkit::Bond::Single);
    QCOMPARE(bond->order(), 1);
}

void BondTest::molecule()
{
    chemkit::Molecule molecule;
    chemkit::Atom *H1 = molecule.addAtom("H");
    chemkit::Atom *H2 = molecule.addAtom("H");
    chemkit::Bond *bond = molecule.addBond(H1, H2);
    QVERIFY(bond->molecule() == &molecule);
}

void BondTest::residue()
{
}

void BondTest::contains()
{
    chemkit::Molecule molecule;
    chemkit::Atom *hydrogen = molecule.addAtom("H");
    chemkit::Atom *carbon = molecule.addAtom("C");
    chemkit::Bond *bond = molecule.addBond(hydrogen, carbon);
    QCOMPARE(bond->contains(hydrogen), true);
    QCOMPARE(bond->contains(carbon), true);
    QCOMPARE(bond->contains(chemkit::Atom::Hydrogen), true);
    QCOMPARE(bond->contains(chemkit::Atom::Carbon), true);
    QCOMPARE(bond->contains(chemkit::Atom::Oxygen), false);

    chemkit::Atom *oxygen = molecule.addAtom("O");
    QCOMPARE(bond->contains(oxygen), false);

    chemkit::Atom *nitrogen = molecule.addAtom("N");
    QCOMPARE(bond->contains(nitrogen), false);
    QCOMPARE(bond->containsBoth(hydrogen, carbon), true);
    QCOMPARE(bond->containsBoth(carbon, hydrogen), true);
    QCOMPARE(bond->containsBoth(carbon, carbon), true);
    QCOMPARE(bond->containsBoth(hydrogen, hydrogen), true);
    QCOMPARE(bond->containsBoth(chemkit::Atom::Hydrogen, chemkit::Atom::Carbon), true);
    QCOMPARE(bond->containsBoth(chemkit::Atom::Carbon, chemkit::Atom::Hydrogen), true);
    QCOMPARE(bond->containsBoth(chemkit::Atom::Carbon, chemkit::Atom::Carbon), false);
    QCOMPARE(bond->containsBoth(chemkit::Atom::Oxygen, chemkit::Atom::Oxygen), false);
    QCOMPARE(bond->containsBoth(carbon, oxygen), false);
    QCOMPARE(bond->containsBoth(carbon, nitrogen), false);
    QCOMPARE(bond->containsBoth(oxygen, nitrogen), false);
}

void BondTest::isTerminal()
{
    chemkit::Molecule molecule;
    chemkit::Atom *C1 = molecule.addAtom("C");
    chemkit::Atom *C2 = molecule.addAtom("C");
    chemkit::Atom *C3 = molecule.addAtom("C");
    chemkit::Atom *C4 = molecule.addAtom("C");
    chemkit::Bond *C1_C2 = molecule.addBond(C1, C2);
    chemkit::Bond *C2_C3 = molecule.addBond(C2, C3);
    chemkit::Bond *C3_C4 = molecule.addBond(C3, C4);
    QCOMPARE(C1_C2->isTerminal(), true);
    QCOMPARE(C2_C3->isTerminal(), false);
    QCOMPARE(C3_C4->isTerminal(), true);
}

void BondTest::rings()
{
    chemkit::Molecule benzene("InChI=1/C6H6/c1-2-4-6-5-3-1/h1-6H", "inchi");
    QCOMPARE(benzene.formula(), std::string("C6H6"));
    QCOMPARE(benzene.ringCount(), 1);
    chemkit::Ring *benzeneRing = benzene.rings()[0];

    foreach(chemkit::Bond *bond, benzene.bonds()){
        if(bond->contains(chemkit::Atom::Hydrogen)){
            QCOMPARE(bond->ringCount(), 0);
            QCOMPARE(bond->isInRing(), false);
            QCOMPARE(bond->isInRing(6), false);
            QCOMPARE(bond->isInRing(5), false);
            QCOMPARE(bond->isAromatic(), false);
            QVERIFY(bond->smallestRing() == 0);
        }
        else{
            QCOMPARE(bond->ringCount(), 1);
            QCOMPARE(bond->isInRing(), true);
            QCOMPARE(bond->isInRing(6), true);
            QCOMPARE(bond->isInRing(5), false);
            QCOMPARE(bond->isAromatic(), true);
            QVERIFY(bond->smallestRing() == benzeneRing);
        }
    }
}

void BondTest::polarity()
{
    chemkit::Molecule molecule;
    chemkit::Atom *hydrogen = molecule.addAtom("H");
    chemkit::Atom *carbon = molecule.addAtom("C");
    chemkit::Bond *bond = molecule.addBond(hydrogen, carbon);
    QCOMPARE(qRound(bond->polarity()), 0);

    chemkit::Atom *oxygen = molecule.addAtom("O");
    bond = molecule.addBond(hydrogen, oxygen);
    QCOMPARE(qRound(bond->polarity()), 1);

    chemkit::Atom *sodium = molecule.addAtom("Na");
    chemkit::Atom *fluorine = molecule.addAtom("F");
    bond = molecule.addBond(sodium, fluorine);
    QCOMPARE(qRound(bond->polarity()), 3);

    chemkit::Atom *helium1 = molecule.addAtom("He");
    chemkit::Atom *helium2 = molecule.addAtom("He");
    bond = molecule.addBond(helium1, helium2);
    QCOMPARE(qRound(bond->polarity()), 0);
}

void BondTest::length()
{
    chemkit::Molecule molecule;
    chemkit::Atom *H1 = molecule.addAtom("H");
    chemkit::Atom *H2 = molecule.addAtom("H");
    chemkit::Bond *bond = molecule.addBond(H1, H2);
    QCOMPARE(bond->length(), chemkit::Float(0.0));

    H1->moveTo(0, 1, 0);
    QCOMPARE(bond->length(), chemkit::Float(1.0));

    H2->moveTo(0, -3, 0);
    QCOMPARE(bond->length(), chemkit::Float(4.0));
}

QTEST_APPLESS_MAIN(BondTest)
<commit_msg>Fix compilation error in BondTest<commit_after>/******************************************************************************
**
** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com>
** All rights reserved.
**
** This file is a part of the chemkit project. For more information
** see <http://www.chemkit.org>.
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions
** are met:
**
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * 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.
**   * Neither the name of the chemkit project 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 THE COPYRIGHT HOLDERS AND 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 THE COPYRIGHT
** OWNER OR 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 "bondtest.h"

#include <chemkit/chemkit.h>
#include <chemkit/molecule.h>
#include <chemkit/lineformat.h>

void BondTest::atoms()
{
    chemkit::Molecule molecule;
    chemkit::Atom *H1 = molecule.addAtom("H");
    chemkit::Atom *H2 = molecule.addAtom("H");
    chemkit::Bond *bond = molecule.addBond(H1, H2);
    QVERIFY(bond->atom1() == H1);
    QVERIFY(bond->atom2() == H2);
    QCOMPARE(bond->atoms().size(), size_t(2));
    QVERIFY(bond->atoms()[0] == H1);
    QVERIFY(bond->atoms()[1] == H2);
}

void BondTest::otherAtom()
{
    chemkit::Molecule molecule;
    chemkit::Atom *H1 = molecule.addAtom("H");
    chemkit::Atom *H2 = molecule.addAtom("H");
    chemkit::Bond *bond = molecule.addBond(H1, H2);
    QVERIFY(bond->otherAtom(H1) == H2);
    QVERIFY(bond->otherAtom(H2) == H1);
}

void BondTest::order()
{
    chemkit::Molecule molecule;
    chemkit::Atom *H1 = molecule.addAtom("H");
    chemkit::Atom *H2 = molecule.addAtom("H");
    chemkit::Bond *bond = molecule.addBond(H1, H2);
    QCOMPARE(bond->order(), 1);

    bond->setOrder(chemkit::Bond::Double);
    QCOMPARE(bond->order(), 2);

    bond->setOrder(chemkit::Bond::Triple);
    QCOMPARE(bond->order(), 3);

    bond->setOrder(chemkit::Bond::Single);
    QCOMPARE(bond->order(), 1);
}

void BondTest::molecule()
{
    chemkit::Molecule molecule;
    chemkit::Atom *H1 = molecule.addAtom("H");
    chemkit::Atom *H2 = molecule.addAtom("H");
    chemkit::Bond *bond = molecule.addBond(H1, H2);
    QVERIFY(bond->molecule() == &molecule);
}

void BondTest::residue()
{
}

void BondTest::contains()
{
    chemkit::Molecule molecule;
    chemkit::Atom *hydrogen = molecule.addAtom("H");
    chemkit::Atom *carbon = molecule.addAtom("C");
    chemkit::Bond *bond = molecule.addBond(hydrogen, carbon);
    QCOMPARE(bond->contains(hydrogen), true);
    QCOMPARE(bond->contains(carbon), true);
    QCOMPARE(bond->contains(chemkit::Atom::Hydrogen), true);
    QCOMPARE(bond->contains(chemkit::Atom::Carbon), true);
    QCOMPARE(bond->contains(chemkit::Atom::Oxygen), false);

    chemkit::Atom *oxygen = molecule.addAtom("O");
    QCOMPARE(bond->contains(oxygen), false);

    chemkit::Atom *nitrogen = molecule.addAtom("N");
    QCOMPARE(bond->contains(nitrogen), false);
    QCOMPARE(bond->containsBoth(hydrogen, carbon), true);
    QCOMPARE(bond->containsBoth(carbon, hydrogen), true);
    QCOMPARE(bond->containsBoth(carbon, carbon), true);
    QCOMPARE(bond->containsBoth(hydrogen, hydrogen), true);
    QCOMPARE(bond->containsBoth(chemkit::Atom::Hydrogen, chemkit::Atom::Carbon), true);
    QCOMPARE(bond->containsBoth(chemkit::Atom::Carbon, chemkit::Atom::Hydrogen), true);
    QCOMPARE(bond->containsBoth(chemkit::Atom::Carbon, chemkit::Atom::Carbon), false);
    QCOMPARE(bond->containsBoth(chemkit::Atom::Oxygen, chemkit::Atom::Oxygen), false);
    QCOMPARE(bond->containsBoth(carbon, oxygen), false);
    QCOMPARE(bond->containsBoth(carbon, nitrogen), false);
    QCOMPARE(bond->containsBoth(oxygen, nitrogen), false);
}

void BondTest::isTerminal()
{
    chemkit::Molecule molecule;
    chemkit::Atom *C1 = molecule.addAtom("C");
    chemkit::Atom *C2 = molecule.addAtom("C");
    chemkit::Atom *C3 = molecule.addAtom("C");
    chemkit::Atom *C4 = molecule.addAtom("C");
    chemkit::Bond *C1_C2 = molecule.addBond(C1, C2);
    chemkit::Bond *C2_C3 = molecule.addBond(C2, C3);
    chemkit::Bond *C3_C4 = molecule.addBond(C3, C4);
    QCOMPARE(C1_C2->isTerminal(), true);
    QCOMPARE(C2_C3->isTerminal(), false);
    QCOMPARE(C3_C4->isTerminal(), true);
}

void BondTest::rings()
{
    chemkit::Molecule benzene("InChI=1/C6H6/c1-2-4-6-5-3-1/h1-6H", "inchi");
    QCOMPARE(benzene.formula(), std::string("C6H6"));
    QCOMPARE(benzene.ringCount(), 1);
    chemkit::Ring *benzeneRing = benzene.rings()[0];

    foreach(chemkit::Bond *bond, benzene.bonds()){
        if(bond->contains(chemkit::Atom::Hydrogen)){
            QCOMPARE(bond->ringCount(), 0);
            QCOMPARE(bond->isInRing(), false);
            QCOMPARE(bond->isInRing(6), false);
            QCOMPARE(bond->isInRing(5), false);
            QCOMPARE(bond->isAromatic(), false);
            QVERIFY(bond->smallestRing() == 0);
        }
        else{
            QCOMPARE(bond->ringCount(), 1);
            QCOMPARE(bond->isInRing(), true);
            QCOMPARE(bond->isInRing(6), true);
            QCOMPARE(bond->isInRing(5), false);
            QCOMPARE(bond->isAromatic(), true);
            QVERIFY(bond->smallestRing() == benzeneRing);
        }
    }
}

void BondTest::polarity()
{
    chemkit::Molecule molecule;
    chemkit::Atom *hydrogen = molecule.addAtom("H");
    chemkit::Atom *carbon = molecule.addAtom("C");
    chemkit::Bond *bond = molecule.addBond(hydrogen, carbon);
    QCOMPARE(qRound(bond->polarity()), 0);

    chemkit::Atom *oxygen = molecule.addAtom("O");
    bond = molecule.addBond(hydrogen, oxygen);
    QCOMPARE(qRound(bond->polarity()), 1);

    chemkit::Atom *sodium = molecule.addAtom("Na");
    chemkit::Atom *fluorine = molecule.addAtom("F");
    bond = molecule.addBond(sodium, fluorine);
    QCOMPARE(qRound(bond->polarity()), 3);

    chemkit::Atom *helium1 = molecule.addAtom("He");
    chemkit::Atom *helium2 = molecule.addAtom("He");
    bond = molecule.addBond(helium1, helium2);
    QCOMPARE(qRound(bond->polarity()), 0);
}

void BondTest::length()
{
    chemkit::Molecule molecule;
    chemkit::Atom *H1 = molecule.addAtom("H");
    chemkit::Atom *H2 = molecule.addAtom("H");
    chemkit::Bond *bond = molecule.addBond(H1, H2);
    QCOMPARE(bond->length(), chemkit::Float(0.0));

    H1->moveTo(0, 1, 0);
    QCOMPARE(bond->length(), chemkit::Float(1.0));

    H2->moveTo(0, -3, 0);
    QCOMPARE(bond->length(), chemkit::Float(4.0));
}

QTEST_APPLESS_MAIN(BondTest)
<|endoftext|>


<commit_before>/**
 * The MIT License (MIT)
 *
 * Copyright © 2017-2018 Ruben Van Boxem
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 **/

/*
 * Color, stored as RGBA.
 */

#ifndef SKUI_GRAPHICS_COLOR_H
#define SKUI_GRAPHICS_COLOR_H

#include <cstdint>

namespace skui
{
  namespace graphics
  {
    class color
    {
    public:
      explicit constexpr color(std::uint8_t red,
                               std::uint8_t green,
                               std::uint8_t blue,
                               std::uint8_t alpha = 1)
        : alpha{alpha}
        , red{red}
        , green{green}
        , blue{blue}
      {}
      explicit constexpr color(std::uint32_t argb)
        : alpha{static_cast<std::uint8_t>(argb >> 24)}
        , red{static_cast<std::uint8_t>(argb >> 16)}
        , green{static_cast<std::uint8_t>(argb >> 8)}
        , blue{static_cast<std::uint8_t>(argb)}
      {}

      std::uint8_t alpha;
      std::uint8_t red;
      std::uint8_t green;
      std::uint8_t blue;
    };

    namespace colors
    {
      static constexpr color transparent {0, 0, 0, 0};

      static constexpr color alice_blue              {0xFFF0F8FF};
      static constexpr color antique_white           {0xFFFAEBD7};
      static constexpr color aqua                    {0XFF00FFFF};
      static constexpr color aquamarine              {0XFF7FFFD4};
      static constexpr color azure                   {0xFFF0FFFF};
      static constexpr color beige                   {0xFFF5F5DC};
      static constexpr color bisque                  {0xFFFFE4C4};
      static constexpr color black                   {0xFF000000};
      static constexpr color blanched_almond         {0xFFFFEBCD};
      static constexpr color blue                    {0xFF0000FF};
      static constexpr color blue_violet             {0xFF8A2BE2};
      static constexpr color brown                   {0xFFA52A2A};
      static constexpr color burly_wood              {0xFFDEB887};
      static constexpr color cadet_blue              {0xFF5F9EA0};
      static constexpr color chartreuse              {0xFF7FFF00};
      static constexpr color chocolate               {0xFFD2691E};
      static constexpr color coral                   {0xFFFF7F50};
      static constexpr color cornflower_blue         {0xFF6495ED};
      static constexpr color cornsilk                {0xFFFFF8DC};
      static constexpr color crimson                 {0xFFDC143C};
      static constexpr color cyan                    {0xFF00FFFF};
      static constexpr color dark_blue               {0xFF00008B};
      static constexpr color dark_cyan               {0xFF008B8B};
      static constexpr color dark_golden_rod         {0xFFB8860B};
      static constexpr color dark_gray               {0xFFA9A9A9};
      static constexpr color dark_grey               {0xFFA9A9A9};
      static constexpr color dark_green              {0xFF006400};
      static constexpr color dark_khaki              {0xFFBDB76B};
      static constexpr color dark_magenta            {0xFF8B008B};
      static constexpr color dark_olive_green        {0xFF556B2F};
      static constexpr color dark_orange             {0xFFFF8C00};
      static constexpr color dark_orchid             {0xFF9932CC};
      static constexpr color dark_red                {0xFF8B0000};
      static constexpr color dark_salmon             {0xFFE9967A};
      static constexpr color dark_sea_green          {0xFF8FBC8F};
      static constexpr color dark_slate_blue         {0xFF483D8B};
      static constexpr color dark_slate_gray         {0xFF2F4F4F};
      static constexpr color dark_slate_grey         {0xFF2F4F4F};
      static constexpr color dark_turquoise          {0xFF00CED1};
      static constexpr color dark_violet             {0xFF9400D3};
      static constexpr color deep_pink               {0xFFFF1493};
      static constexpr color deep_sky_blue           {0xFF00BFFF};
      static constexpr color dim_gray                {0xFF696969};
      static constexpr color dim_grey                {0xFF696969};
      static constexpr color dodger_blue             {0xFF1E90FF};
      static constexpr color fire_brick              {0xFFB22222};
      static constexpr color floral_white            {0xFFFFFAF0};
      static constexpr color forest_green            {0xFF228B22};
      static constexpr color fuchsia                 {0xFFFF00FF};
      static constexpr color gainsboro               {0xFFDCDCDC};
      static constexpr color ghost_white             {0xFFF8F8FF};
      static constexpr color gold                    {0xFFFFD700};
      static constexpr color golden_rod              {0xFFDAA520};
      static constexpr color gray                    {0xFF808080};
      static constexpr color grey                    {0xFF808080};
      static constexpr color green                   {0xFF008000};
      static constexpr color green_yellow            {0xFFADFF2F};
      static constexpr color honey_dew               {0xFFF0FFF0};
      static constexpr color hot_pink                {0xFFFF69B4};
      static constexpr color indian_red              {0xFFCD5C5C};
      static constexpr color indigo                  {0xFF4B0082};
      static constexpr color ivory                   {0xFFFFFFF0};
      static constexpr color khaki                   {0xFFF0E68C};
      static constexpr color lavender                {0xFFE6E6FA};
      static constexpr color lavender_blush          {0xFFFFF0F5};
      static constexpr color lawn_green              {0xFF7CFC00};
      static constexpr color lemon_chiffon           {0xFFFFFACD};
      static constexpr color light_blue              {0xFFADD8E6};
      static constexpr color light_coral             {0xFFF08080};
      static constexpr color light_cyan              {0xFFE0FFFF};
      static constexpr color light_golden_rod_yellow {0xFFFAFAD2};
      static constexpr color light_gray              {0xFFD3D3D3};
      static constexpr color light_grey              {0xFFD3D3D3};
      static constexpr color light_green             {0xFF90EE90};
      static constexpr color light_pink              {0xFFFFB6C1};
      static constexpr color light_salmon            {0xFFFFA07A};
      static constexpr color light_sea_green         {0xFF20B2AA};
      static constexpr color light_sky_blue          {0xFF87CEFA};
      static constexpr color light_slate_gray        {0xFF778899};
      static constexpr color light_slate_grey        {0xFF778899};
      static constexpr color light_steel_blue        {0xFFB0C4DE};
      static constexpr color light_yellow            {0xFFFFFFE0};
      static constexpr color lime                    {0xFF00FF00};
      static constexpr color lime_green              {0xFF32CD32};
      static constexpr color linen                   {0xFFFAF0E6};
      static constexpr color magenta                 {0xFFFF00FF};
      static constexpr color maroon                  {0xFF800000};
      static constexpr color medium_aqua_marine      {0xFF66CDAA};
      static constexpr color medium_blue             {0xFF0000CD};
      static constexpr color medium_orchid           {0XFFBA55D3};
      static constexpr color medium_purple           {0xFF9370DB};
      static constexpr color medium_sea_green        {0xFF3CB371};
      static constexpr color medium_slate_blue       {0xFF7B68EE};
      static constexpr color medium_spring_green     {0xFF00FA9A};
      static constexpr color medium_turqoise         {0xFF48D1CC};
      static constexpr color medium_violet_red       {0xFFC71585};
      static constexpr color midnight_blue           {0xFF191970};
      static constexpr color mint_cream              {0xFFF5FFFA};
      static constexpr color misty_rose              {0xFFFFE4E1};
      static constexpr color moccasin                {0xFFFFE4B5};
      static constexpr color navajo_white            {0xFFFFDEAD};
      static constexpr color navy                    {0xFF000080};
      static constexpr color old_lace                {0xFFFDF5E6};
      static constexpr color olive                   {0xFF808000};
      static constexpr color olive_drab              {0xFF6B8E23};
      static constexpr color orange                  {0xFFFFA500};
      static constexpr color orange_red              {0xFFFF4500};
      static constexpr color orchid                  {0xFFDA70D6};
      static constexpr color pale_golden_rod         {0xFFEEE8AA};
      static constexpr color pale_green              {0xFF98FB98};
      static constexpr color pale_turquoise          {0xFFAFEEEE};
      static constexpr color pale_violet_red         {0xFFDB7093};
      static constexpr color papaya_whip             {0xFFFFEFD5};
      static constexpr color peach_puff              {0xFFFFC0CB};
      static constexpr color peru                    {0xFFCD853F};
      static constexpr color pink                    {0xFFFFC0CB};
      static constexpr color plum                    {0xFFDDA0DD};
      static constexpr color powder_blue             {0xFFB0E0E6};
      static constexpr color purple                  {0xFF800080};
      static constexpr color rebecca_purple          {0xFF663399};
      static constexpr color red                     {0xFFFF0000};
      static constexpr color rosy_brown              {0xFFBC8F8F};
      static constexpr color royal_blue              {0xFF4169E1};
      static constexpr color saddle_brown            {0xFF8B4513};
      static constexpr color salmon                  {0xFFFA8072};
      static constexpr color sandy_brown             {0xFFF4A460};
      static constexpr color sea_green               {0xFF2E8B57};
      static constexpr color sea_shell               {0xFFFFF5EE};
      static constexpr color sienna                  {0xFFA0522D};
      static constexpr color silver                  {0xFFC0C0C0};
      static constexpr color sky_blue                {0xFF87CEEB};
      static constexpr color slate_blue              {0xFF6A5ACD};
      static constexpr color slate_gray              {0xFF708090};
      static constexpr color slate_grey              {0xFF708090};
      static constexpr color snow                    {0xFFFFFAFA};
      static constexpr color spring_green            {0xFF00FF7F};
      static constexpr color steel_blue              {0xFF4682B4};
      static constexpr color tan                     {0xFFD2B48C};
      static constexpr color teal                    {0xFF008080};
      static constexpr color thistle                 {0xFFD8BFD8};
      static constexpr color tomato                  {0xFFFF6347};
      static constexpr color turquoise               {0xFF40E0D0};
      static constexpr color violet                  {0xFFEE82EE};
      static constexpr color wheat                   {0xFFF5DEB3};
      static constexpr color white                   {0xFFFFFFFF};
      static constexpr color white_smoke             {0xFFF5F5F5};
      static constexpr color yellow                  {0xFFFFFF00};
      static constexpr color yellow_green            {0xFF9ACD32};
    }
  }
}

#endif
<commit_msg>Add graphics::color overload for std::ostream.<commit_after>/**
 * The MIT License (MIT)
 *
 * Copyright © 2017-2018 Ruben Van Boxem
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 **/

/*
 * Color, stored as RGBA.
 */

#ifndef SKUI_GRAPHICS_COLOR_H
#define SKUI_GRAPHICS_COLOR_H

#include <core/utility.h++>

#include <cstdint>

namespace skui
{
  namespace graphics
  {
    class color
    {
    public:
      explicit constexpr color(std::uint8_t red,
                               std::uint8_t green,
                               std::uint8_t blue,
                               std::uint8_t alpha = 1)
        : alpha{alpha}
        , red{red}
        , green{green}
        , blue{blue}
      {}
      explicit constexpr color(std::uint32_t argb)
        : alpha{static_cast<std::uint8_t>(argb >> 24)}
        , red{static_cast<std::uint8_t>(argb >> 16)}
        , green{static_cast<std::uint8_t>(argb >> 8)}
        , blue{static_cast<std::uint8_t>(argb)}
      {}

      explicit constexpr operator std::uint32_t() const
      {
        return static_cast<std::uint32_t>(alpha << 24 | red << 16 | green << 8 | blue);
      }

      std::uint8_t alpha;
      std::uint8_t red;
      std::uint8_t green;
      std::uint8_t blue;
    };

    inline std::ostream& operator<<(std::ostream& os, const color& color)
    {
      core::ostream_format_keeper keeper(os);

      return os << std::hex << std::uint32_t(color) << '\n';
    }

    namespace colors
    {
      static constexpr color transparent {0, 0, 0, 0};

      static constexpr color alice_blue              {0xFFF0F8FF};
      static constexpr color antique_white           {0xFFFAEBD7};
      static constexpr color aqua                    {0XFF00FFFF};
      static constexpr color aquamarine              {0XFF7FFFD4};
      static constexpr color azure                   {0xFFF0FFFF};
      static constexpr color beige                   {0xFFF5F5DC};
      static constexpr color bisque                  {0xFFFFE4C4};
      static constexpr color black                   {0xFF000000};
      static constexpr color blanched_almond         {0xFFFFEBCD};
      static constexpr color blue                    {0xFF0000FF};
      static constexpr color blue_violet             {0xFF8A2BE2};
      static constexpr color brown                   {0xFFA52A2A};
      static constexpr color burly_wood              {0xFFDEB887};
      static constexpr color cadet_blue              {0xFF5F9EA0};
      static constexpr color chartreuse              {0xFF7FFF00};
      static constexpr color chocolate               {0xFFD2691E};
      static constexpr color coral                   {0xFFFF7F50};
      static constexpr color cornflower_blue         {0xFF6495ED};
      static constexpr color cornsilk                {0xFFFFF8DC};
      static constexpr color crimson                 {0xFFDC143C};
      static constexpr color cyan                    {0xFF00FFFF};
      static constexpr color dark_blue               {0xFF00008B};
      static constexpr color dark_cyan               {0xFF008B8B};
      static constexpr color dark_golden_rod         {0xFFB8860B};
      static constexpr color dark_gray               {0xFFA9A9A9};
      static constexpr color dark_grey               {0xFFA9A9A9};
      static constexpr color dark_green              {0xFF006400};
      static constexpr color dark_khaki              {0xFFBDB76B};
      static constexpr color dark_magenta            {0xFF8B008B};
      static constexpr color dark_olive_green        {0xFF556B2F};
      static constexpr color dark_orange             {0xFFFF8C00};
      static constexpr color dark_orchid             {0xFF9932CC};
      static constexpr color dark_red                {0xFF8B0000};
      static constexpr color dark_salmon             {0xFFE9967A};
      static constexpr color dark_sea_green          {0xFF8FBC8F};
      static constexpr color dark_slate_blue         {0xFF483D8B};
      static constexpr color dark_slate_gray         {0xFF2F4F4F};
      static constexpr color dark_slate_grey         {0xFF2F4F4F};
      static constexpr color dark_turquoise          {0xFF00CED1};
      static constexpr color dark_violet             {0xFF9400D3};
      static constexpr color deep_pink               {0xFFFF1493};
      static constexpr color deep_sky_blue           {0xFF00BFFF};
      static constexpr color dim_gray                {0xFF696969};
      static constexpr color dim_grey                {0xFF696969};
      static constexpr color dodger_blue             {0xFF1E90FF};
      static constexpr color fire_brick              {0xFFB22222};
      static constexpr color floral_white            {0xFFFFFAF0};
      static constexpr color forest_green            {0xFF228B22};
      static constexpr color fuchsia                 {0xFFFF00FF};
      static constexpr color gainsboro               {0xFFDCDCDC};
      static constexpr color ghost_white             {0xFFF8F8FF};
      static constexpr color gold                    {0xFFFFD700};
      static constexpr color golden_rod              {0xFFDAA520};
      static constexpr color gray                    {0xFF808080};
      static constexpr color grey                    {0xFF808080};
      static constexpr color green                   {0xFF008000};
      static constexpr color green_yellow            {0xFFADFF2F};
      static constexpr color honey_dew               {0xFFF0FFF0};
      static constexpr color hot_pink                {0xFFFF69B4};
      static constexpr color indian_red              {0xFFCD5C5C};
      static constexpr color indigo                  {0xFF4B0082};
      static constexpr color ivory                   {0xFFFFFFF0};
      static constexpr color khaki                   {0xFFF0E68C};
      static constexpr color lavender                {0xFFE6E6FA};
      static constexpr color lavender_blush          {0xFFFFF0F5};
      static constexpr color lawn_green              {0xFF7CFC00};
      static constexpr color lemon_chiffon           {0xFFFFFACD};
      static constexpr color light_blue              {0xFFADD8E6};
      static constexpr color light_coral             {0xFFF08080};
      static constexpr color light_cyan              {0xFFE0FFFF};
      static constexpr color light_golden_rod_yellow {0xFFFAFAD2};
      static constexpr color light_gray              {0xFFD3D3D3};
      static constexpr color light_grey              {0xFFD3D3D3};
      static constexpr color light_green             {0xFF90EE90};
      static constexpr color light_pink              {0xFFFFB6C1};
      static constexpr color light_salmon            {0xFFFFA07A};
      static constexpr color light_sea_green         {0xFF20B2AA};
      static constexpr color light_sky_blue          {0xFF87CEFA};
      static constexpr color light_slate_gray        {0xFF778899};
      static constexpr color light_slate_grey        {0xFF778899};
      static constexpr color light_steel_blue        {0xFFB0C4DE};
      static constexpr color light_yellow            {0xFFFFFFE0};
      static constexpr color lime                    {0xFF00FF00};
      static constexpr color lime_green              {0xFF32CD32};
      static constexpr color linen                   {0xFFFAF0E6};
      static constexpr color magenta                 {0xFFFF00FF};
      static constexpr color maroon                  {0xFF800000};
      static constexpr color medium_aqua_marine      {0xFF66CDAA};
      static constexpr color medium_blue             {0xFF0000CD};
      static constexpr color medium_orchid           {0XFFBA55D3};
      static constexpr color medium_purple           {0xFF9370DB};
      static constexpr color medium_sea_green        {0xFF3CB371};
      static constexpr color medium_slate_blue       {0xFF7B68EE};
      static constexpr color medium_spring_green     {0xFF00FA9A};
      static constexpr color medium_turqoise         {0xFF48D1CC};
      static constexpr color medium_violet_red       {0xFFC71585};
      static constexpr color midnight_blue           {0xFF191970};
      static constexpr color mint_cream              {0xFFF5FFFA};
      static constexpr color misty_rose              {0xFFFFE4E1};
      static constexpr color moccasin                {0xFFFFE4B5};
      static constexpr color navajo_white            {0xFFFFDEAD};
      static constexpr color navy                    {0xFF000080};
      static constexpr color old_lace                {0xFFFDF5E6};
      static constexpr color olive                   {0xFF808000};
      static constexpr color olive_drab              {0xFF6B8E23};
      static constexpr color orange                  {0xFFFFA500};
      static constexpr color orange_red              {0xFFFF4500};
      static constexpr color orchid                  {0xFFDA70D6};
      static constexpr color pale_golden_rod         {0xFFEEE8AA};
      static constexpr color pale_green              {0xFF98FB98};
      static constexpr color pale_turquoise          {0xFFAFEEEE};
      static constexpr color pale_violet_red         {0xFFDB7093};
      static constexpr color papaya_whip             {0xFFFFEFD5};
      static constexpr color peach_puff              {0xFFFFC0CB};
      static constexpr color peru                    {0xFFCD853F};
      static constexpr color pink                    {0xFFFFC0CB};
      static constexpr color plum                    {0xFFDDA0DD};
      static constexpr color powder_blue             {0xFFB0E0E6};
      static constexpr color purple                  {0xFF800080};
      static constexpr color rebecca_purple          {0xFF663399};
      static constexpr color red                     {0xFFFF0000};
      static constexpr color rosy_brown              {0xFFBC8F8F};
      static constexpr color royal_blue              {0xFF4169E1};
      static constexpr color saddle_brown            {0xFF8B4513};
      static constexpr color salmon                  {0xFFFA8072};
      static constexpr color sandy_brown             {0xFFF4A460};
      static constexpr color sea_green               {0xFF2E8B57};
      static constexpr color sea_shell               {0xFFFFF5EE};
      static constexpr color sienna                  {0xFFA0522D};
      static constexpr color silver                  {0xFFC0C0C0};
      static constexpr color sky_blue                {0xFF87CEEB};
      static constexpr color slate_blue              {0xFF6A5ACD};
      static constexpr color slate_gray              {0xFF708090};
      static constexpr color slate_grey              {0xFF708090};
      static constexpr color snow                    {0xFFFFFAFA};
      static constexpr color spring_green            {0xFF00FF7F};
      static constexpr color steel_blue              {0xFF4682B4};
      static constexpr color tan                     {0xFFD2B48C};
      static constexpr color teal                    {0xFF008080};
      static constexpr color thistle                 {0xFFD8BFD8};
      static constexpr color tomato                  {0xFFFF6347};
      static constexpr color turquoise               {0xFF40E0D0};
      static constexpr color violet                  {0xFFEE82EE};
      static constexpr color wheat                   {0xFFF5DEB3};
      static constexpr color white                   {0xFFFFFFFF};
      static constexpr color white_smoke             {0xFFF5F5F5};
      static constexpr color yellow                  {0xFFFFFF00};
      static constexpr color yellow_green            {0xFF9ACD32};
    }
  }
}

#endif
<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2014 Khaled Nasr
 */

#include <shogun/base/Parameter.h>
#include <shogun/neuralnets/NeuralLayer.h>

using namespace shogun;

CNeuralLayer::CNeuralLayer()
: CSGObject(), m_num_neurons(0), m_previous_layer_num_neurons(0),
	m_batch_size(0)
{
	init();
}

CNeuralLayer::CNeuralLayer(int32_t num_neurons)
: CSGObject(), m_num_neurons(0),
	m_previous_layer_num_neurons(0), m_batch_size(0)
{
	init();
}

CNeuralLayer::CNeuralLayer(const CNeuralLayer& orig) : CSGObject()
{
	shallow_copy(orig);
	init();
}

CNeuralLayer::~CNeuralLayer()
{
}

void CNeuralLayer::initialize(int32_t previous_layer_num_neurons)
{
	m_previous_layer_num_neurons = previous_layer_num_neurons;
}

void CNeuralLayer::set_batch_size(int32_t batch_size)
{
	m_batch_size = batch_size;

	if (m_activations.vector!=NULL) SG_FREE(m_activations.vector);
	if (m_input_gradients.vector!=NULL) SG_FREE(m_input_gradients.vector);
	if (m_local_gradients.vector!=NULL) SG_FREE(m_local_gradients.vector);

	m_activations.vlen = m_num_neurons * m_batch_size;
	m_input_gradients.vlen = m_previous_layer_num_neurons * m_batch_size;
	m_local_gradients.vlen = m_num_neurons * m_batch_size;

	m_activations.vector = SG_MALLOC(float64_t, m_activations.vlen);
	m_input_gradients.vector = SG_MALLOC(float64_t, m_input_gradients.vlen);
	m_local_gradients.vector = SG_MALLOC(float64_t, m_local_gradients.vlen);
}

void CNeuralLayer::init()
{
	SG_ADD(&m_num_neurons, "num_neurons",
	       "Number of Neurons", MS_NOT_AVAILABLE);
	SG_ADD(&m_previous_layer_num_neurons, "previous_layer_num_neurons",
	       "Number of neurons in the previous layer", MS_NOT_AVAILABLE);
	SG_ADD(&m_batch_size, "batch_size",
	       "Batch Size", MS_NOT_AVAILABLE);
	SG_ADD(&m_activations, "activations",
	       "Activations", MS_NOT_AVAILABLE);
	SG_ADD(&m_input_gradients, "input_gradients",
	       "Input Gradients", MS_NOT_AVAILABLE);
	SG_ADD(&m_local_gradients, "local_gradients",
	       "Local Gradients", MS_NOT_AVAILABLE);
}

void CNeuralLayer::shallow_copy(const CNeuralLayer &orig)
{
	m_num_neurons = orig.m_num_neurons;
	m_previous_layer_num_neurons = orig.m_previous_layer_num_neurons;
	m_batch_size = orig.m_batch_size;
	m_activations = SGVector<float64_t>(orig.m_activations);
	m_input_gradients = SGVector<float64_t>(orig.m_input_gradients);
	m_local_gradients = SGVector<float64_t>(orig.m_local_gradients);
}

<commit_msg>small bugfix<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2014 Khaled Nasr
 */

#include <shogun/base/Parameter.h>
#include <shogun/neuralnets/NeuralLayer.h>

using namespace shogun;

CNeuralLayer::CNeuralLayer()
: CSGObject(), m_num_neurons(0), m_previous_layer_num_neurons(0),
	m_batch_size(0)
{
	init();
}

CNeuralLayer::CNeuralLayer(int32_t num_neurons)
: CSGObject(), m_num_neurons(num_neurons),
m_previous_layer_num_neurons(0), m_batch_size(0)
{
	init();
}

CNeuralLayer::CNeuralLayer(const CNeuralLayer& orig) : CSGObject()
{
	shallow_copy(orig);
	init();
}

CNeuralLayer::~CNeuralLayer()
{
}

void CNeuralLayer::initialize(int32_t previous_layer_num_neurons)
{
	m_previous_layer_num_neurons = previous_layer_num_neurons;
}

void CNeuralLayer::set_batch_size(int32_t batch_size)
{
	m_batch_size = batch_size;

	if (m_activations.vector!=NULL) SG_FREE(m_activations.vector);
	if (m_input_gradients.vector!=NULL) SG_FREE(m_input_gradients.vector);
	if (m_local_gradients.vector!=NULL) SG_FREE(m_local_gradients.vector);

	m_activations.vlen = m_num_neurons * m_batch_size;
	m_input_gradients.vlen = m_previous_layer_num_neurons * m_batch_size;
	m_local_gradients.vlen = m_num_neurons * m_batch_size;

	m_activations.vector = SG_MALLOC(float64_t, m_activations.vlen);
	m_input_gradients.vector = SG_MALLOC(float64_t, m_input_gradients.vlen);
	m_local_gradients.vector = SG_MALLOC(float64_t, m_local_gradients.vlen);
}

void CNeuralLayer::init()
{
	SG_ADD(&m_num_neurons, "num_neurons",
	       "Number of Neurons", MS_NOT_AVAILABLE);
	SG_ADD(&m_previous_layer_num_neurons, "previous_layer_num_neurons",
	       "Number of neurons in the previous layer", MS_NOT_AVAILABLE);
	SG_ADD(&m_batch_size, "batch_size",
	       "Batch Size", MS_NOT_AVAILABLE);
	SG_ADD(&m_activations, "activations",
	       "Activations", MS_NOT_AVAILABLE);
	SG_ADD(&m_input_gradients, "input_gradients",
	       "Input Gradients", MS_NOT_AVAILABLE);
	SG_ADD(&m_local_gradients, "local_gradients",
	       "Local Gradients", MS_NOT_AVAILABLE);
}

void CNeuralLayer::shallow_copy(const CNeuralLayer &orig)
{
	m_num_neurons = orig.m_num_neurons;
	m_previous_layer_num_neurons = orig.m_previous_layer_num_neurons;
	m_batch_size = orig.m_batch_size;
	m_activations = SGVector<float64_t>(orig.m_activations);
	m_input_gradients = SGVector<float64_t>(orig.m_input_gradients);
	m_local_gradients = SGVector<float64_t>(orig.m_local_gradients);
}

<|endoftext|>


<commit_before>/*
 * Copyright 2010-2012 Esrille Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ViewCSSImp.h"

#include <org/w3c/dom/Text.h>
#include <org/w3c/dom/Comment.h>

#include <new>

#include "CSSStyleRuleImp.h"
#include "CSSStyleDeclarationImp.h"
#include "DocumentImp.h"

#include "Box.h"
#include "StackingContext.h"

#include "font/FontDatabase.h"
#include "font/FontManager.h"
#include "font/FontManagerBackEndGL.h"

namespace {

FontManagerBackEndGL backend;

const int Point = 33;

}

namespace org { namespace w3c { namespace dom { namespace bootstrap {

FontTexture* ViewCSSImp::selectFont(CSSStyleDeclarationImp* style)
{
    FontManager* manager = backend.getFontManager();
    unsigned s = style->fontStyle.getStyle();
    unsigned w = style->fontWeight.getWeight();
    for (auto i = style->fontFamily.getFamilyNames().begin(); i != style->fontFamily.getFamilyNames().end(); ++i) {
        if (FontFace* face = manager->getFontFace(*i, s, w))
            return face->getFontTexture(Point, s, w);
    }
    unsigned g = style->fontFamily.getGeneric();
    if (!g)
        g = CSSFontFamilyValueImp::SansSerif;
    if (FontFace* face = manager->getFontFace(g, s, w))
        return face->getFontTexture(Point, s, w);
    return 0;
}

FontTexture* ViewCSSImp::selectAltFont(CSSStyleDeclarationImp* style, FontTexture* current, char32_t u)
{
    assert(current);
    FontManager* manager = backend.getFontManager();
    unsigned s = style->fontStyle.getStyle();
    unsigned w = style->fontWeight.getWeight();
    bool skipped = false;
    for (auto i = style->fontFamily.getFamilyNames().begin(); i != style->fontFamily.getFamilyNames().end(); ++i) {
        FontFace* face = manager->getFontFace(*i, s, w);
        if (face->getFamilyName() == current->getFace()->getFamilyName()) {
            // TODO: Deal with filesnames registered more than once.
            skipped = true;
            continue;
        }
        if (skipped && face->hasGlyph(u))
            return face->getFontTexture(Point, s, w);
    }
    unsigned g = style->fontFamily.getGeneric();
    if (!g)
        g = CSSFontFamilyValueImp::SansSerif;
    if (FontFace* face = manager->getAltFontFace(g, s, w, current, u))
        return face->getFontTexture(Point, s, w);
    return 0;
}

void ViewCSSImp::render()
{
    glPushMatrix();
    glScalef(zoom, zoom, zoom);
    glTranslatef(-window->getScrollX(), -window->getScrollY(), 0.0f);
    if (stackingContexts)
        stackingContexts->render(this);
    glPopMatrix();

    if (overflow != CSSOverflowValueImp::Hidden) {
        Box::renderVerticalScrollBar(initialContainingBlock.width, initialContainingBlock.height, window->getScrollY(), boxTree->getTotalHeight());
        Box::renderHorizontalScrollBar(initialContainingBlock.width, initialContainingBlock.height, window->getScrollX(), scrollWidth);
    }
}

}}}}  // org::w3c::dom::bootstrap

void initFonts(int* argc, char* argv[])
{
    FontManager* manager = backend.getFontManager();
    FontDatabase::loadBaseFonts(manager);
    for (int i = 1; i < *argc; ++i) {
        if (strcmp(argv[i], "-testfonts") == 0) {
            FontDatabase::loadTestFonts(manager);
            for (; i < *argc; ++i)
                argv[i] = argv[i + 1];
            --*argc;
            break;
        }
    }
}
<commit_msg>(ViewCSSImp::selectAltFont) : Fix a bug.<commit_after>/*
 * Copyright 2010-2012 Esrille Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ViewCSSImp.h"

#include <org/w3c/dom/Text.h>
#include <org/w3c/dom/Comment.h>

#include <new>

#include "CSSStyleRuleImp.h"
#include "CSSStyleDeclarationImp.h"
#include "DocumentImp.h"

#include "Box.h"
#include "StackingContext.h"

#include "font/FontDatabase.h"
#include "font/FontManager.h"
#include "font/FontManagerBackEndGL.h"

namespace {

FontManagerBackEndGL backend;

const int Point = 33;

}

namespace org { namespace w3c { namespace dom { namespace bootstrap {

FontTexture* ViewCSSImp::selectFont(CSSStyleDeclarationImp* style)
{
    FontManager* manager = backend.getFontManager();
    unsigned s = style->fontStyle.getStyle();
    unsigned w = style->fontWeight.getWeight();
    for (auto i = style->fontFamily.getFamilyNames().begin(); i != style->fontFamily.getFamilyNames().end(); ++i) {
        if (FontFace* face = manager->getFontFace(*i, s, w))
            return face->getFontTexture(Point, s, w);
    }
    unsigned g = style->fontFamily.getGeneric();
    if (!g)
        g = CSSFontFamilyValueImp::SansSerif;
    if (FontFace* face = manager->getFontFace(g, s, w))
        return face->getFontTexture(Point, s, w);
    return 0;
}

FontTexture* ViewCSSImp::selectAltFont(CSSStyleDeclarationImp* style, FontTexture* current, char32_t u)
{
    assert(current);
    FontManager* manager = backend.getFontManager();
    unsigned s = style->fontStyle.getStyle();
    unsigned w = style->fontWeight.getWeight();
    bool skipped = false;
    for (auto i = style->fontFamily.getFamilyNames().begin(); i != style->fontFamily.getFamilyNames().end(); ++i) {
        FontFace* face = manager->getFontFace(*i, s, w);
        if (!face)
            continue;
        if (face->getFamilyName() == current->getFace()->getFamilyName()) {
            // TODO: Deal with filesnames registered more than once.
            skipped = true;
            continue;
        }
        if (skipped && face->hasGlyph(u))
            return face->getFontTexture(Point, s, w);
    }
    unsigned g = style->fontFamily.getGeneric();
    if (!g)
        g = CSSFontFamilyValueImp::SansSerif;
    if (FontFace* face = manager->getAltFontFace(g, s, w, current, u))
        return face->getFontTexture(Point, s, w);
    return 0;
}

void ViewCSSImp::render()
{
    glPushMatrix();
    glScalef(zoom, zoom, zoom);
    glTranslatef(-window->getScrollX(), -window->getScrollY(), 0.0f);
    if (stackingContexts)
        stackingContexts->render(this);
    glPopMatrix();

    if (overflow != CSSOverflowValueImp::Hidden) {
        Box::renderVerticalScrollBar(initialContainingBlock.width, initialContainingBlock.height, window->getScrollY(), boxTree->getTotalHeight());
        Box::renderHorizontalScrollBar(initialContainingBlock.width, initialContainingBlock.height, window->getScrollX(), scrollWidth);
    }
}

}}}}  // org::w3c::dom::bootstrap

void initFonts(int* argc, char* argv[])
{
    FontManager* manager = backend.getFontManager();
    FontDatabase::loadBaseFonts(manager);
    for (int i = 1; i < *argc; ++i) {
        if (strcmp(argv[i], "-testfonts") == 0) {
            FontDatabase::loadTestFonts(manager);
            for (; i < *argc; ++i)
                argv[i] = argv[i + 1];
            --*argc;
            break;
        }
    }
}
<|endoftext|>


<commit_before>
#include "nucleus/streams/file_input_stream.h"

namespace nu {

namespace detail {

I64 setFileInputStreamPosition(FileInputStream::HandleType handle, I64 pos) {
  LARGE_INTEGER li = {0};
  li.QuadPart = pos;
  li.LowPart = ::SetFilePointer(static_cast<HANDLE>(handle), static_cast<LONG>(li.LowPart), &li.HighPart, FILE_BEGIN);
  return li.QuadPart;
}

}  // namespace detail

FileInputStream::SizeType FileInputStream::getLength() {
  SizeType fileSize = 0;
  DWORD lowSize = ::GetFileSize(static_cast<HANDLE>(m_handle), nullptr);
  fileSize = lowSize;
  return fileSize;
}

void FileInputStream::openHandle() {
  HANDLE h = ::CreateFileW((LPCWSTR)m_path.getPath().c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
                           OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
  if (h != INVALID_HANDLE_VALUE) {
    m_handle = (void*)h;
  } else {
    m_status = false;
   }
}

void FileInputStream::closeHandle() {
  ::CloseHandle(static_cast<HANDLE>(m_handle));
}

FileInputStream::SizeType FileInputStream::readInternal(void* buffer, SizeType numBytes) {
  if (m_handle != nullptr) {
    DWORD actualNum = 0;
    if (::ReadFile(static_cast<HANDLE>(m_handle), buffer, static_cast<DWORD>(numBytes), &actualNum, nullptr) == FALSE) {
      m_status = false;
    }

    return static_cast<USize>(actualNum);
  }

  return 0;
}

}  // namespace nu
<commit_msg>Fixed formatting<commit_after>
#include "nucleus/streams/file_input_stream.h"

namespace nu {

namespace detail {

I64 setFileInputStreamPosition(FileInputStream::HandleType handle, I64 pos) {
  LARGE_INTEGER li = {0};
  li.QuadPart = pos;
  li.LowPart = ::SetFilePointer(static_cast<HANDLE>(handle), static_cast<LONG>(li.LowPart), &li.HighPart, FILE_BEGIN);
  return li.QuadPart;
}

}  // namespace detail

FileInputStream::SizeType FileInputStream::getLength() {
  SizeType fileSize = 0;
  DWORD lowSize = ::GetFileSize(static_cast<HANDLE>(m_handle), nullptr);
  fileSize = lowSize;
  return fileSize;
}

void FileInputStream::openHandle() {
  HANDLE h = ::CreateFileW((LPCWSTR)m_path.getPath().c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
                           OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
  if (h != INVALID_HANDLE_VALUE) {
    m_handle = (void*)h;
  } else {
    m_status = false;
  }
}

void FileInputStream::closeHandle() {
  ::CloseHandle(static_cast<HANDLE>(m_handle));
}

FileInputStream::SizeType FileInputStream::readInternal(void* buffer, SizeType numBytes) {
  if (m_handle != nullptr) {
    DWORD actualNum = 0;
    if (::ReadFile(static_cast<HANDLE>(m_handle), buffer, static_cast<DWORD>(numBytes), &actualNum, nullptr) == FALSE) {
      m_status = false;
    }

    return static_cast<USize>(actualNum);
  }

  return 0;
}

}  // namespace nu
<|endoftext|>


<commit_before>#include "dialogerrors.h"
#include "ui_dialogerrors.h"

#include <QTextStream>
#include <QByteArray>
#include <QClipboard>

#include <validation/devisermessage.h>

DialogErrors::DialogErrors(const QList<DeviserMessage*>& errors,
                           QWidget *parent)
  : QDialog(parent)
  , ui(new Ui::DialogErrors)
  , mErrors(errors)
  , mMessages()
{
  ui->setupUi(this);

  QByteArray array;
  QTextStream stream(&array, QIODevice::WriteOnly);
  stream.setCodec("UTF-8");

  setWindowTitle(
        QString("Package Validation: %1 issues found.")
        .arg(errors.count()));

  stream << QString("Package Validation: %1 issues found.")
            .arg(errors.count()) << endl << endl;

  ui->lblCount->setText(QString("Package Validation: %1 issues found.")
                        .arg(errors.count()));

  QLayout* layout = ui->scrollAreaWidgetContents->layout();
  if (layout == NULL)
  {
    layout = new QVBoxLayout(ui->scrollAreaWidgetContents);
  }

  foreach(DeviserMessage* message, errors)
  {
    QHBoxLayout *hlayout = new QHBoxLayout();
    QLabel *pixmap = new QLabel(ui->scrollAreaWidgetContents);
    pixmap->setMaximumWidth(50);
    pixmap->setMaximumHeight(50);
    pixmap->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
    switch (message->severity()) {
    case DEVISER_ERROR:
    case DEVISER_FATAL_ERROR:
      pixmap ->setPixmap(QPixmap(":images/dialog-error.png"));
      stream << "Error: ";
      break;

    case DEVISER_NOTICE:
      pixmap ->setPixmap(QPixmap(":images/dialog-information.png"));
      stream << "Notice: ";
      break;

    default:
      pixmap ->setPixmap(QPixmap(":images/dialog-warning.png"));
      stream << "Warning: ";
      break;
    }
    hlayout->addWidget(pixmap);

    QLabel *label = new QLabel(message->message(), ui->scrollAreaWidgetContents);

    stream << message->message() << endl << endl;

    label->setWordWrap(true);
    hlayout->addWidget(label);

    layout->addItem(hlayout);
  }

  layout->addItem(
        new QSpacerItem(10,10, QSizePolicy::Minimum, QSizePolicy::Expanding));

  stream.flush();

  mMessages = QString::fromUtf8(array);

}

DialogErrors::~DialogErrors()
{
  delete ui;
}

void DialogErrors::copyErrors()
{
  QClipboard *clipboard = QApplication::clipboard();
  clipboard->setText(mMessages);
}
<commit_msg>- allow copying of individual error messages<commit_after>#include "dialogerrors.h"
#include "ui_dialogerrors.h"

#include <QTextStream>
#include <QByteArray>
#include <QClipboard>

#include <validation/devisermessage.h>

DialogErrors::DialogErrors(const QList<DeviserMessage*>& errors,
                           QWidget *parent)
  : QDialog(parent)
  , ui(new Ui::DialogErrors)
  , mErrors(errors)
  , mMessages()
{
  ui->setupUi(this);

  QByteArray array;
  QTextStream stream(&array, QIODevice::WriteOnly);
  stream.setCodec("UTF-8");

  setWindowTitle(
        QString("Package Validation: %1 issues found.")
        .arg(errors.count()));

  stream << QString("Package Validation: %1 issues found.")
            .arg(errors.count()) << endl << endl;

  ui->lblCount->setText(QString("Package Validation: %1 issues found.")
                        .arg(errors.count()));

  QLayout* layout = ui->scrollAreaWidgetContents->layout();
  if (layout == NULL)
  {
    layout = new QVBoxLayout(ui->scrollAreaWidgetContents);
  }

  foreach(DeviserMessage* message, errors)
  {
    QHBoxLayout *hlayout = new QHBoxLayout();
    QLabel *pixmap = new QLabel(ui->scrollAreaWidgetContents);
    pixmap->setMaximumWidth(50);
    pixmap->setMaximumHeight(50);
    pixmap->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
    switch (message->severity()) {
    case DEVISER_ERROR:
    case DEVISER_FATAL_ERROR:
      pixmap ->setPixmap(QPixmap(":images/dialog-error.png"));
      stream << "Error: ";
      break;

    case DEVISER_NOTICE:
      pixmap ->setPixmap(QPixmap(":images/dialog-information.png"));
      stream << "Notice: ";
      break;

    default:
      pixmap ->setPixmap(QPixmap(":images/dialog-warning.png"));
      stream << "Warning: ";
      break;
    }
    hlayout->addWidget(pixmap);

    QLabel *label = new QLabel(message->message(), ui->scrollAreaWidgetContents);
    label->setTextInteractionFlags(Qt::TextSelectableByKeyboard | Qt::TextSelectableByMouse);
    stream << message->message() << endl << endl;

    label->setWordWrap(true);
    hlayout->addWidget(label);

    layout->addItem(hlayout);
  }

  layout->addItem(
        new QSpacerItem(10,10, QSizePolicy::Minimum, QSizePolicy::Expanding));

  stream.flush();

  mMessages = QString::fromUtf8(array);

}

DialogErrors::~DialogErrors()
{
  delete ui;
}

void DialogErrors::copyErrors()
{
  QClipboard *clipboard = QApplication::clipboard();
  clipboard->setText(mMessages);
}
<|endoftext|>