<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: templateimpl.cxx,v $
 *
 *  $Revision: 1.22 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-23 14:47:00 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_configmgr.hxx"

#include <stdio.h>
#include "templateimpl.hxx"

#ifndef CONFIGMGR_TREEPROVIDER_HXX
#include "treeprovider.hxx"
#endif

#ifndef CONFIGMGR_NODEVISITOR_HXX
#include "nodevisitor.hxx"
#endif
#ifndef CONFIGMGR_TREEACCESSOR_HXX
#include "treeaccessor.hxx"
#endif
#ifndef CONFIGMGR_NODEACCESS_HXX
#include "nodeaccess.hxx"
#endif
#ifndef CONFIGMGR_VALUENODEACCESS_HXX
#include "valuenodeaccess.hxx"
#endif
#ifndef CONFIGMGR_SETNODEACCESS_HXX
#include "setnodeaccess.hxx"
#endif

#ifndef _CONFIGMGR_STRDECL_HXX_
#include "strdecl.hxx"
#endif
#ifndef CONFIGMGR_TYPECONVERTER_HXX
#include "typeconverter.hxx"
#endif
#ifndef CONFIGMGR_LOCALIZEDTREEACTIONS_HXX
#include "localizedtreeactions.hxx"
#endif
#ifndef _CONFIGMGR_TREEACTIONS_HXX_
#include "treeactions.hxx"
#endif
#ifndef CONFIGMGR_API_APITYPES_HXX_
#include "apitypes.hxx"
#endif

#ifndef INCLUDED_MAP
#include <map>
#define INCLUDED_MAP
#endif

namespace configmgr
{
    namespace configuration
    {
//-----------------------------------------------------------------------------

Name TemplateName::makeSimpleTypeName(UnoType const& aType)
{
    OUString sTypeName = toTemplateName(aType);
    return makeName(sTypeName, Name::NoValidate());
}
//-----------------------------------------------------------------------------

UnoType TemplateName::resolveSimpleTypeName(Name const& aName)
{
    OUString sTypeName = aName.toString();
    return parseTemplateName(sTypeName);
}
//-----------------------------------------------------------------------------

Name TemplateName::makeNativeTypeModuleName()
{
    OUString aModuleName( TEMPLATE_MODULE_NATIVE_VALUE );
    return makeName(aModuleName, Name::NoValidate());
}
//-----------------------------------------------------------------------------
Name TemplateName::makeLocalizedTypeModuleName()
{
    OUString aModuleName( TEMPLATE_MODULE_LOCALIZED_VALUE );
    return makeName(aModuleName, Name::NoValidate());
}
//-----------------------------------------------------------------------------
bool TemplateName::isSimpleTypeName() const
{
    bool bIsSimple = (aModule.toString().compareToAscii(TEMPLATE_MODULE_NATIVE_PREFIX,
                                                        TEMPLATE_MODULE_NATIVE_PREFIX.getLength()) == 0);

    OSL_ENSURE(!bIsSimple ||
                aModule == makeNativeTypeModuleName() ||
                aModule == makeLocalizedTypeModuleName(),
                "ERROR: Invalid template module with native prefix found");

    return bIsSimple;
}
//-----------------------------------------------------------------------------

UnoType TemplateName::resolveToSimpleType() const
{
    UnoType aType;
    if ( isSimpleTypeName() )
    {
        aType = resolveSimpleTypeName( aName );
    }
    else
        OSL_ENSURE(false, "TemplateName::resolveToSimpleType must be called only for simple type name pairs");
    return aType;
}
//-----------------------------------------------------------------------------
// class TemplateImplHelper
//-----------------------------------------------------------------------------

TemplateHolder TemplateImplHelper::createNew (TemplateName const& aNames,UnoType const& aType)
{
    return new Template(aNames.aName, aNames.aModule, aType);
}
//-----------------------------------------------------------------------------

TemplateHolder TemplateImplHelper::makeSpecialTemplate (TemplateName const& aNames, SpecialTemplateProvider const& aProvider, UnoType const& aType)
{
    OSL_ENSURE(aProvider.m_aImpl.is(), "Cannot find a template without a provider");

    if (aProvider.m_aImpl.is())
        return aProvider.m_aImpl->makeTemplate(aNames,aType);

    else
        return TemplateHolder(0);
}
//-----------------------------------------------------------------------------

TemplateHolder TemplateImplHelper::makeElementTemplateWithType(TemplateName const& _aNames, TemplateProvider const& _aProvider, data::SetNodeAccess const& _aSet)
{
    OSL_ENSURE(_aProvider.m_aImpl.is(), "ERROR: Cannot find a template without a provider");

    if (_aProvider.m_aImpl.is())
        return _aProvider.m_aImpl->makeElementTemplateWithType(_aNames,_aSet);

    else
        return TemplateHolder(0);
}
//-----------------------------------------------------------------------------

void TemplateImplHelper::assignActualType (Template& aTemplate,UnoType const& aType)
{
    OSL_PRECOND( aType != getNoTypeAvailable(), "ERROR: Assigning NO type to a template" );

    if (!aTemplate.isInstanceTypeKnown())
        aTemplate.m_aInstanceType = aType;

    OSL_ENSURE(aTemplate.isInstanceTypeKnown(), "ERROR: Could not assign given type to a template");
    OSL_ENSURE(aTemplate.getInstanceType() == aType, "ERROR: Trying to change instance type of a template");
}
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// class SpecialTemplateProvider_Impl
//-----------------------------------------------------------------------------

SpecialTemplateProvider_Impl::SpecialTemplateProvider_Impl()
: m_aRepository()
{
}
//-----------------------------------------------------------------------------

TemplateHolder SpecialTemplateProvider_Impl::makeTemplate (TemplateName const& aNames, UnoType const& aType)
{
    typedef TemplateRepository::value_type Entry;

    TemplateRepository::iterator it = m_aRepository.find(aNames);
    if (it == m_aRepository.end())
        it = m_aRepository.insert( Entry( aNames, TemplateImplHelper::createNew(aNames,aType) ) ).first;

    else if (!it->second->isInstanceTypeKnown())
        TemplateImplHelper::assignActualType(*it->second, aType);

    OSL_ENSURE(it->second->isInstanceTypeKnown(), "No type assigned to Template");
    OSL_ENSURE(it->second->getInstanceType() == aType, "Inconsistent type found for Template");
    return it->second;

}

//-----------------------------------------------------------------------------
// class TemplateProvider_Impl
//-----------------------------------------------------------------------------

TemplateProvider_Impl::TemplateProvider_Impl(TemplateManagerRef const & xProvider, RequestOptions const& aOptions)
: m_xProvider(xProvider)
, m_aOptions(aOptions)
, m_aRepository()
{
}
//-----------------------------------------------------------------------------

data::TreeSegment TemplateProvider_Impl::instantiate(TemplateHolder const& aTemplate)
{
    data::TreeSegment pRet;
    if (aTemplate.is())
    {
        data::TreeAccessor aTemplateData = m_xProvider->requestTemplate(aTemplate->getName(), aTemplate->getModule());

        pRet = cloneExpandedForLocale(aTemplateData, m_aOptions.getLocale());
    }
    return pRet;
}
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
namespace
{
    using namespace data;
//-----------------------------------------------------------------------------
    struct TypeDetector : SetVisitor
    {
        enum State
        {
            Contradicting = -1,
            NotFound = 0,
            SomeValue,
            VariousValue,
            SomeTree
        };

        State   result;
        UnoType type;

        TypeDetector() : result(NotFound), type() {}

       protected:
            using SetVisitor::handle;

    private: // NodeAction implementation
        Result handle(ValueNodeAccess const& _aValueNode);
        Result handle(NodeAccess const& _aNonValueNode);
    };
//-----------------------------------------------------------------------------
    static UnoType detectNodeType(TreeAccessor const& _aElement)
    {
        if (_aElement == NULL)
            throw configuration::Exception("Could not load required template to detect set elements");

        TypeDetector aDetector;
        aDetector.visitTree( _aElement );

        switch(aDetector.result)
        {
        case TypeDetector::SomeTree:        // found tree
        case TypeDetector::VariousValue:    // found an Any
        case TypeDetector::SomeValue:       // found a particular value type
            break;

#ifdef DBG_UTIL
        case TypeDetector::NotFound:        OSL_ENSURE(false,"Impossible Result: Node not handled");        if (false) // dirty abuse of case
        case TypeDetector::Contradicting:   OSL_ENSURE(false,"Impossible Result: Node contradicts itself"); if (false) // dirty abuse of case
#endif // DBG_UTIL
        default:                            OSL_ENSURE(false,"Impossible Result: Unknown result code");

            throw configuration::Exception("INTERNAL ERROR: Could not detect set element type from loaded instance");
        }
        return aDetector.type;
    }

    //-------------------------------------------------------------------------
    static bool detectElementType(UnoType& aType, data::SetNodeAccess const& _aSet)
    {
        TypeDetector aDetector;
        aDetector.visitElements( _aSet );

        bool bResult = false;
        switch(aDetector.result)
        {
        case TypeDetector::SomeTree:        // found tree
        case TypeDetector::VariousValue:    // found an Any
            aType = aDetector.type;
            bResult = true;
            break;

        case TypeDetector::SomeValue:       // found a value or an any
        case TypeDetector::NotFound:        // found no element
            break;

        case TypeDetector::Contradicting:
            OSL_ENSURE(false,"Invalid Set: contains values and subtrees");
            break;

        default: OSL_ENSURE(false,"Unreachable code");  break;
        }
        return bResult;
    }
//-----------------------------------------------------------------------------

}
//-----------------------------------------------------------------------------
TemplateHolder TemplateProvider_Impl::makeElementTemplateWithType(TemplateName const& _aNames, data::SetNodeAccess const& _aSet)
{
    typedef TemplateRepository::value_type Entry;

    TemplateRepository::iterator it = m_aRepository.find(_aNames);

    if (it == m_aRepository.end() || !it->second->isInstanceTypeKnown())
    {
        UnoType aType;
        if (_aNames.isSimpleTypeName()) // native type found
        {
            aType = _aNames.resolveToSimpleType();

            if (aType == TemplateImplHelper::getNoTypeAvailable())
                throw configuration::Exception("INTERNAL ERROR: Could not resolve native type");
        }

        else if (!detectElementType(aType,_aSet))
        {
            OSL_ASSERT(_aNames.aName == _aSet.getElementTemplateName());
            OSL_ASSERT(_aNames.aModule == _aSet.getElementTemplateModule());

            data::TreeAccessor aTemplateData = m_xProvider->requestTemplate(_aNames.aName, _aNames.aModule);

            aType = detectNodeType(aTemplateData); // throws if necessary
        }
        OSL_ASSERT( aType != TemplateImplHelper::getNoTypeAvailable() );

        if (it == m_aRepository.end())
            it = m_aRepository.insert( Entry( _aNames, TemplateImplHelper::createNew(_aNames,aType) ) ).first;

        else
            TemplateImplHelper::assignActualType(*it->second, aType);

        OSL_ENSURE(it->second->isInstanceTypeKnown(), "No type assigned to Template");
        OSL_ENSURE(it->second->getInstanceType() == aType, "Inconsistent type found for Template");
    }

#ifdef DBG_UTIL
    else
    {
        OSL_ENSURE(it->second->isInstanceTypeKnown(), "No type assigned to Template");
        UnoType aTestType;
        if (detectElementType(aTestType,_aSet))
            OSL_ENSURE(it->second->getInstanceType() == aTestType, "Inconsistent type found for Template");
    }
#endif // DBG_UTIL

    return it->second;

}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
namespace
{
//-----------------------------------------------------------------------------
    TypeDetector::Result TypeDetector::handle(ValueNodeAccess const& _aValueNode)
    {
        UnoType aFoundType = _aValueNode.getValueType();

        bool isNullType = (aFoundType.getTypeClass() == uno::TypeClass_VOID);
        bool isAnyType  = (aFoundType.getTypeClass() == uno::TypeClass_ANY);

        switch (this->result) // transition depends on previous state
        {
        case NotFound:
            this->type = aFoundType;

            if (isAnyType)
                this->result = VariousValue;

            else if (!isNullType)
                this->result = SomeValue;

            break;

        case SomeValue:
            if (!isNullType && this->type != aFoundType)
            {
                this->result = VariousValue;
                this->type =  configapi::getAnyType();
                OSL_ASSERT(type.getTypeClass() == uno::TypeClass_ANY);
            }
            break;

        case VariousValue: // remain unchanged - type already is 'Any'
            break;

        case SomeTree: OSL_ENSURE(false, "Found value node does not match previous (tree) sibling");
        default:
            this->result = Contradicting;
            break;
        }
        return CONTINUE; // always continue to detect errors in data
    }
//-----------------------------------------------------------------------------
    TypeDetector::Result TypeDetector::handle(NodeAccess const& _aNonValueNode)
    {
            { (void)_aNonValueNode; }
        OSL_ENSURE(!ValueNodeAccess::isInstance(_aNonValueNode),"Value node dipatched to wrong handler");
        switch (this->result) // transition depends on previous state
        {
        case NotFound:
            this->type = configapi::getUnoInterfaceType();
            this->result = SomeTree;
            break;

        case SomeTree: // remain unchanged - type already is Tree
            break;

        case SomeValue:
        case VariousValue:  OSL_ENSURE(false, "Found Subtree node does not match previous (value) sibling");
        default:
            this->result = Contradicting;
            break;
        }
        return CONTINUE; // always continue to detect errors in data
    }

//-----------------------------------------------------------------------------
} // anonymous
//-----------------------------------------------------------------------------
    } // configuration
} // configmgr

<commit_msg>INTEGRATION: CWS changefileheader (1.22.16); FILE MERGED 2008/04/01 12:27:38 thb 1.22.16.2: #i85898# Stripping all external header guards 2008/03/31 12:22:56 rt 1.22.16.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: templateimpl.cxx,v $
 * $Revision: 1.23 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_configmgr.hxx"

#include <stdio.h>
#include "templateimpl.hxx"
#include "treeprovider.hxx"
#include "nodevisitor.hxx"
#include "treeaccessor.hxx"
#include "nodeaccess.hxx"
#include "valuenodeaccess.hxx"
#include "setnodeaccess.hxx"
#include "strdecl.hxx"
#include "typeconverter.hxx"
#include "localizedtreeactions.hxx"
#include "treeactions.hxx"
#include "apitypes.hxx"

#ifndef INCLUDED_MAP
#include <map>
#define INCLUDED_MAP
#endif

namespace configmgr
{
    namespace configuration
    {
//-----------------------------------------------------------------------------

Name TemplateName::makeSimpleTypeName(UnoType const& aType)
{
    OUString sTypeName = toTemplateName(aType);
    return makeName(sTypeName, Name::NoValidate());
}
//-----------------------------------------------------------------------------

UnoType TemplateName::resolveSimpleTypeName(Name const& aName)
{
    OUString sTypeName = aName.toString();
    return parseTemplateName(sTypeName);
}
//-----------------------------------------------------------------------------

Name TemplateName::makeNativeTypeModuleName()
{
    OUString aModuleName( TEMPLATE_MODULE_NATIVE_VALUE );
    return makeName(aModuleName, Name::NoValidate());
}
//-----------------------------------------------------------------------------
Name TemplateName::makeLocalizedTypeModuleName()
{
    OUString aModuleName( TEMPLATE_MODULE_LOCALIZED_VALUE );
    return makeName(aModuleName, Name::NoValidate());
}
//-----------------------------------------------------------------------------
bool TemplateName::isSimpleTypeName() const
{
    bool bIsSimple = (aModule.toString().compareToAscii(TEMPLATE_MODULE_NATIVE_PREFIX,
                                                        TEMPLATE_MODULE_NATIVE_PREFIX.getLength()) == 0);

    OSL_ENSURE(!bIsSimple ||
                aModule == makeNativeTypeModuleName() ||
                aModule == makeLocalizedTypeModuleName(),
                "ERROR: Invalid template module with native prefix found");

    return bIsSimple;
}
//-----------------------------------------------------------------------------

UnoType TemplateName::resolveToSimpleType() const
{
    UnoType aType;
    if ( isSimpleTypeName() )
    {
        aType = resolveSimpleTypeName( aName );
    }
    else
        OSL_ENSURE(false, "TemplateName::resolveToSimpleType must be called only for simple type name pairs");
    return aType;
}
//-----------------------------------------------------------------------------
// class TemplateImplHelper
//-----------------------------------------------------------------------------

TemplateHolder TemplateImplHelper::createNew (TemplateName const& aNames,UnoType const& aType)
{
    return new Template(aNames.aName, aNames.aModule, aType);
}
//-----------------------------------------------------------------------------

TemplateHolder TemplateImplHelper::makeSpecialTemplate (TemplateName const& aNames, SpecialTemplateProvider const& aProvider, UnoType const& aType)
{
    OSL_ENSURE(aProvider.m_aImpl.is(), "Cannot find a template without a provider");

    if (aProvider.m_aImpl.is())
        return aProvider.m_aImpl->makeTemplate(aNames,aType);

    else
        return TemplateHolder(0);
}
//-----------------------------------------------------------------------------

TemplateHolder TemplateImplHelper::makeElementTemplateWithType(TemplateName const& _aNames, TemplateProvider const& _aProvider, data::SetNodeAccess const& _aSet)
{
    OSL_ENSURE(_aProvider.m_aImpl.is(), "ERROR: Cannot find a template without a provider");

    if (_aProvider.m_aImpl.is())
        return _aProvider.m_aImpl->makeElementTemplateWithType(_aNames,_aSet);

    else
        return TemplateHolder(0);
}
//-----------------------------------------------------------------------------

void TemplateImplHelper::assignActualType (Template& aTemplate,UnoType const& aType)
{
    OSL_PRECOND( aType != getNoTypeAvailable(), "ERROR: Assigning NO type to a template" );

    if (!aTemplate.isInstanceTypeKnown())
        aTemplate.m_aInstanceType = aType;

    OSL_ENSURE(aTemplate.isInstanceTypeKnown(), "ERROR: Could not assign given type to a template");
    OSL_ENSURE(aTemplate.getInstanceType() == aType, "ERROR: Trying to change instance type of a template");
}
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// class SpecialTemplateProvider_Impl
//-----------------------------------------------------------------------------

SpecialTemplateProvider_Impl::SpecialTemplateProvider_Impl()
: m_aRepository()
{
}
//-----------------------------------------------------------------------------

TemplateHolder SpecialTemplateProvider_Impl::makeTemplate (TemplateName const& aNames, UnoType const& aType)
{
    typedef TemplateRepository::value_type Entry;

    TemplateRepository::iterator it = m_aRepository.find(aNames);
    if (it == m_aRepository.end())
        it = m_aRepository.insert( Entry( aNames, TemplateImplHelper::createNew(aNames,aType) ) ).first;

    else if (!it->second->isInstanceTypeKnown())
        TemplateImplHelper::assignActualType(*it->second, aType);

    OSL_ENSURE(it->second->isInstanceTypeKnown(), "No type assigned to Template");
    OSL_ENSURE(it->second->getInstanceType() == aType, "Inconsistent type found for Template");
    return it->second;

}

//-----------------------------------------------------------------------------
// class TemplateProvider_Impl
//-----------------------------------------------------------------------------

TemplateProvider_Impl::TemplateProvider_Impl(TemplateManagerRef const & xProvider, RequestOptions const& aOptions)
: m_xProvider(xProvider)
, m_aOptions(aOptions)
, m_aRepository()
{
}
//-----------------------------------------------------------------------------

data::TreeSegment TemplateProvider_Impl::instantiate(TemplateHolder const& aTemplate)
{
    data::TreeSegment pRet;
    if (aTemplate.is())
    {
        data::TreeAccessor aTemplateData = m_xProvider->requestTemplate(aTemplate->getName(), aTemplate->getModule());

        pRet = cloneExpandedForLocale(aTemplateData, m_aOptions.getLocale());
    }
    return pRet;
}
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
namespace
{
    using namespace data;
//-----------------------------------------------------------------------------
    struct TypeDetector : SetVisitor
    {
        enum State
        {
            Contradicting = -1,
            NotFound = 0,
            SomeValue,
            VariousValue,
            SomeTree
        };

        State   result;
        UnoType type;

        TypeDetector() : result(NotFound), type() {}

       protected:
            using SetVisitor::handle;

    private: // NodeAction implementation
        Result handle(ValueNodeAccess const& _aValueNode);
        Result handle(NodeAccess const& _aNonValueNode);
    };
//-----------------------------------------------------------------------------
    static UnoType detectNodeType(TreeAccessor const& _aElement)
    {
        if (_aElement == NULL)
            throw configuration::Exception("Could not load required template to detect set elements");

        TypeDetector aDetector;
        aDetector.visitTree( _aElement );

        switch(aDetector.result)
        {
        case TypeDetector::SomeTree:        // found tree
        case TypeDetector::VariousValue:    // found an Any
        case TypeDetector::SomeValue:       // found a particular value type
            break;

#ifdef DBG_UTIL
        case TypeDetector::NotFound:        OSL_ENSURE(false,"Impossible Result: Node not handled");        if (false) // dirty abuse of case
        case TypeDetector::Contradicting:   OSL_ENSURE(false,"Impossible Result: Node contradicts itself"); if (false) // dirty abuse of case
#endif // DBG_UTIL
        default:                            OSL_ENSURE(false,"Impossible Result: Unknown result code");

            throw configuration::Exception("INTERNAL ERROR: Could not detect set element type from loaded instance");
        }
        return aDetector.type;
    }

    //-------------------------------------------------------------------------
    static bool detectElementType(UnoType& aType, data::SetNodeAccess const& _aSet)
    {
        TypeDetector aDetector;
        aDetector.visitElements( _aSet );

        bool bResult = false;
        switch(aDetector.result)
        {
        case TypeDetector::SomeTree:        // found tree
        case TypeDetector::VariousValue:    // found an Any
            aType = aDetector.type;
            bResult = true;
            break;

        case TypeDetector::SomeValue:       // found a value or an any
        case TypeDetector::NotFound:        // found no element
            break;

        case TypeDetector::Contradicting:
            OSL_ENSURE(false,"Invalid Set: contains values and subtrees");
            break;

        default: OSL_ENSURE(false,"Unreachable code");  break;
        }
        return bResult;
    }
//-----------------------------------------------------------------------------

}
//-----------------------------------------------------------------------------
TemplateHolder TemplateProvider_Impl::makeElementTemplateWithType(TemplateName const& _aNames, data::SetNodeAccess const& _aSet)
{
    typedef TemplateRepository::value_type Entry;

    TemplateRepository::iterator it = m_aRepository.find(_aNames);

    if (it == m_aRepository.end() || !it->second->isInstanceTypeKnown())
    {
        UnoType aType;
        if (_aNames.isSimpleTypeName()) // native type found
        {
            aType = _aNames.resolveToSimpleType();

            if (aType == TemplateImplHelper::getNoTypeAvailable())
                throw configuration::Exception("INTERNAL ERROR: Could not resolve native type");
        }

        else if (!detectElementType(aType,_aSet))
        {
            OSL_ASSERT(_aNames.aName == _aSet.getElementTemplateName());
            OSL_ASSERT(_aNames.aModule == _aSet.getElementTemplateModule());

            data::TreeAccessor aTemplateData = m_xProvider->requestTemplate(_aNames.aName, _aNames.aModule);

            aType = detectNodeType(aTemplateData); // throws if necessary
        }
        OSL_ASSERT( aType != TemplateImplHelper::getNoTypeAvailable() );

        if (it == m_aRepository.end())
            it = m_aRepository.insert( Entry( _aNames, TemplateImplHelper::createNew(_aNames,aType) ) ).first;

        else
            TemplateImplHelper::assignActualType(*it->second, aType);

        OSL_ENSURE(it->second->isInstanceTypeKnown(), "No type assigned to Template");
        OSL_ENSURE(it->second->getInstanceType() == aType, "Inconsistent type found for Template");
    }

#ifdef DBG_UTIL
    else
    {
        OSL_ENSURE(it->second->isInstanceTypeKnown(), "No type assigned to Template");
        UnoType aTestType;
        if (detectElementType(aTestType,_aSet))
            OSL_ENSURE(it->second->getInstanceType() == aTestType, "Inconsistent type found for Template");
    }
#endif // DBG_UTIL

    return it->second;

}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
namespace
{
//-----------------------------------------------------------------------------
    TypeDetector::Result TypeDetector::handle(ValueNodeAccess const& _aValueNode)
    {
        UnoType aFoundType = _aValueNode.getValueType();

        bool isNullType = (aFoundType.getTypeClass() == uno::TypeClass_VOID);
        bool isAnyType  = (aFoundType.getTypeClass() == uno::TypeClass_ANY);

        switch (this->result) // transition depends on previous state
        {
        case NotFound:
            this->type = aFoundType;

            if (isAnyType)
                this->result = VariousValue;

            else if (!isNullType)
                this->result = SomeValue;

            break;

        case SomeValue:
            if (!isNullType && this->type != aFoundType)
            {
                this->result = VariousValue;
                this->type =  configapi::getAnyType();
                OSL_ASSERT(type.getTypeClass() == uno::TypeClass_ANY);
            }
            break;

        case VariousValue: // remain unchanged - type already is 'Any'
            break;

        case SomeTree: OSL_ENSURE(false, "Found value node does not match previous (tree) sibling");
        default:
            this->result = Contradicting;
            break;
        }
        return CONTINUE; // always continue to detect errors in data
    }
//-----------------------------------------------------------------------------
    TypeDetector::Result TypeDetector::handle(NodeAccess const& _aNonValueNode)
    {
            { (void)_aNonValueNode; }
        OSL_ENSURE(!ValueNodeAccess::isInstance(_aNonValueNode),"Value node dipatched to wrong handler");
        switch (this->result) // transition depends on previous state
        {
        case NotFound:
            this->type = configapi::getUnoInterfaceType();
            this->result = SomeTree;
            break;

        case SomeTree: // remain unchanged - type already is Tree
            break;

        case SomeValue:
        case VariousValue:  OSL_ENSURE(false, "Found Subtree node does not match previous (value) sibling");
        default:
            this->result = Contradicting;
            break;
        }
        return CONTINUE; // always continue to detect errors in data
    }

//-----------------------------------------------------------------------------
} // anonymous
//-----------------------------------------------------------------------------
    } // configuration
} // configmgr

<|endoftext|>


<commit_before><commit_msg>X11: set window type hint<commit_after><|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "query.h"
#include <vespa/vespalib/objects/visit.hpp>

namespace search {

void QueryConnector::visitMembers(vespalib::ObjectVisitor &visitor) const
{
    visit(visitor, "Operator", _opName);
}

QueryConnector::QueryConnector(const char * opName) :
  QueryNode(),
  _opName(opName),
  _index()
{
}

QueryConnector::~QueryConnector() = default;

const HitList & QueryConnector::evaluateHits(HitList & hl) const
{
    if (evaluate()) {
        hl.push_back(Hit(1, 0, 0, 1));
    }
    return hl;
}

void QueryConnector::reset()
{
    for(const auto & node : *this) {
        node->reset();
    }
}

void QueryConnector::getLeafs(QueryTermList & tl)
{
    for(const auto & node : *this) {
        node->getLeafs(tl);
    }
}

void QueryConnector::getLeafs(ConstQueryTermList & tl) const
{
    for(const auto & node : *this) {
        node->getLeafs(tl);
    }
}

void QueryConnector::getPhrases(QueryNodeRefList & tl)
{
    for(const auto & node : *this) {
        node->getPhrases(tl);
    }
}

void QueryConnector::getPhrases(ConstQueryNodeRefList & tl) const
{
    for(const auto & node : *this) {
        node->getPhrases(tl);
    }
}

size_t QueryConnector::depth() const
{
    size_t d(0);
    for(const auto & node : *this) {
        size_t t = node->depth();
        if (t > d) {
            d = t;
        }
    }
    return d+1;
}

size_t QueryConnector::width() const
{
  size_t w(0);
  for(const auto & node : *this) {
    w += node->width();
  }

  return w;
}

std::unique_ptr<QueryConnector>
QueryConnector::create(ParseItem::ItemType type)
{
    switch (type) {
        case search::ParseItem::ITEM_AND:          return std::make_unique<AndQueryNode>();
        case search::ParseItem::ITEM_OR:           return std::make_unique<OrQueryNode>();
        case search::ParseItem::ITEM_WEAK_AND:     return std::make_unique<OrQueryNode>();
        case search::ParseItem::ITEM_EQUIV:        return std::make_unique<EquivQueryNode>();
        case search::ParseItem::ITEM_WEIGHTED_SET: return std::make_unique<EquivQueryNode>();
        case search::ParseItem::ITEM_DOT_PRODUCT:  return std::make_unique<OrQueryNode>();
        case search::ParseItem::ITEM_WAND:         return std::make_unique<OrQueryNode>();
        case search::ParseItem::ITEM_NOT:          return std::make_unique<AndNotQueryNode>();
        case search::ParseItem::ITEM_PHRASE:       return std::make_unique<PhraseQueryNode>();
        case search::ParseItem::ITEM_SAME_ELEMENT: return std::make_unique<SameElementQueryNode>();
        case search::ParseItem::ITEM_NEAR:         return std::make_unique<NearQueryNode>();
        case search::ParseItem::ITEM_ONEAR:        return std::make_unique<ONearQueryNode>();
        default: return nullptr;
    }
}

bool TrueNode::evaluate() const
{
    return true;
}

bool AndQueryNode::evaluate() const
{
  bool ok(true);
  for (const_iterator it=begin(), mt=end(); ok && (it!=mt); it++) {
    const QueryNode & qn = **it;
    ok = ok && qn.evaluate();
  }
  return ok;
}

bool AndNotQueryNode::evaluate() const
{
  bool ok(empty() ? true : front()->evaluate());
  if (!empty()) {
    for (const_iterator it=begin()+1, mt=end(); ok && (it!=mt); it++) {
      const QueryNode & qn = **it;
      ok = ok && ! qn.evaluate();
    }
  }
  return ok;
}

bool OrQueryNode::evaluate() const
{
  bool ok(false);
  for (const_iterator it=begin(), mt=end(); !ok && (it!=mt); it++) {
    const QueryNode & qn = **it;
    ok = qn.evaluate();
  }
  return ok;
}

bool EquivQueryNode::evaluate() const
{
    return OrQueryNode::evaluate();
}

bool SameElementQueryNode::evaluate() const {
    HitList hl;
    return ! evaluateHits(hl).empty();
}

const HitList &
SameElementQueryNode::evaluateHits(HitList & hl) const
{
    hl.clear();
    if ( !AndQueryNode::evaluate()) return hl;

    HitList tmpHL;
    unsigned int numFields = size();
    unsigned int currMatchCount = 0;
    std::vector<unsigned int> indexVector(numFields, 0);
    auto curr = static_cast<const QueryTerm *> ((*this)[currMatchCount].get());
    bool exhausted( curr->evaluateHits(tmpHL).empty());
    for (; !exhausted; ) {
        auto next = static_cast<const QueryTerm *>((*this)[currMatchCount+1].get());
        unsigned int & currIndex = indexVector[currMatchCount];
        unsigned int & nextIndex = indexVector[currMatchCount+1];

        const auto & currHit = curr->evaluateHits(tmpHL)[currIndex];
        uint32_t currElemId = currHit.elemId();

        const HitList & nextHL = next->evaluateHits(tmpHL);

        size_t nextIndexMax = nextHL.size();
        while ((nextIndex < nextIndexMax) && (nextHL[nextIndex].elemId() < currElemId)) {
            nextIndex++;
        }
        if (nextHL[nextIndex].elemId() == currElemId) {
            currMatchCount++;
            if ((currMatchCount+1) == numFields) {
                Hit h = nextHL[indexVector[currMatchCount]];
                hl.emplace_back(0, h.context(), h.elemId(), h.weight());
                currMatchCount = 0;
                indexVector[0]++;
            }
        } else {
            currMatchCount = 0;
            indexVector[currMatchCount]++;
        }
        curr = static_cast<const QueryTerm *>((*this)[currMatchCount].get());
        exhausted = (nextIndex >= nextIndexMax) || (indexVector[currMatchCount] >= curr->evaluateHits(tmpHL).size());
    }
    return hl;
}

bool PhraseQueryNode::evaluate() const
{
  HitList hl;
  return ! evaluateHits(hl).empty();
}

void PhraseQueryNode::getPhrases(QueryNodeRefList & tl)            { tl.push_back(this); }
void PhraseQueryNode::getPhrases(ConstQueryNodeRefList & tl) const { tl.push_back(this); }

const HitList &
PhraseQueryNode::evaluateHits(HitList & hl) const
{
    hl.clear();
    _fieldInfo.clear();
    if ( ! AndQueryNode::evaluate()) return hl;

    HitList tmpHL;
    unsigned int fullPhraseLen = size();
    unsigned int currPhraseLen = 0;
    std::vector<unsigned int> indexVector(fullPhraseLen, 0);
    auto curr = static_cast<const QueryTerm *> ((*this)[currPhraseLen].get());
    bool exhausted( curr->evaluateHits(tmpHL).empty());
    for (; !exhausted; ) {
        auto next = static_cast<const QueryTerm *>((*this)[currPhraseLen+1].get());
        unsigned int & currIndex = indexVector[currPhraseLen];
        unsigned int & nextIndex = indexVector[currPhraseLen+1];

        const auto & currHit = curr->evaluateHits(tmpHL)[currIndex];
        size_t firstPosition = currHit.pos();
        uint32_t currElemId = currHit.elemId();
        uint32_t currContext = currHit.context();

        const HitList & nextHL = next->evaluateHits(tmpHL);

        int diff(0);
        size_t nextIndexMax = nextHL.size();
        while ((nextIndex < nextIndexMax) &&
              ((nextHL[nextIndex].context() < currContext) ||
               ((nextHL[nextIndex].context() == currContext) && (nextHL[nextIndex].elemId() <= currElemId))) &&
             ((diff = nextHL[nextIndex].pos()-firstPosition) < 1))
        {
            nextIndex++;
        }
        if ((diff == 1) && (nextHL[nextIndex].context() == currContext) && (nextHL[nextIndex].elemId() == currElemId)) {
            currPhraseLen++;
            if ((currPhraseLen+1) == fullPhraseLen) {
                Hit h = nextHL[indexVector[currPhraseLen]];
                hl.push_back(h);
                const QueryTerm::FieldInfo & fi = next->getFieldInfo(h.context());
                updateFieldInfo(h.context(), hl.size() - 1, fi.getFieldLength());
                currPhraseLen = 0;
                indexVector[0]++;
            }
        } else {
            currPhraseLen = 0;
            indexVector[currPhraseLen]++;
        }
        curr = static_cast<const QueryTerm *>((*this)[currPhraseLen].get());
        exhausted = (nextIndex >= nextIndexMax) || (indexVector[currPhraseLen] >= curr->evaluateHits(tmpHL).size());
    }
    return hl;
}

void
PhraseQueryNode::updateFieldInfo(size_t fid, size_t offset, size_t fieldLength) const
{
    if (fid >= _fieldInfo.size()) {
        _fieldInfo.resize(fid + 1);
        // only set hit offset and field length the first time
        QueryTerm::FieldInfo & fi = _fieldInfo[fid];
        fi.setHitOffset(offset);
        fi.setFieldLength(fieldLength);
    }
    QueryTerm::FieldInfo & fi = _fieldInfo[fid];
    fi.setHitCount(fi.getHitCount() + 1);
}

bool NotQueryNode::evaluate() const
{
  bool ok(false);
  for (const auto & node : *this) {
    ok |= ! node->evaluate();
  }
  return ok;
}

bool NearQueryNode::evaluate() const
{
  bool ok(AndQueryNode::evaluate());
  return ok;
}

void NearQueryNode::visitMembers(vespalib::ObjectVisitor &visitor) const
{
    AndQueryNode::visitMembers(visitor);
    visit(visitor, "distance", static_cast<uint64_t>(_distance));
}

bool ONearQueryNode::evaluate() const
{
  bool ok(NearQueryNode::evaluate());
  return ok;
}

Query::Query() = default;

Query::Query(const QueryNodeResultFactory & factory, const QueryPacketT & queryRep) :
  _root()
{
  build(factory, queryRep);
}

bool Query::evaluate() const
{
  bool ok = valid() ? _root->evaluate() : false;
  return ok;
}

bool Query::build(const QueryNodeResultFactory & factory, const QueryPacketT & queryRep)
{
    search::SimpleQueryStackDumpIterator stack(queryRep);
    if (stack.next()) {
        _root = QueryNode::Build(nullptr, factory, stack, true);
    }
    return valid();
}

void Query::getLeafs(QueryTermList & tl)
{
  if (valid()) {
    _root->getLeafs(tl);
  }
}

void Query::getLeafs(ConstQueryTermList & tl) const
{
  if (valid()) {
    _root->getLeafs(tl);
  }
}

void Query::getPhrases(QueryNodeRefList & tl)
{
  if (valid()) {
    _root->getPhrases(tl);
  }
}

void Query::getPhrases(ConstQueryNodeRefList & tl) const
{
  if (valid()) {
    _root->getPhrases(tl);
  }
}

void Query::reset()
{
  if (valid()) {
    _root->reset();
  }
}

size_t Query::depth() const
{
  return valid() ? _root->depth() : 0;
}

size_t Query::width() const
{
  return valid() ? _root->width() : 0;
}

}
<commit_msg>Do not read past the end.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "query.h"
#include <vespa/vespalib/objects/visit.hpp>

namespace search {

void QueryConnector::visitMembers(vespalib::ObjectVisitor &visitor) const
{
    visit(visitor, "Operator", _opName);
}

QueryConnector::QueryConnector(const char * opName) :
  QueryNode(),
  _opName(opName),
  _index()
{
}

QueryConnector::~QueryConnector() = default;

const HitList & QueryConnector::evaluateHits(HitList & hl) const
{
    if (evaluate()) {
        hl.push_back(Hit(1, 0, 0, 1));
    }
    return hl;
}

void QueryConnector::reset()
{
    for(const auto & node : *this) {
        node->reset();
    }
}

void QueryConnector::getLeafs(QueryTermList & tl)
{
    for(const auto & node : *this) {
        node->getLeafs(tl);
    }
}

void QueryConnector::getLeafs(ConstQueryTermList & tl) const
{
    for(const auto & node : *this) {
        node->getLeafs(tl);
    }
}

void QueryConnector::getPhrases(QueryNodeRefList & tl)
{
    for(const auto & node : *this) {
        node->getPhrases(tl);
    }
}

void QueryConnector::getPhrases(ConstQueryNodeRefList & tl) const
{
    for(const auto & node : *this) {
        node->getPhrases(tl);
    }
}

size_t QueryConnector::depth() const
{
    size_t d(0);
    for(const auto & node : *this) {
        size_t t = node->depth();
        if (t > d) {
            d = t;
        }
    }
    return d+1;
}

size_t QueryConnector::width() const
{
  size_t w(0);
  for(const auto & node : *this) {
    w += node->width();
  }

  return w;
}

std::unique_ptr<QueryConnector>
QueryConnector::create(ParseItem::ItemType type)
{
    switch (type) {
        case search::ParseItem::ITEM_AND:          return std::make_unique<AndQueryNode>();
        case search::ParseItem::ITEM_OR:           return std::make_unique<OrQueryNode>();
        case search::ParseItem::ITEM_WEAK_AND:     return std::make_unique<OrQueryNode>();
        case search::ParseItem::ITEM_EQUIV:        return std::make_unique<EquivQueryNode>();
        case search::ParseItem::ITEM_WEIGHTED_SET: return std::make_unique<EquivQueryNode>();
        case search::ParseItem::ITEM_DOT_PRODUCT:  return std::make_unique<OrQueryNode>();
        case search::ParseItem::ITEM_WAND:         return std::make_unique<OrQueryNode>();
        case search::ParseItem::ITEM_NOT:          return std::make_unique<AndNotQueryNode>();
        case search::ParseItem::ITEM_PHRASE:       return std::make_unique<PhraseQueryNode>();
        case search::ParseItem::ITEM_SAME_ELEMENT: return std::make_unique<SameElementQueryNode>();
        case search::ParseItem::ITEM_NEAR:         return std::make_unique<NearQueryNode>();
        case search::ParseItem::ITEM_ONEAR:        return std::make_unique<ONearQueryNode>();
        default: return nullptr;
    }
}

bool TrueNode::evaluate() const
{
    return true;
}

bool AndQueryNode::evaluate() const
{
  bool ok(true);
  for (const_iterator it=begin(), mt=end(); ok && (it!=mt); it++) {
    const QueryNode & qn = **it;
    ok = ok && qn.evaluate();
  }
  return ok;
}

bool AndNotQueryNode::evaluate() const
{
  bool ok(empty() ? true : front()->evaluate());
  if (!empty()) {
    for (const_iterator it=begin()+1, mt=end(); ok && (it!=mt); it++) {
      const QueryNode & qn = **it;
      ok = ok && ! qn.evaluate();
    }
  }
  return ok;
}

bool OrQueryNode::evaluate() const
{
  bool ok(false);
  for (const_iterator it=begin(), mt=end(); !ok && (it!=mt); it++) {
    const QueryNode & qn = **it;
    ok = qn.evaluate();
  }
  return ok;
}

bool EquivQueryNode::evaluate() const
{
    return OrQueryNode::evaluate();
}

bool SameElementQueryNode::evaluate() const {
    HitList hl;
    return ! evaluateHits(hl).empty();
}

const HitList &
SameElementQueryNode::evaluateHits(HitList & hl) const
{
    hl.clear();
    if ( !AndQueryNode::evaluate()) return hl;

    HitList tmpHL;
    unsigned int numFields = size();
    unsigned int currMatchCount = 0;
    std::vector<unsigned int> indexVector(numFields, 0);
    auto curr = static_cast<const QueryTerm *> ((*this)[currMatchCount].get());
    bool exhausted( curr->evaluateHits(tmpHL).empty());
    for (; !exhausted; ) {
        auto next = static_cast<const QueryTerm *>((*this)[currMatchCount+1].get());
        unsigned int & currIndex = indexVector[currMatchCount];
        unsigned int & nextIndex = indexVector[currMatchCount+1];

        const auto & currHit = curr->evaluateHits(tmpHL)[currIndex];
        uint32_t currElemId = currHit.elemId();

        const HitList & nextHL = next->evaluateHits(tmpHL);

        size_t nextIndexMax = nextHL.size();
        while ((nextIndex < nextIndexMax) && (nextHL[nextIndex].elemId() < currElemId)) {
            nextIndex++;
        }
        if ((nextIndex < nextIndexMax) && (nextHL[nextIndex].elemId() == currElemId)) {
            currMatchCount++;
            if ((currMatchCount+1) == numFields) {
                Hit h = nextHL[indexVector[currMatchCount]];
                hl.emplace_back(0, h.context(), h.elemId(), h.weight());
                currMatchCount = 0;
                indexVector[0]++;
            }
        } else {
            currMatchCount = 0;
            indexVector[currMatchCount]++;
        }
        curr = static_cast<const QueryTerm *>((*this)[currMatchCount].get());
        exhausted = (nextIndex >= nextIndexMax) || (indexVector[currMatchCount] >= curr->evaluateHits(tmpHL).size());
    }
    return hl;
}

bool PhraseQueryNode::evaluate() const
{
  HitList hl;
  return ! evaluateHits(hl).empty();
}

void PhraseQueryNode::getPhrases(QueryNodeRefList & tl)            { tl.push_back(this); }
void PhraseQueryNode::getPhrases(ConstQueryNodeRefList & tl) const { tl.push_back(this); }

const HitList &
PhraseQueryNode::evaluateHits(HitList & hl) const
{
    hl.clear();
    _fieldInfo.clear();
    if ( ! AndQueryNode::evaluate()) return hl;

    HitList tmpHL;
    unsigned int fullPhraseLen = size();
    unsigned int currPhraseLen = 0;
    std::vector<unsigned int> indexVector(fullPhraseLen, 0);
    auto curr = static_cast<const QueryTerm *> ((*this)[currPhraseLen].get());
    bool exhausted( curr->evaluateHits(tmpHL).empty());
    for (; !exhausted; ) {
        auto next = static_cast<const QueryTerm *>((*this)[currPhraseLen+1].get());
        unsigned int & currIndex = indexVector[currPhraseLen];
        unsigned int & nextIndex = indexVector[currPhraseLen+1];

        const auto & currHit = curr->evaluateHits(tmpHL)[currIndex];
        size_t firstPosition = currHit.pos();
        uint32_t currElemId = currHit.elemId();
        uint32_t currContext = currHit.context();

        const HitList & nextHL = next->evaluateHits(tmpHL);

        int diff(0);
        size_t nextIndexMax = nextHL.size();
        while ((nextIndex < nextIndexMax) &&
              ((nextHL[nextIndex].context() < currContext) ||
               ((nextHL[nextIndex].context() == currContext) && (nextHL[nextIndex].elemId() <= currElemId))) &&
             ((diff = nextHL[nextIndex].pos()-firstPosition) < 1))
        {
            nextIndex++;
        }
        if ((diff == 1) && (nextHL[nextIndex].context() == currContext) && (nextHL[nextIndex].elemId() == currElemId)) {
            currPhraseLen++;
            if ((currPhraseLen+1) == fullPhraseLen) {
                Hit h = nextHL[indexVector[currPhraseLen]];
                hl.push_back(h);
                const QueryTerm::FieldInfo & fi = next->getFieldInfo(h.context());
                updateFieldInfo(h.context(), hl.size() - 1, fi.getFieldLength());
                currPhraseLen = 0;
                indexVector[0]++;
            }
        } else {
            currPhraseLen = 0;
            indexVector[currPhraseLen]++;
        }
        curr = static_cast<const QueryTerm *>((*this)[currPhraseLen].get());
        exhausted = (nextIndex >= nextIndexMax) || (indexVector[currPhraseLen] >= curr->evaluateHits(tmpHL).size());
    }
    return hl;
}

void
PhraseQueryNode::updateFieldInfo(size_t fid, size_t offset, size_t fieldLength) const
{
    if (fid >= _fieldInfo.size()) {
        _fieldInfo.resize(fid + 1);
        // only set hit offset and field length the first time
        QueryTerm::FieldInfo & fi = _fieldInfo[fid];
        fi.setHitOffset(offset);
        fi.setFieldLength(fieldLength);
    }
    QueryTerm::FieldInfo & fi = _fieldInfo[fid];
    fi.setHitCount(fi.getHitCount() + 1);
}

bool NotQueryNode::evaluate() const
{
  bool ok(false);
  for (const auto & node : *this) {
    ok |= ! node->evaluate();
  }
  return ok;
}

bool NearQueryNode::evaluate() const
{
  bool ok(AndQueryNode::evaluate());
  return ok;
}

void NearQueryNode::visitMembers(vespalib::ObjectVisitor &visitor) const
{
    AndQueryNode::visitMembers(visitor);
    visit(visitor, "distance", static_cast<uint64_t>(_distance));
}

bool ONearQueryNode::evaluate() const
{
  bool ok(NearQueryNode::evaluate());
  return ok;
}

Query::Query() = default;

Query::Query(const QueryNodeResultFactory & factory, const QueryPacketT & queryRep) :
  _root()
{
  build(factory, queryRep);
}

bool Query::evaluate() const
{
  bool ok = valid() ? _root->evaluate() : false;
  return ok;
}

bool Query::build(const QueryNodeResultFactory & factory, const QueryPacketT & queryRep)
{
    search::SimpleQueryStackDumpIterator stack(queryRep);
    if (stack.next()) {
        _root = QueryNode::Build(nullptr, factory, stack, true);
    }
    return valid();
}

void Query::getLeafs(QueryTermList & tl)
{
  if (valid()) {
    _root->getLeafs(tl);
  }
}

void Query::getLeafs(ConstQueryTermList & tl) const
{
  if (valid()) {
    _root->getLeafs(tl);
  }
}

void Query::getPhrases(QueryNodeRefList & tl)
{
  if (valid()) {
    _root->getPhrases(tl);
  }
}

void Query::getPhrases(ConstQueryNodeRefList & tl) const
{
  if (valid()) {
    _root->getPhrases(tl);
  }
}

void Query::reset()
{
  if (valid()) {
    _root->reset();
  }
}

size_t Query::depth() const
{
  return valid() ? _root->depth() : 0;
}

size_t Query::width() const
{
  return valid() ? _root->width() : 0;
}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dispatchinformationprovider.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: ihi $ $Date: 2007-04-16 16:38:29 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_DISPATCH_DISPATCHINFORMATIONPROVIDER_HXX_
#include <dispatch/dispatchinformationprovider.hxx>
#endif

#ifndef __FRAMEWORK_DISPATCH_CLOSEDISPATCHER_HXX_
#include <dispatch/closedispatcher.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif

#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif

#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_FRAME_COMMANDGROUP_HPP_
#include <com/sun/star/frame/CommandGroup.hpp>
#endif

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

#ifndef _COMPHELPER_SEQUENCEASVECTOR_HXX_
#include <comphelper/sequenceasvector.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

namespace css = ::com::sun::star;

//_________________________________________________________________________________________________________________
//  declarations
//_________________________________________________________________________________________________________________
DEFINE_XINTERFACE_1(DispatchInformationProvider                               ,
                    OWeakObject                                               ,
                    DIRECT_INTERFACE(css::frame::XDispatchInformationProvider))

//_________________________________________________________________________________________________________________
DispatchInformationProvider::DispatchInformationProvider(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ,
                                                         const css::uno::Reference< css::frame::XFrame >&              xFrame)
    : ThreadHelpBase(&Application::GetSolarMutex())
    , m_xSMGR       (xSMGR                        )
    , m_xFrame      (xFrame                       )
{
}

//_________________________________________________________________________________________________________________
DispatchInformationProvider::~DispatchInformationProvider()
{
}

//_________________________________________________________________________________________________________________
css::uno::Sequence< sal_Int16 > SAL_CALL DispatchInformationProvider::getSupportedCommandGroups()
    throw (css::uno::RuntimeException)
{
    css::uno::Sequence< css::uno::Reference< css::frame::XDispatchInformationProvider > > lProvider = implts_getAllSubProvider();
    sal_Int32                                                                             c1        = lProvider.getLength();
    sal_Int32                                                                             i1        = 0;

    ::comphelper::SequenceAsVector< sal_Int16 > lGroups;

    for (i1=0; i1<c1; ++i1)
    {
        // ignore controller, which doesnt implement the right interface
        css::uno::Reference< css::frame::XDispatchInformationProvider > xProvider = lProvider[i1];
        if (!xProvider.is())
            continue;

        const css::uno::Sequence< sal_Int16 > lProviderGroups = xProvider->getSupportedCommandGroups();
              sal_Int32                       c2              = lProviderGroups.getLength();
              sal_Int32                       i2              = 0;
        for (i2=0; i2<c2; ++i2)
        {
            const sal_Int16&                                                  rGroup = lProviderGroups[i2];
                  ::comphelper::SequenceAsVector< sal_Int16 >::const_iterator pGroup = ::std::find(lGroups.begin(), lGroups.end(), rGroup);
            if (pGroup == lGroups.end())
                lGroups.push_back(rGroup);
        }
    }

    return lGroups.getAsConstList();
}

//_________________________________________________________________________________________________________________
css::uno::Sequence< css::frame::DispatchInformation > SAL_CALL DispatchInformationProvider::getConfigurableDispatchInformation(sal_Int16 nCommandGroup)
    throw (css::uno::RuntimeException)
{
    css::uno::Sequence< css::uno::Reference< css::frame::XDispatchInformationProvider > > lProvider = implts_getAllSubProvider();
    sal_Int32                                                                             c1        = lProvider.getLength();
    sal_Int32                                                                             i1        = 0;

    BaseHash< css::frame::DispatchInformation > lInfos;

    for (i1=0; i1<c1; ++i1)
    {
        try
        {
            // ignore controller, which doesnt implement the right interface
            css::uno::Reference< css::frame::XDispatchInformationProvider > xProvider = lProvider[i1];
            if (!xProvider.is())
                continue;

            const css::uno::Sequence< css::frame::DispatchInformation > lProviderInfos = xProvider->getConfigurableDispatchInformation(nCommandGroup);
                  sal_Int32                                             c2             = lProviderInfos.getLength();
                  sal_Int32                                             i2             = 0;
            for (i2=0; i2<c2; ++i2)
            {
                const css::frame::DispatchInformation&                            rInfo = lProviderInfos[i2];
                      BaseHash< css::frame::DispatchInformation >::const_iterator pInfo = lInfos.find(rInfo.Command);
                if (pInfo == lInfos.end())
                    lInfos[rInfo.Command] = rInfo;
            }
        }
        catch(const css::uno::RuntimeException& exRun)
            { throw exRun; }
        catch(const css::uno::Exception&)
            { continue; }
    }

    c1 = (sal_Int32)lInfos.size();
    i1 = 0;

    css::uno::Sequence< css::frame::DispatchInformation >       lReturn(c1);
    BaseHash< css::frame::DispatchInformation >::const_iterator pStepp ;
    for (  pStepp  = lInfos.begin()          ;
           pStepp != lInfos.end  () && i1<c1 ;
         ++pStepp, ++i1                      )
    {
        lReturn[i1] = pStepp->second;
    }
    return lReturn;
}

//_________________________________________________________________________________________________________________
css::uno::Sequence< css::uno::Reference< css::frame::XDispatchInformationProvider > > DispatchInformationProvider::implts_getAllSubProvider()
{
    // SAFE -> ----------------------------------
    ReadGuard aReadLock(m_aLock);
    css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = m_xSMGR;
    css::uno::Reference< css::frame::XFrame >              xFrame(m_xFrame.get(), css::uno::UNO_QUERY);
    aReadLock.unlock();
    // <- SAFE ----------------------------------

    if (!xFrame.is())
        return css::uno::Sequence< css::uno::Reference< css::frame::XDispatchInformationProvider > >();

    CloseDispatcher* pCloser = new CloseDispatcher(xSMGR, xFrame, ::rtl::OUString::createFromAscii("_self")); // explicit "_self" ... not "" ... see implementation of close dispatcher itself!
    css::uno::Reference< css::uno::XInterface > xCloser(static_cast< css::frame::XDispatch* >(pCloser), css::uno::UNO_QUERY);

    css::uno::Reference< css::frame::XDispatchInformationProvider > xCloseDispatch(xCloser                                                      , css::uno::UNO_QUERY);
    css::uno::Reference< css::frame::XDispatchInformationProvider > xController   (xFrame->getController()                                      , css::uno::UNO_QUERY);
    css::uno::Reference< css::frame::XDispatchInformationProvider > xAppDispatcher(xSMGR->createInstance(IMPLEMENTATIONNAME_APPDISPATCHPROVIDER), css::uno::UNO_QUERY);

    css::uno::Sequence< css::uno::Reference< css::frame::XDispatchInformationProvider > > lProvider(3);
    lProvider[0] = xController   ;
    lProvider[1] = xCloseDispatch;
    lProvider[2] = xAppDispatcher;

    return lProvider;
}

} // namespace framework
<commit_msg>INTEGRATION: CWS changefileheader (1.5.170); FILE MERGED 2008/04/01 15:18:37 thb 1.5.170.3: #i85898# Stripping all external header guards 2008/04/01 10:58:05 thb 1.5.170.2: #i85898# Stripping all external header guards 2008/03/28 15:35:14 rt 1.5.170.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: dispatchinformationprovider.cxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________
#include <dispatch/dispatchinformationprovider.hxx>
#include <dispatch/closedispatcher.hxx>
#include <threadhelp/readguard.hxx>
#include <threadhelp/writeguard.hxx>
#include <stdtypes.h>
#include <services.h>

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________
#include <com/sun/star/frame/CommandGroup.hpp>

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________
#include <comphelper/sequenceasvector.hxx>

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

namespace css = ::com::sun::star;

//_________________________________________________________________________________________________________________
//  declarations
//_________________________________________________________________________________________________________________
DEFINE_XINTERFACE_1(DispatchInformationProvider                               ,
                    OWeakObject                                               ,
                    DIRECT_INTERFACE(css::frame::XDispatchInformationProvider))

//_________________________________________________________________________________________________________________
DispatchInformationProvider::DispatchInformationProvider(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ,
                                                         const css::uno::Reference< css::frame::XFrame >&              xFrame)
    : ThreadHelpBase(&Application::GetSolarMutex())
    , m_xSMGR       (xSMGR                        )
    , m_xFrame      (xFrame                       )
{
}

//_________________________________________________________________________________________________________________
DispatchInformationProvider::~DispatchInformationProvider()
{
}

//_________________________________________________________________________________________________________________
css::uno::Sequence< sal_Int16 > SAL_CALL DispatchInformationProvider::getSupportedCommandGroups()
    throw (css::uno::RuntimeException)
{
    css::uno::Sequence< css::uno::Reference< css::frame::XDispatchInformationProvider > > lProvider = implts_getAllSubProvider();
    sal_Int32                                                                             c1        = lProvider.getLength();
    sal_Int32                                                                             i1        = 0;

    ::comphelper::SequenceAsVector< sal_Int16 > lGroups;

    for (i1=0; i1<c1; ++i1)
    {
        // ignore controller, which doesnt implement the right interface
        css::uno::Reference< css::frame::XDispatchInformationProvider > xProvider = lProvider[i1];
        if (!xProvider.is())
            continue;

        const css::uno::Sequence< sal_Int16 > lProviderGroups = xProvider->getSupportedCommandGroups();
              sal_Int32                       c2              = lProviderGroups.getLength();
              sal_Int32                       i2              = 0;
        for (i2=0; i2<c2; ++i2)
        {
            const sal_Int16&                                                  rGroup = lProviderGroups[i2];
                  ::comphelper::SequenceAsVector< sal_Int16 >::const_iterator pGroup = ::std::find(lGroups.begin(), lGroups.end(), rGroup);
            if (pGroup == lGroups.end())
                lGroups.push_back(rGroup);
        }
    }

    return lGroups.getAsConstList();
}

//_________________________________________________________________________________________________________________
css::uno::Sequence< css::frame::DispatchInformation > SAL_CALL DispatchInformationProvider::getConfigurableDispatchInformation(sal_Int16 nCommandGroup)
    throw (css::uno::RuntimeException)
{
    css::uno::Sequence< css::uno::Reference< css::frame::XDispatchInformationProvider > > lProvider = implts_getAllSubProvider();
    sal_Int32                                                                             c1        = lProvider.getLength();
    sal_Int32                                                                             i1        = 0;

    BaseHash< css::frame::DispatchInformation > lInfos;

    for (i1=0; i1<c1; ++i1)
    {
        try
        {
            // ignore controller, which doesnt implement the right interface
            css::uno::Reference< css::frame::XDispatchInformationProvider > xProvider = lProvider[i1];
            if (!xProvider.is())
                continue;

            const css::uno::Sequence< css::frame::DispatchInformation > lProviderInfos = xProvider->getConfigurableDispatchInformation(nCommandGroup);
                  sal_Int32                                             c2             = lProviderInfos.getLength();
                  sal_Int32                                             i2             = 0;
            for (i2=0; i2<c2; ++i2)
            {
                const css::frame::DispatchInformation&                            rInfo = lProviderInfos[i2];
                      BaseHash< css::frame::DispatchInformation >::const_iterator pInfo = lInfos.find(rInfo.Command);
                if (pInfo == lInfos.end())
                    lInfos[rInfo.Command] = rInfo;
            }
        }
        catch(const css::uno::RuntimeException& exRun)
            { throw exRun; }
        catch(const css::uno::Exception&)
            { continue; }
    }

    c1 = (sal_Int32)lInfos.size();
    i1 = 0;

    css::uno::Sequence< css::frame::DispatchInformation >       lReturn(c1);
    BaseHash< css::frame::DispatchInformation >::const_iterator pStepp ;
    for (  pStepp  = lInfos.begin()          ;
           pStepp != lInfos.end  () && i1<c1 ;
         ++pStepp, ++i1                      )
    {
        lReturn[i1] = pStepp->second;
    }
    return lReturn;
}

//_________________________________________________________________________________________________________________
css::uno::Sequence< css::uno::Reference< css::frame::XDispatchInformationProvider > > DispatchInformationProvider::implts_getAllSubProvider()
{
    // SAFE -> ----------------------------------
    ReadGuard aReadLock(m_aLock);
    css::uno::Reference< css::lang::XMultiServiceFactory > xSMGR = m_xSMGR;
    css::uno::Reference< css::frame::XFrame >              xFrame(m_xFrame.get(), css::uno::UNO_QUERY);
    aReadLock.unlock();
    // <- SAFE ----------------------------------

    if (!xFrame.is())
        return css::uno::Sequence< css::uno::Reference< css::frame::XDispatchInformationProvider > >();

    CloseDispatcher* pCloser = new CloseDispatcher(xSMGR, xFrame, ::rtl::OUString::createFromAscii("_self")); // explicit "_self" ... not "" ... see implementation of close dispatcher itself!
    css::uno::Reference< css::uno::XInterface > xCloser(static_cast< css::frame::XDispatch* >(pCloser), css::uno::UNO_QUERY);

    css::uno::Reference< css::frame::XDispatchInformationProvider > xCloseDispatch(xCloser                                                      , css::uno::UNO_QUERY);
    css::uno::Reference< css::frame::XDispatchInformationProvider > xController   (xFrame->getController()                                      , css::uno::UNO_QUERY);
    css::uno::Reference< css::frame::XDispatchInformationProvider > xAppDispatcher(xSMGR->createInstance(IMPLEMENTATIONNAME_APPDISPATCHPROVIDER), css::uno::UNO_QUERY);

    css::uno::Sequence< css::uno::Reference< css::frame::XDispatchInformationProvider > > lProvider(3);
    lProvider[0] = xController   ;
    lProvider[1] = xCloseDispatch;
    lProvider[2] = xAppDispatcher;

    return lProvider;
}

} // namespace framework
<|endoftext|>


<commit_before><commit_msg>don't make more calls to the disk thread when aborting<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org)
 *
 * 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.
 *
 */
#define BOOST_TEST_MAIN

#define BOOST_TEST_MODULE table_test
#include <boost/lexical_cast.hpp>
#include <boost/test/unit_test.hpp>
#include <exception>
#include <iostream>
#include <votca/tools/table.h>

using namespace std;
using namespace votca::tools;

BOOST_AUTO_TEST_SUITE(table_test)

BOOST_AUTO_TEST_CASE(create_test) {
  Table tb;
  Table tb2(tb);
}

BOOST_AUTO_TEST_CASE(size_test) {
  Table tb;
  BOOST_CHECK_EQUAL(tb.size(), 0);
}

BOOST_AUTO_TEST_CASE(pushback_test) {
  Table tb;
  for (double x = 0; x < 10; ++x) {
    double y = 2 * x;
    tb.push_back(x, y);
  }
  BOOST_CHECK_EQUAL(tb.size(), 10);
}

BOOST_AUTO_TEST_CASE(resize_test) {
  Table tb;
  tb.resize(0);
  tb.resize(10);

  bool error_thrown = false;
  try {
    tb.resize(-5);
  } catch (...) {
    error_thrown = true;
  }
  BOOST_CHECK(error_thrown);
}

BOOST_AUTO_TEST_CASE(xy_test) {
  Table tb;
  for (double x = 0; x < 10; ++x) {
    double y = 2 * x;
    tb.push_back(x, y);
  }

  auto x_v = tb.x();
  auto y_v = tb.y();
  for (votca::Index i = 0; i < 10; ++i) {
    votca::Index x = i;
    votca::Index y = 2 * x;
    BOOST_CHECK_EQUAL(static_cast<votca::Index>(x_v(i)),
                      static_cast<votca::Index>(tb.x(i)));
    BOOST_CHECK_EQUAL(static_cast<votca::Index>(y_v(i)),
                      static_cast<votca::Index>(tb.y(i)));
    BOOST_CHECK_EQUAL(x, static_cast<votca::Index>(tb.x(i)));
    BOOST_CHECK_EQUAL(y, static_cast<votca::Index>(tb.y(i)));
    BOOST_CHECK_EQUAL(x, static_cast<votca::Index>(x_v(i)));
    BOOST_CHECK_EQUAL(y, static_cast<votca::Index>(y_v(i)));
  }
}

BOOST_AUTO_TEST_CASE(getMinMax_test) {
  Table tb;
  for (double x = 0; x < 10; ++x) {
    double y = 2 * x;
    tb.push_back(x, y);
  }

  BOOST_CHECK_EQUAL(static_cast<votca::Index>(tb.getMinX()), 0);
  BOOST_CHECK_EQUAL(static_cast<votca::Index>(tb.getMaxX()), 9);
  BOOST_CHECK_EQUAL(static_cast<votca::Index>(tb.getMinY()), 0);
  BOOST_CHECK_EQUAL(static_cast<votca::Index>(tb.getMaxY()), 18);
}

BOOST_AUTO_TEST_CASE(generate_grid_spacing_test) {
  Table tb;
  double min_v = 1.2;
  double max_v = 2.0;

  tb.GenerateGridSpacing(min_v, max_v, 0.2);

  BOOST_CHECK_EQUAL(tb.size(), 5);
  BOOST_CHECK_EQUAL(static_cast<votca::Index>(round(tb.getMinX() * 10)), 12);
  BOOST_CHECK_EQUAL(static_cast<votca::Index>(round(tb.getMaxX() * 10)), 20);
}

BOOST_AUTO_TEST_CASE(smoothing_test) {
  Table tb;
  double min_v = 1.2;
  double max_v = 2.0;

  tb.GenerateGridSpacing(min_v, max_v, 0.1);

  BOOST_CHECK_EQUAL(tb.size(), 9);
  tb.y() = tb.x().array().sinh();
  tb.Smooth(2);
  Eigen::VectorXd refy = Eigen::VectorXd::Zero(9);
  refy << 1.50946, 1.70621, 1.91563, 2.14274, 2.39083, 2.66271, 2.96119,
      3.28637, 3.62686;

  bool equal = tb.y().isApprox(refy, 1e-5);

  if (!equal) {
    std::cout << "result value" << std::endl;
    std::cout << tb.y().transpose() << std::endl;
    std::cout << "ref value" << std::endl;
    std::cout << refy.transpose() << std::endl;
  }
  BOOST_CHECK_EQUAL(equal, true);
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>update test_table results<commit_after>/*
 * Copyright 2009-2019 The VOTCA Development Team (http://www.votca.org)
 *
 * 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.
 *
 */
#define BOOST_TEST_MAIN

#define BOOST_TEST_MODULE table_test
#include <boost/lexical_cast.hpp>
#include <boost/test/unit_test.hpp>
#include <exception>
#include <iostream>
#include <votca/tools/table.h>

using namespace std;
using namespace votca::tools;

BOOST_AUTO_TEST_SUITE(table_test)

BOOST_AUTO_TEST_CASE(create_test) {
  Table tb;
  Table tb2(tb);
}

BOOST_AUTO_TEST_CASE(size_test) {
  Table tb;
  BOOST_CHECK_EQUAL(tb.size(), 0);
}

BOOST_AUTO_TEST_CASE(pushback_test) {
  Table tb;
  for (double x = 0; x < 10; ++x) {
    double y = 2 * x;
    tb.push_back(x, y);
  }
  BOOST_CHECK_EQUAL(tb.size(), 10);
}

BOOST_AUTO_TEST_CASE(resize_test) {
  Table tb;
  tb.resize(0);
  tb.resize(10);

  bool error_thrown = false;
  try {
    tb.resize(-5);
  } catch (...) {
    error_thrown = true;
  }
  BOOST_CHECK(error_thrown);
}

BOOST_AUTO_TEST_CASE(xy_test) {
  Table tb;
  for (double x = 0; x < 10; ++x) {
    double y = 2 * x;
    tb.push_back(x, y);
  }

  auto x_v = tb.x();
  auto y_v = tb.y();
  for (votca::Index i = 0; i < 10; ++i) {
    votca::Index x = i;
    votca::Index y = 2 * x;
    BOOST_CHECK_EQUAL(static_cast<votca::Index>(x_v(i)),
                      static_cast<votca::Index>(tb.x(i)));
    BOOST_CHECK_EQUAL(static_cast<votca::Index>(y_v(i)),
                      static_cast<votca::Index>(tb.y(i)));
    BOOST_CHECK_EQUAL(x, static_cast<votca::Index>(tb.x(i)));
    BOOST_CHECK_EQUAL(y, static_cast<votca::Index>(tb.y(i)));
    BOOST_CHECK_EQUAL(x, static_cast<votca::Index>(x_v(i)));
    BOOST_CHECK_EQUAL(y, static_cast<votca::Index>(y_v(i)));
  }
}

BOOST_AUTO_TEST_CASE(getMinMax_test) {
  Table tb;
  for (double x = 0; x < 10; ++x) {
    double y = 2 * x;
    tb.push_back(x, y);
  }

  BOOST_CHECK_EQUAL(static_cast<votca::Index>(tb.getMinX()), 0);
  BOOST_CHECK_EQUAL(static_cast<votca::Index>(tb.getMaxX()), 9);
  BOOST_CHECK_EQUAL(static_cast<votca::Index>(tb.getMinY()), 0);
  BOOST_CHECK_EQUAL(static_cast<votca::Index>(tb.getMaxY()), 18);
}

BOOST_AUTO_TEST_CASE(generate_grid_spacing_test) {
  Table tb;
  double min_v = 1.2;
  double max_v = 2.0;

  tb.GenerateGridSpacing(min_v, max_v, 0.2);

  BOOST_CHECK_EQUAL(tb.size(), 5);
  BOOST_CHECK_EQUAL(static_cast<votca::Index>(round(tb.getMinX() * 10)), 12);
  BOOST_CHECK_EQUAL(static_cast<votca::Index>(round(tb.getMaxX() * 10)), 20);
}

BOOST_AUTO_TEST_CASE(smoothing_test) {
  Table tb;
  double min_v = 1.2;
  double max_v = 2.0;

  tb.GenerateGridSpacing(min_v, max_v, 0.1);

  BOOST_CHECK_EQUAL(tb.size(), 9);
  tb.y() = tb.x().array().sinh();
  tb.Smooth(2);
  Eigen::VectorXd refy = Eigen::VectorXd::Zero(9);
  refy << 1.50946, 1.70621, 1.91527, 2.14055, 2.38962, 2.65963, 2.95959,
       3.28268, 3.62686;

  bool equal = tb.y().isApprox(refy, 1e-5);

  if (!equal) {
    std::cout << "result value" << std::endl;
    std::cout << tb.y().transpose() << std::endl;
    std::cout << "ref value" << std::endl;
    std::cout << refy.transpose() << std::endl;
  }
  BOOST_CHECK_EQUAL(equal, true);
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before><commit_msg>fix tracker_manager argument forwarding<commit_after><|endoftext|>