<commit_before>/*************************************************************************
 *
 *  $RCSfile: query.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: oj $ $Date: 2000-10-25 07:30:24 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DBA_COREAPI_QUERY_HXX_
#include "query.hxx"
#endif
#ifndef DBACCESS_SHARED_DBASTRINGS_HRC
#include "dbastrings.hrc"
#endif
#include "registryhelper.hxx"

#ifndef _CPPUHELPER_QUERYINTERFACE_HXX_
#include <cppuhelper/queryinterface.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_AGGREGATION_HXX_
#include <comphelper/propagg.hxx>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif

#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif

using namespace dbaccess;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::registry;
using namespace ::comphelper;
using namespace ::osl;
using namespace ::cppu;

#define AGG_PROPERTY(handle, propname_out)  \
    static_cast< ::comphelper::OPropertyArrayAggregationHelper* >(const_cast< OQuery_LINUX* >(this)->getArrayHelper())->fillAggregatePropertyInfoByHandle(&propname_out, NULL, handle)

//........................................................................
namespace dbaccess
{
//........................................................................

//==========================================================================
//= OQuery_LINUX
//==========================================================================
DBG_NAME(OQuery_LINUX)
//--------------------------------------------------------------------------
OQuery_LINUX::OQuery_LINUX(const Reference< XPropertySet >& _rxCommandDefinition, const Reference< XConnection >& _rxConn)
    :OConfigurationFlushable(m_aMutex)
    ,m_bColumnsOutOfDate(sal_True)
    ,m_bCaseSensitiv(sal_True)
    ,m_xCommandDefinition(_rxCommandDefinition)
    ,m_eDoingCurrently(NONE)
    ,m_xConnection(_rxConn)
{
    DBG_CTOR(OQuery_LINUX, NULL);

    DBG_ASSERT(m_xCommandDefinition.is(), "OQuery_LINUX::OQuery_LINUX : invalid CommandDefinition object !");
    if (m_xCommandDefinition.is())
    {
        m_xCommandDefinition->addPropertyChangeListener(::rtl::OUString(), this);

        // TODO : be a listener on the configuration node which is responsible for my properties not belonging
        // to the CommandDefinition
    }
    DBG_ASSERT(m_xConnection.is(), "OQuery_LINUX::OQuery_LINUX : invalid connection !");
}

//--------------------------------------------------------------------------
OQuery_LINUX::~OQuery_LINUX()
{
    DBG_DTOR(OQuery_LINUX, NULL);
}

// XTypeProvider
//--------------------------------------------------------------------------
Sequence< Type > SAL_CALL OQuery_LINUX::getTypes() throw (RuntimeException)
{
    return ::comphelper::concatSequences(OQueryDescriptor::getTypes(), OQuery_Base::getTypes(), OConfigurationFlushable::getTypes());
}

// XInterface
//--------------------------------------------------------------------------
Any SAL_CALL OQuery_LINUX::queryInterface( const Type& _rType ) throw(RuntimeException)
{
    Any aReturn = OQuery_Base::queryInterface(_rType);
    if (!aReturn.hasValue())
        aReturn = OQueryDescriptor::queryInterface(_rType);
    if (!aReturn.hasValue())
        aReturn = OConfigurationFlushable::queryInterface(_rType);
    return aReturn;
}

// XColumnsSupplier
//--------------------------------------------------------------------------
Reference< XNameAccess > SAL_CALL OQuery_LINUX::getColumns(  ) throw(RuntimeException)
{
    MutexGuard aGuard(m_aMutex);
    if (m_bColumnsOutOfDate)
    {
        m_aColumns.clearColumns();

        // TODO

        m_bColumnsOutOfDate = sal_False;
    }
    return &m_aColumns;
}

// XServiceInfo
//--------------------------------------------------------------------------
IMPLEMENT_SERVICE_INFO3(OQuery_LINUX, "com.sun.star.sdb.dbaccess.OQuery", SERVICE_SDB_DATASETTINGS, SERVICE_SDB_QUERY, SERVICE_SDB_QUERYDEFINITION)

// ::com::sun::star::beans::XPropertyChangeListener
//--------------------------------------------------------------------------
void SAL_CALL OQuery_LINUX::propertyChange( const PropertyChangeEvent& _rSource ) throw(RuntimeException)
{
    sal_Int32 nOwnHandle = -1;
    {
        MutexGuard aGuard(m_aMutex);

        DBG_ASSERT(_rSource.Source.get() == Reference< XInterface >(m_xCommandDefinition, UNO_QUERY).get(),
            "OQuery_LINUX::propertyChange : where did this call come from ?");

        if (m_eDoingCurrently == SETTING_PROPERTIES)
            // we're setting the property ourself, so we will do the neccessary notifications later
            return;

        // forward this to our own member holding a copy of the property value
        if (getArrayHelper()->hasPropertyByName(_rSource.PropertyName))
        {
            Property aOwnProp = getArrayHelper()->getPropertyByName(_rSource.PropertyName);
            nOwnHandle = aOwnProp.Handle;
            OQueryDescriptor::setFastPropertyValue_NoBroadcast(nOwnHandle, _rSource.NewValue);
                // don't use our own setFastPropertyValue_NoBroadcast, this would forward it to the CommandSettings,
                // again
                // and don't use the "real" setPropertyValue, this is to expensive and not sure to succeed
        }
        else
        {
            DBG_ERROR("OQuery_LINUX::propertyChange : my CommandDefinition has more properties than I do !");
        }
    }

    fire(&nOwnHandle, &_rSource.NewValue, &_rSource.OldValue, 1, sal_False);
}

//--------------------------------------------------------------------------
void SAL_CALL OQuery_LINUX::disposing( const EventObject& _rSource )
{
    MutexGuard aGuard(m_aMutex);

    DBG_ASSERT(_rSource.Source.get() == Reference< XInterface >(m_xCommandDefinition, UNO_QUERY).get(),
        "OQuery_LINUX::disposing : where did this call come from ?");

    m_xCommandDefinition->removePropertyChangeListener(::rtl::OUString(), this);
    m_xCommandDefinition = NULL;
}

// XDataDescriptorFactory
//--------------------------------------------------------------------------
Reference< XPropertySet > SAL_CALL OQuery_LINUX::createDataDescriptor(  ) throw(RuntimeException)
{
    return new OQueryDescriptor(*this);
}

// OQueryDescriptor
//--------------------------------------------------------------------------
void OQuery_LINUX::initializeFrom(const OConfigurationNode& _rConfigLocation)
{
    OQueryDescriptor::initializeFrom(_rConfigLocation);

    m_aConfigurationNode = _rConfigLocation.cloneAsRoot();
}

// OConfigurationFlushable
//--------------------------------------------------------------------------
void OQuery_LINUX::flush_NoBroadcast_NoCommit()
{
    if (!m_aConfigurationNode.isValid())
        throw DisposedException();
    OQueryDescriptor::storeTo(m_aConfigurationNode);
}

// pseudo-XComponent
//--------------------------------------------------------------------------
void SAL_CALL OQuery_LINUX::dispose()
{
    MutexGuard aGuard(m_aMutex);
    if (m_xCommandDefinition.is())
    {
        m_xCommandDefinition->removePropertyChangeListener(::rtl::OUString(), this);
        m_xCommandDefinition = NULL;
    }
    m_aConfigurationNode.clear();
    OQueryDescriptor::dispose();
}

//--------------------------------------------------------------------------
void OQuery_LINUX::setFastPropertyValue_NoBroadcast( sal_Int32 _nHandle, const Any& _rValue ) throw (Exception)
{
    ODataSettings::setFastPropertyValue_NoBroadcast(_nHandle, _rValue);
    ::rtl::OUString sAggPropName;
    if (AGG_PROPERTY(_nHandle, sAggPropName))
    {   // the base class holds the property values itself, but we have to forward this to our CommandDefinition
        m_eDoingCurrently = SETTING_PROPERTIES;
        OAutoActionReset(this);
        m_xCommandDefinition->setPropertyValue(sAggPropName, _rValue);
    }
}

//--------------------------------------------------------------------------
Reference< XPropertySetInfo > SAL_CALL OQuery_LINUX::getPropertySetInfo(  ) throw(RuntimeException)
{
    return createPropertySetInfo( getInfoHelper() ) ;
}

//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& OQuery_LINUX::getInfoHelper()
{
    return *getArrayHelper();
}

//--------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OQuery::createArrayHelper( ) const
{
    Sequence< Property > aProps;
    // our own props
    describeProperties(aProps);
    return new ::cppu::OPropertyArrayHelper(aProps);
}

//........................................................................
}   // namespace dbaccess
//........................................................................

<commit_msg>fill query with live, like columns<commit_after>/*************************************************************************
 *
 *  $RCSfile: query.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: oj $ $Date: 2001-01-04 14:26:47 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DBA_COREAPI_QUERY_HXX_
#include "query.hxx"
#endif
#ifndef DBACCESS_SHARED_DBASTRINGS_HRC
#include "dbastrings.hrc"
#endif
#include "registryhelper.hxx"

#ifndef _CPPUHELPER_QUERYINTERFACE_HXX_
#include <cppuhelper/queryinterface.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_AGGREGATION_HXX_
#include <comphelper/propagg.hxx>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif

#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_HXX_
#include <comphelper/property.hxx>
#endif

using namespace dbaccess;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::registry;
using namespace ::comphelper;
using namespace ::osl;
using namespace ::cppu;

#define AGG_PROPERTY(handle, propname_out)  \
    static_cast< ::comphelper::OPropertyArrayAggregationHelper* >(const_cast< OQuery_LINUX* >(this)->getArrayHelper())->fillAggregatePropertyInfoByHandle(&propname_out, NULL, handle)

//........................................................................
namespace dbaccess
{
//........................................................................

//==========================================================================
//= OQuery_LINUX
//==========================================================================
DBG_NAME(OQuery_LINUX)
//--------------------------------------------------------------------------
OQuery_LINUX::OQuery_LINUX(const Reference< XPropertySet >& _rxCommandDefinition, const Reference< XConnection >& _rxConn)
    :OConfigurationFlushable(m_aMutex)
    ,OQueryDescriptor(_rxCommandDefinition)
    ,m_bColumnsOutOfDate(sal_True)
    ,m_bCaseSensitiv(sal_True)
    ,m_xCommandDefinition(_rxCommandDefinition)
    ,m_eDoingCurrently(NONE)
    ,m_xConnection(_rxConn)
{
    DBG_CTOR(OQuery_LINUX, NULL);

    DBG_ASSERT(m_xCommandDefinition.is(), "OQuery_LINUX::OQuery_LINUX : invalid CommandDefinition object !");
    if (m_xCommandDefinition.is())
    {
        m_xCommandDefinition->addPropertyChangeListener(::rtl::OUString(), this);

        // TODO : be a listener on the configuration node which is responsible for my properties not belonging
        // to the CommandDefinition
    }
    DBG_ASSERT(m_xConnection.is(), "OQuery_LINUX::OQuery_LINUX : invalid connection !");
}

//--------------------------------------------------------------------------
OQuery_LINUX::~OQuery_LINUX()
{
    DBG_DTOR(OQuery_LINUX, NULL);
}

// XTypeProvider
//--------------------------------------------------------------------------
Sequence< Type > SAL_CALL OQuery_LINUX::getTypes() throw (RuntimeException)
{
    return ::comphelper::concatSequences(OQueryDescriptor::getTypes(), OQuery_Base::getTypes(), OConfigurationFlushable::getTypes());
}

// XInterface
//--------------------------------------------------------------------------
Any SAL_CALL OQuery_LINUX::queryInterface( const Type& _rType ) throw(RuntimeException)
{
    Any aReturn = OQuery_Base::queryInterface(_rType);
    if (!aReturn.hasValue())
        aReturn = OQueryDescriptor::queryInterface(_rType);
    if (!aReturn.hasValue())
        aReturn = OConfigurationFlushable::queryInterface(_rType);
    return aReturn;
}

// XColumnsSupplier
//--------------------------------------------------------------------------
Reference< XNameAccess > SAL_CALL OQuery_LINUX::getColumns(  ) throw(RuntimeException)
{
    MutexGuard aGuard(m_aMutex);
    if (m_bColumnsOutOfDate)
    {
        m_aColumns.clearColumns();

        // fill the columns with columns from teh statement
        try
        {
            Reference< XStatement > xStmt = m_xConnection->createStatement();
            OSL_ENSURE(xStmt.is(),"No Statement created!");
            if(xStmt.is())
            {
                Reference< XColumnsSupplier > xRs(xStmt->executeQuery(m_sCommand),UNO_QUERY);
                OSL_ENSURE(xRs.is(),"No Resultset created!");
                if(xRs.is())
                {
                    Reference< XNameAccess > xColumns = xRs->getColumns();
                    if(xColumns.is())
                    {
                        Sequence< ::rtl::OUString> aNames = xColumns->getElementNames();
                        const ::rtl::OUString* pBegin = aNames.getConstArray();
                        const ::rtl::OUString* pEnd   = pBegin + aNames.getLength();
                        for(;pBegin != pEnd;++pBegin)
                        {
                            ODescriptorColumn* pColumn = new ODescriptorColumn(*pBegin);
                            Reference<XPropertySet> xSet = pColumn;
                            Reference<XPropertySet> xSource;
                            xColumns->getByName(*pBegin) >>= xSource;
                            ::comphelper::copyProperties(xSource,xSet);
                            m_aColumns.append(*pBegin,pColumn);
                        }
                    }
                    ::comphelper::disposeComponent(xRs);
                }
                ::comphelper::disposeComponent(xStmt);
            }

            m_bColumnsOutOfDate = sal_False;
            m_aColumns.setInitialized();
        }
        catch(SQLException&)
        {
        }
    }
    return &m_aColumns;
}

// XServiceInfo
//--------------------------------------------------------------------------
IMPLEMENT_SERVICE_INFO3(OQuery_LINUX, "com.sun.star.sdb.dbaccess.OQuery", SERVICE_SDB_DATASETTINGS, SERVICE_SDB_QUERY, SERVICE_SDB_QUERYDEFINITION)

// ::com::sun::star::beans::XPropertyChangeListener
//--------------------------------------------------------------------------
void SAL_CALL OQuery_LINUX::propertyChange( const PropertyChangeEvent& _rSource ) throw(RuntimeException)
{
    sal_Int32 nOwnHandle = -1;
    {
        MutexGuard aGuard(m_aMutex);

        DBG_ASSERT(_rSource.Source.get() == Reference< XInterface >(m_xCommandDefinition, UNO_QUERY).get(),
            "OQuery_LINUX::propertyChange : where did this call come from ?");

        if (m_eDoingCurrently == SETTING_PROPERTIES)
            // we're setting the property ourself, so we will do the neccessary notifications later
            return;

        // forward this to our own member holding a copy of the property value
        if (getArrayHelper()->hasPropertyByName(_rSource.PropertyName))
        {
            Property aOwnProp = getArrayHelper()->getPropertyByName(_rSource.PropertyName);
            nOwnHandle = aOwnProp.Handle;
            OQueryDescriptor::setFastPropertyValue_NoBroadcast(nOwnHandle, _rSource.NewValue);
                // don't use our own setFastPropertyValue_NoBroadcast, this would forward it to the CommandSettings,
                // again
                // and don't use the "real" setPropertyValue, this is to expensive and not sure to succeed
        }
        else
        {
            DBG_ERROR("OQuery_LINUX::propertyChange : my CommandDefinition has more properties than I do !");
        }
    }

    fire(&nOwnHandle, &_rSource.NewValue, &_rSource.OldValue, 1, sal_False);
}

//--------------------------------------------------------------------------
void SAL_CALL OQuery_LINUX::disposing( const EventObject& _rSource )
{
    MutexGuard aGuard(m_aMutex);

    DBG_ASSERT(_rSource.Source.get() == Reference< XInterface >(m_xCommandDefinition, UNO_QUERY).get(),
        "OQuery_LINUX::disposing : where did this call come from ?");

    m_xCommandDefinition->removePropertyChangeListener(::rtl::OUString(), this);
    m_xCommandDefinition = NULL;
}

// XDataDescriptorFactory
//--------------------------------------------------------------------------
Reference< XPropertySet > SAL_CALL OQuery_LINUX::createDataDescriptor(  ) throw(RuntimeException)
{
    return new OQueryDescriptor(*this);
}

// OQueryDescriptor
//--------------------------------------------------------------------------
void OQuery_LINUX::initializeFrom(const OConfigurationNode& _rConfigLocation)
{
    OQueryDescriptor::initializeFrom(_rConfigLocation);

    m_aConfigurationNode = _rConfigLocation.cloneAsRoot();
}

// OConfigurationFlushable
//--------------------------------------------------------------------------
void OQuery_LINUX::flush_NoBroadcast_NoCommit()
{
    if (!m_aConfigurationNode.isValid())
        throw DisposedException();
    OQueryDescriptor::storeTo(m_aConfigurationNode);
}

// pseudo-XComponent
//--------------------------------------------------------------------------
void SAL_CALL OQuery_LINUX::dispose()
{
    MutexGuard aGuard(m_aMutex);
    if (m_xCommandDefinition.is())
    {
        m_xCommandDefinition->removePropertyChangeListener(::rtl::OUString(), this);
        m_xCommandDefinition = NULL;
    }
    m_aConfigurationNode.clear();
    OQueryDescriptor::dispose();
}

//--------------------------------------------------------------------------
void OQuery_LINUX::setFastPropertyValue_NoBroadcast( sal_Int32 _nHandle, const Any& _rValue ) throw (Exception)
{
    OQueryDescriptor::setFastPropertyValue_NoBroadcast(_nHandle, _rValue);
    ::rtl::OUString sAggPropName;
    sal_Int16 nAttr = 0;
    if (getInfoHelper().fillPropertyMembersByHandle(&sAggPropName,&nAttr,_nHandle))
    {   // the base class holds the property values itself, but we have to forward this to our CommandDefinition
        m_eDoingCurrently = SETTING_PROPERTIES;
        OAutoActionReset(this);
        m_xCommandDefinition->setPropertyValue(sAggPropName, _rValue);
    }
}

//--------------------------------------------------------------------------
Reference< XPropertySetInfo > SAL_CALL OQuery_LINUX::getPropertySetInfo(  ) throw(RuntimeException)
{
    return createPropertySetInfo( getInfoHelper() ) ;
}

//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& OQuery_LINUX::getInfoHelper()
{
    return *getArrayHelper();
}

//--------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OQuery::createArrayHelper( ) const
{
    Sequence< Property > aProps;
    // our own props
    describeProperties(aProps);
    return new ::cppu::OPropertyArrayHelper(aProps);
}

//........................................................................
}   // namespace dbaccess
//........................................................................

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: JAccess.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 12:25:02 $
 *
 *  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
 *
 ************************************************************************/
#ifndef DBACCESS_JACCESS_HXX
#define DBACCESS_JACCESS_HXX

#ifndef _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_
#include <toolkit/awt/vclxaccessiblecomponent.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

namespace dbaui
{
    class OJoinTableView;
    typedef ::cppu::ImplHelper1< ::com::sun::star::accessibility::XAccessible
                                            > OJoinDesignViewAccess_BASE;
    /** the class OJoinDesignViewAccess represents the accessible object for join views
        like the QueryDesign and the RelationDesign
    */
    class OJoinDesignViewAccess     :   public VCLXAccessibleComponent, public OJoinDesignViewAccess_BASE
    {
        OJoinTableView* m_pTableView; // the window which I should give accessibility to

    protected:
        /** isEditable returns the current editable state
            @return true if the controller is not readonly otherwise false
        */
        virtual sal_Bool isEditable() const;
    public:
        /** OJoinDesignViewAccess needs a valid view
        */
        OJoinDesignViewAccess(  OJoinTableView* _pTableView);

        // XInterface
        DECLARE_XINTERFACE( )
        DECLARE_XTYPEPROVIDER( )

        // XServiceInfo - static methods
        static ::rtl::OUString getImplementationName_Static(void) throw( com::sun::star::uno::RuntimeException );

        virtual ::rtl::OUString SAL_CALL getImplementationName() throw(com::sun::star::uno::RuntimeException);

        // XAccessible
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext(  ) throw (::com::sun::star::uno::RuntimeException);

        // XAccessibleContext
        virtual sal_Int32 SAL_CALL getAccessibleChildCount(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException,::com::sun::star::uno::RuntimeException);
        virtual sal_Int16 SAL_CALL getAccessibleRole(  ) throw (::com::sun::star::uno::RuntimeException);

        OJoinTableView* getTableView() const { return m_pTableView; }

        void notifyAccessibleEvent(
                    const sal_Int16 _nEventId,
                    const ::com::sun::star::uno::Any& _rOldValue,
                    const ::com::sun::star::uno::Any& _rNewValue
                )
        {
            NotifyAccessibleEvent(_nEventId,_rOldValue,_rNewValue);
        }

        void clearTableView();
    };
}
#endif // DBACCESS_JACCESS_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.7.162); FILE MERGED 2008/03/31 13:27:43 rt 1.7.162.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: JAccess.hxx,v $
 * $Revision: 1.8 $
 *
 * 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.
 *
 ************************************************************************/
#ifndef DBACCESS_JACCESS_HXX
#define DBACCESS_JACCESS_HXX

#ifndef _TOOLKIT_AWT_VCLXACCESSIBLECOMPONENT_HXX_
#include <toolkit/awt/vclxaccessiblecomponent.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

namespace dbaui
{
    class OJoinTableView;
    typedef ::cppu::ImplHelper1< ::com::sun::star::accessibility::XAccessible
                                            > OJoinDesignViewAccess_BASE;
    /** the class OJoinDesignViewAccess represents the accessible object for join views
        like the QueryDesign and the RelationDesign
    */
    class OJoinDesignViewAccess     :   public VCLXAccessibleComponent, public OJoinDesignViewAccess_BASE
    {
        OJoinTableView* m_pTableView; // the window which I should give accessibility to

    protected:
        /** isEditable returns the current editable state
            @return true if the controller is not readonly otherwise false
        */
        virtual sal_Bool isEditable() const;
    public:
        /** OJoinDesignViewAccess needs a valid view
        */
        OJoinDesignViewAccess(  OJoinTableView* _pTableView);

        // XInterface
        DECLARE_XINTERFACE( )
        DECLARE_XTYPEPROVIDER( )

        // XServiceInfo - static methods
        static ::rtl::OUString getImplementationName_Static(void) throw( com::sun::star::uno::RuntimeException );

        virtual ::rtl::OUString SAL_CALL getImplementationName() throw(com::sun::star::uno::RuntimeException);

        // XAccessible
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext(  ) throw (::com::sun::star::uno::RuntimeException);

        // XAccessibleContext
        virtual sal_Int32 SAL_CALL getAccessibleChildCount(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > SAL_CALL getAccessibleChild( sal_Int32 i ) throw (::com::sun::star::lang::IndexOutOfBoundsException,::com::sun::star::uno::RuntimeException);
        virtual sal_Int16 SAL_CALL getAccessibleRole(  ) throw (::com::sun::star::uno::RuntimeException);

        OJoinTableView* getTableView() const { return m_pTableView; }

        void notifyAccessibleEvent(
                    const sal_Int16 _nEventId,
                    const ::com::sun::star::uno::Any& _rOldValue,
                    const ::com::sun::star::uno::Any& _rNewValue
                )
        {
            NotifyAccessibleEvent(_nEventId,_rOldValue,_rNewValue);
        }

        void clearTableView();
    };
}
#endif // DBACCESS_JACCESS_HXX
<|endoftext|>


<commit_before>/*===========================================================================*\
 *                                                                           *
 *                               OpenMesh                                    *
 *      Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen      *
 *                           www.openmesh.org                                *
 *                                                                           *
 *---------------------------------------------------------------------------*
 *  This file is part of OpenMesh.                                           *
 *                                                                           *
 *  OpenMesh is free software: you can redistribute it and/or modify         *
 *  it under the terms of the GNU Lesser General Public License as           *
 *  published by the Free Software Foundation, either version 3 of           *
 *  the License, or (at your option) any later version with the              *
 *  following exceptions:                                                    *
 *                                                                           *
 *  If other files instantiate templates or use macros                       *
 *  or inline functions from this file, or you compile this file and         *
 *  link it with other files to produce an executable, this file does        *
 *  not by itself cause the resulting executable to be covered by the        *
 *  GNU Lesser General Public License. This exception does not however       *
 *  invalidate any other reasons why the executable file might be            *
 *  covered by the GNU Lesser General Public License.                        *
 *                                                                           *
 *  OpenMesh 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 LesserGeneral Public          *
 *  License along with OpenMesh.  If not,                                    *
 *  see <http://www.gnu.org/licenses/>.                                      *
 *                                                                           *
\*===========================================================================*/

/*===========================================================================*\
 *                                                                           *
 *   $Revision$                                                         *
 *   $Date$                   *
 *                                                                           *
\*===========================================================================*/

#ifndef DOXY_IGNORE_THIS
// ----------------------------------------------------------------------------
#include <OpenMesh/Core/System/config.h>
#if defined(OM_CC_MIPS)
#  include <math.h>
#  include <stdio.h>
#else
#  include <cmath>
#  include <cstdio>
#endif
#include "Timer.hh"
// ----------------------------------------------------------------------------

// ------------------------------------------------------------- namespace ----

namespace OpenMesh {
namespace Utils {

// ----------------------------------------------------------------------------

using namespace std;

// -------------------------------------------------------------- TimerImpl ----

};

// compiler and os dependent implementation

// ------------------------------------------------------------- posix time ----
#if defined(__GNUC__) && defined(__POSIX__)

#ifndef DOXY_IGNORE_THIS
#  include <time.h>
#endif

template <clockid_t N>
class TimerImplPosix : public TimerImpl
{
public:
    TimerImplPosix() : id_(N), seconds_(0.0)
    { }

    ~TimerImplPosix()
    { }

    virtual void reset(void) { seconds_ = 0.0; }

    virtual void start(void) { seconds_ = 0.0; clock_gettime( id_, &start_ ); }
    virtual void stop(void)
    {
        timespec stop;
        clock_gettime( id_, &stop );
        seconds_ += ( stop.tv_sec - start_.tv_sec );
        seconds_ += ( (double(stop.tv_nsec-start_.tv_nsec)*1e-9) );
    }

    virtual void cont(void)  { clock_gettime( id_, &start_ ); }

    virtual double seconds() const { return seconds_; }

protected:
   clockid_t id_;
   double    seconds_;
   timespec  start_;
};

// ----------------------------------------------------------- gettimeofday ----
#elif (defined(__GNUC__) || (defined(__INTEL_COMPILER) && !defined(WIN32))) && !defined(__MINGW32__)

#  include <sys/time.h>
#  include <sys/resource.h>
#  include <unistd.h>

class TimerImplGToD: public TimerImpl
{
public:
    TimerImplGToD() : seconds_(0.0)
    { }

    ~TimerImplGToD()
    { }

    virtual void reset(void) { seconds_ = 0.0; }
    virtual void start(void) { seconds_ = 0.0; gettimeofday( &start_, &tz_ ); }

    virtual void stop(void)
    {
      gettimeofday( &stop_, &tz_ );

      seconds_ +=  (double)(stop_.tv_sec - start_.tv_sec);
      seconds_ +=  (double)(stop_.tv_usec- start_.tv_usec)*1e-6;
    }

    virtual void cont(void)  { gettimeofday( &start_, &tz_); }

    virtual double seconds() const { return seconds_; }

private:

  struct timeval start_, stop_;
  struct timezone tz_;

  double seconds_;
};

#else // ---------------------------------------- standard implementation ----

#include <time.h>

static const unsigned long clockticks = CLOCKS_PER_SEC;

class TimerImplStd : public TimerImpl
{
public:
   TimerImplStd() : freq_(clockticks),count_(0),start_(0) { reset(); }
   ~TimerImplStd() { ; }

   virtual void   reset(void) { count_ = 0; }
   virtual void   start(void) { count_ = 0; start_ = clock(); }
   virtual void   stop(void);
   virtual void   cont(void)  { start_ = clock(); }
   virtual double seconds(void) const { return (double)count_/(double)freq_; }

protected:
   unsigned long freq_;
   unsigned long count_;
   unsigned long start_;
};

void TimerImplStd::stop(void)
{
   unsigned long stop_ = clock();
   count_ += stop_-start_;
}

#endif

// ----------------------------------------------------------------- Timer ----

Timer::Timer(void)
{
#if defined(__GNUC__) && defined(__POSIX__)
// CLOCK_REALTIME
// CLOCK_MONOTONIC     - ?
// CLOCK_REALTIME_HR   - RTlinux
// CLOCK_MONOTONIC_HR  - ?
#  if defined(CLOCK_REALTIME_HR)
  impl_      = new TimerImplPosix<CLOCK_REALTIME_HR>;
#  else
  impl_      = new TimerImplPosix<CLOCK_REALTIME>;
#  endif
#elif (defined(__GNUC__) || (defined(__INTEL_COMPILER) && !defined(WIN32)) ) && !defined(__MINGW32__)
  impl_      = new TimerImplGToD;
#else
  impl_       = new TimerImplStd;
#endif
  state_      = Stopped;
}

Timer::~Timer(void)
{
   delete impl_;
   state_ = Stopped;
}

void Timer::reset(void)
{
   state_ = Stopped;
   impl_->reset();
}

void Timer::start(void)
{
   state_ = Running;
   impl_->start();
}

void Timer::stop(void)
{
   impl_->stop();
   state_ = Stopped;
}

void Timer::cont(void)
{
   impl_->cont();
   state_ = Running;
}

double Timer::seconds(void) const
{
   return state_==Stopped ? impl_->seconds() : 0.0;
}

std::string Timer::as_string(Timer::Format format)
{
   if (state_ == Running)
       return "Running";
   return as_string(impl_->seconds(),format);
}

std::string Timer::as_string(double seconds, Timer::Format format)
{
   char string[32];

   double fraction;
   double integer;
   unsigned long t;
//    double rest;
   short  hour,min,sec;
   bool   negative = false;

   if ( seconds < 0 )
   {
      negative = true;
      seconds *= -1;
   }

   fraction = modf(seconds,&integer);

   t = (unsigned long)integer;

   hour = short( t / 3600L );
   t   %= 3600L;
   min  = short( t / 60L );
   t   %= 60L;
   sec  = short( t );
//    rest = (double)t + fraction;

   char *ptr = string;
   if (negative)
      *ptr++ = '-';

   switch(format)
   {
   case Timer::Automatic:
      if (hour)
         ptr += sprintf(ptr,"%02dh:",hour);

      if (min)
         ptr += sprintf(ptr,"%02dm:",min);
      else if (ptr>string && hour)
         ptr += sprintf(ptr,"00m:");

      if (sec)
         ptr += sprintf(ptr,"%02d",sec);
      else if (ptr>string && min)
         ptr += sprintf(ptr,"00");

      if (!hour && !min) // higher resolution necessary
      {
         if (ptr > string && sec)
         {
            sprintf(ptr,".%.3fs",fraction);
            ptr++;
            while(*(ptr+2))
            {
               *ptr = *(ptr+2);
               ptr++;
            }
            *ptr = '\0';
         }
         else if ( fraction * 1e2 > 0.1)
            sprintf(ptr,"%.3fcs",fraction*1.e2);
         else if ( fraction * 1e3 > 0.1)
            sprintf(ptr,"%.3fms",fraction*1.e3);
         else if ( fraction * 1e6 > 0.1)
            sprintf(ptr,"%.1f\xb5s",fraction*1.e6);
         else if ( fraction * 1e9 > 0.1)
            sprintf(ptr,"%.1fns",fraction*1.e9);
         else
            sprintf(ptr,"%.1fps",fraction*1.e12);
      } else // append a 's' for seconds!
      {
         ptr[0] = 's';
         ptr[1] = '\0';
      }
      break;
   case Timer::Long:
      ptr += sprintf(ptr,"%02dh:%02dm:%02d",hour,min,sec);
      sprintf(ptr,".%.12fs",fraction);
      ptr++;
      while(*(ptr+2))
      {
         *ptr = *(ptr+2);
         ptr++;
      }
      *ptr = '\0';
      break;
   case Timer::Hours:
      sprintf(ptr,"%02dh:%02dm:%02ds",hour,min,sec); break;
   case Timer::Minutes:
      ptr += sprintf(ptr,"%02dm:%02d", min, sec);
      sprintf(ptr,".%.2fs",fraction);
      ptr++;
      while(*(ptr+2))
      {
         *ptr = *(ptr+2);
         ptr++;
      }
      *ptr = '\0';
      break;
   case Timer::Seconds: sprintf(ptr,"%.3fs",seconds); break;
   case Timer::HSeconds: sprintf(ptr,"%.3fcs",seconds*1e2); break;
   case Timer::MSeconds:  sprintf(ptr,"%.3fms",seconds*1e3); break;
   case Timer::MicroSeconds: sprintf(ptr,"%.1f\xb5s",seconds*1e6); break;
   case Timer::NanoSeconds: sprintf(ptr,"%.1fns",seconds*1e9); break;
   }
   return string;
}

// ============================================================================
} // END_NS_UTILS
} // END_NS_OPENMESH
// ----------------------------------------------------------------------------
#endif // DOXY_IGNORE_THIS
// ============================================================================
// end of file Timer.cc
// ============================================================================

<commit_msg>Typo<commit_after>/*===========================================================================*\
 *                                                                           *
 *                               OpenMesh                                    *
 *      Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen      *
 *                           www.openmesh.org                                *
 *                                                                           *
 *---------------------------------------------------------------------------*
 *  This file is part of OpenMesh.                                           *
 *                                                                           *
 *  OpenMesh is free software: you can redistribute it and/or modify         *
 *  it under the terms of the GNU Lesser General Public License as           *
 *  published by the Free Software Foundation, either version 3 of           *
 *  the License, or (at your option) any later version with the              *
 *  following exceptions:                                                    *
 *                                                                           *
 *  If other files instantiate templates or use macros                       *
 *  or inline functions from this file, or you compile this file and         *
 *  link it with other files to produce an executable, this file does        *
 *  not by itself cause the resulting executable to be covered by the        *
 *  GNU Lesser General Public License. This exception does not however       *
 *  invalidate any other reasons why the executable file might be            *
 *  covered by the GNU Lesser General Public License.                        *
 *                                                                           *
 *  OpenMesh 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 LesserGeneral Public          *
 *  License along with OpenMesh.  If not,                                    *
 *  see <http://www.gnu.org/licenses/>.                                      *
 *                                                                           *
\*===========================================================================*/

/*===========================================================================*\
 *                                                                           *
 *   $Revision$                                                         *
 *   $Date$                   *
 *                                                                           *
\*===========================================================================*/

#ifndef DOXY_IGNORE_THIS
// ----------------------------------------------------------------------------
#include <OpenMesh/Core/System/config.h>
#if defined(OM_CC_MIPS)
#  include <math.h>
#  include <stdio.h>
#else
#  include <cmath>
#  include <cstdio>
#endif
#include "Timer.hh"
// ----------------------------------------------------------------------------

// ------------------------------------------------------------- namespace ----

namespace OpenMesh {
namespace Utils {

// ----------------------------------------------------------------------------

using namespace std;

// -------------------------------------------------------------- TimerImpl ----

// compiler and os dependent implementation

// ------------------------------------------------------------- posix time ----
#if defined(__GNUC__) && defined(__POSIX__)

#ifndef DOXY_IGNORE_THIS
#  include <time.h>
#endif

template <clockid_t N>
class TimerImplPosix : public TimerImpl
{
public:
    TimerImplPosix() : id_(N), seconds_(0.0)
    { }

    ~TimerImplPosix()
    { }

    virtual void reset(void) { seconds_ = 0.0; }

    virtual void start(void) { seconds_ = 0.0; clock_gettime( id_, &start_ ); }
    virtual void stop(void)
    {
        timespec stop;
        clock_gettime( id_, &stop );
        seconds_ += ( stop.tv_sec - start_.tv_sec );
        seconds_ += ( (double(stop.tv_nsec-start_.tv_nsec)*1e-9) );
    }

    virtual void cont(void)  { clock_gettime( id_, &start_ ); }

    virtual double seconds() const { return seconds_; }

protected:
   clockid_t id_;
   double    seconds_;
   timespec  start_;
};

// ----------------------------------------------------------- gettimeofday ----
#elif (defined(__GNUC__) || (defined(__INTEL_COMPILER) && !defined(WIN32))) && !defined(__MINGW32__)

#  include <sys/time.h>
#  include <sys/resource.h>
#  include <unistd.h>

class TimerImplGToD: public TimerImpl
{
public:
    TimerImplGToD() : seconds_(0.0)
    { }

    ~TimerImplGToD()
    { }

    virtual void reset(void) { seconds_ = 0.0; }
    virtual void start(void) { seconds_ = 0.0; gettimeofday( &start_, &tz_ ); }

    virtual void stop(void)
    {
      gettimeofday( &stop_, &tz_ );

      seconds_ +=  (double)(stop_.tv_sec - start_.tv_sec);
      seconds_ +=  (double)(stop_.tv_usec- start_.tv_usec)*1e-6;
    }

    virtual void cont(void)  { gettimeofday( &start_, &tz_); }

    virtual double seconds() const { return seconds_; }

private:

  struct timeval start_, stop_;
  struct timezone tz_;

  double seconds_;
};

#else // ---------------------------------------- standard implementation ----

#include <time.h>

static const unsigned long clockticks = CLOCKS_PER_SEC;

class TimerImplStd : public TimerImpl
{
public:
   TimerImplStd() : freq_(clockticks),count_(0),start_(0) { reset(); }
   ~TimerImplStd() { ; }

   virtual void   reset(void) { count_ = 0; }
   virtual void   start(void) { count_ = 0; start_ = clock(); }
   virtual void   stop(void);
   virtual void   cont(void)  { start_ = clock(); }
   virtual double seconds(void) const { return (double)count_/(double)freq_; }

protected:
   unsigned long freq_;
   unsigned long count_;
   unsigned long start_;
};

void TimerImplStd::stop(void)
{
   unsigned long stop_ = clock();
   count_ += stop_-start_;
}

#endif

// ----------------------------------------------------------------- Timer ----

Timer::Timer(void)
{
#if defined(__GNUC__) && defined(__POSIX__)
// CLOCK_REALTIME
// CLOCK_MONOTONIC     - ?
// CLOCK_REALTIME_HR   - RTlinux
// CLOCK_MONOTONIC_HR  - ?
#  if defined(CLOCK_REALTIME_HR)
  impl_      = new TimerImplPosix<CLOCK_REALTIME_HR>;
#  else
  impl_      = new TimerImplPosix<CLOCK_REALTIME>;
#  endif
#elif (defined(__GNUC__) || (defined(__INTEL_COMPILER) && !defined(WIN32)) ) && !defined(__MINGW32__)
  impl_      = new TimerImplGToD;
#else
  impl_       = new TimerImplStd;
#endif
  state_      = Stopped;
}

Timer::~Timer(void)
{
   delete impl_;
   state_ = Stopped;
}

void Timer::reset(void)
{
   state_ = Stopped;
   impl_->reset();
}

void Timer::start(void)
{
   state_ = Running;
   impl_->start();
}

void Timer::stop(void)
{
   impl_->stop();
   state_ = Stopped;
}

void Timer::cont(void)
{
   impl_->cont();
   state_ = Running;
}

double Timer::seconds(void) const
{
   return state_==Stopped ? impl_->seconds() : 0.0;
}

std::string Timer::as_string(Timer::Format format)
{
   if (state_ == Running)
       return "Running";
   return as_string(impl_->seconds(),format);
}

std::string Timer::as_string(double seconds, Timer::Format format)
{
   char string[32];

   double fraction;
   double integer;
   unsigned long t;
//    double rest;
   short  hour,min,sec;
   bool   negative = false;

   if ( seconds < 0 )
   {
      negative = true;
      seconds *= -1;
   }

   fraction = modf(seconds,&integer);

   t = (unsigned long)integer;

   hour = short( t / 3600L );
   t   %= 3600L;
   min  = short( t / 60L );
   t   %= 60L;
   sec  = short( t );
//    rest = (double)t + fraction;

   char *ptr = string;
   if (negative)
      *ptr++ = '-';

   switch(format)
   {
   case Timer::Automatic:
      if (hour)
         ptr += sprintf(ptr,"%02dh:",hour);

      if (min)
         ptr += sprintf(ptr,"%02dm:",min);
      else if (ptr>string && hour)
         ptr += sprintf(ptr,"00m:");

      if (sec)
         ptr += sprintf(ptr,"%02d",sec);
      else if (ptr>string && min)
         ptr += sprintf(ptr,"00");

      if (!hour && !min) // higher resolution necessary
      {
         if (ptr > string && sec)
         {
            sprintf(ptr,".%.3fs",fraction);
            ptr++;
            while(*(ptr+2))
            {
               *ptr = *(ptr+2);
               ptr++;
            }
            *ptr = '\0';
         }
         else if ( fraction * 1e2 > 0.1)
            sprintf(ptr,"%.3fcs",fraction*1.e2);
         else if ( fraction * 1e3 > 0.1)
            sprintf(ptr,"%.3fms",fraction*1.e3);
         else if ( fraction * 1e6 > 0.1)
            sprintf(ptr,"%.1f\xb5s",fraction*1.e6);
         else if ( fraction * 1e9 > 0.1)
            sprintf(ptr,"%.1fns",fraction*1.e9);
         else
            sprintf(ptr,"%.1fps",fraction*1.e12);
      } else // append a 's' for seconds!
      {
         ptr[0] = 's';
         ptr[1] = '\0';
      }
      break;
   case Timer::Long:
      ptr += sprintf(ptr,"%02dh:%02dm:%02d",hour,min,sec);
      sprintf(ptr,".%.12fs",fraction);
      ptr++;
      while(*(ptr+2))
      {
         *ptr = *(ptr+2);
         ptr++;
      }
      *ptr = '\0';
      break;
   case Timer::Hours:
      sprintf(ptr,"%02dh:%02dm:%02ds",hour,min,sec); break;
   case Timer::Minutes:
      ptr += sprintf(ptr,"%02dm:%02d", min, sec);
      sprintf(ptr,".%.2fs",fraction);
      ptr++;
      while(*(ptr+2))
      {
         *ptr = *(ptr+2);
         ptr++;
      }
      *ptr = '\0';
      break;
   case Timer::Seconds: sprintf(ptr,"%.3fs",seconds); break;
   case Timer::HSeconds: sprintf(ptr,"%.3fcs",seconds*1e2); break;
   case Timer::MSeconds:  sprintf(ptr,"%.3fms",seconds*1e3); break;
   case Timer::MicroSeconds: sprintf(ptr,"%.1f\xb5s",seconds*1e6); break;
   case Timer::NanoSeconds: sprintf(ptr,"%.1fns",seconds*1e9); break;
   }
   return string;
}

// ============================================================================
} // END_NS_UTILS
} // END_NS_OPENMESH
// ----------------------------------------------------------------------------
#endif // DOXY_IGNORE_THIS
// ============================================================================
// end of file Timer.cc
// ============================================================================

<|endoftext|>


<commit_before>#include "SDBPShardConnection.h"
#include "SDBPClient.h"
#include "Application/Common/ClientResponse.h"
#include "Application/SDBP/SDBPRequestMessage.h"
#include "Application/SDBP/SDBPResponseMessage.h"

#define CONN_BUFSIZE    4096

#define CLIENT_MUTEX_GUARD_DECLARE()    MutexGuard mutexGuard(client->mutex)
#define CLIENT_MUTEX_LOCK()             mutexGuard.Lock()
#define CLIENT_MUTEX_UNLOCK()           mutexGuard.Unlock()

using namespace SDBPClient;

static bool LessThan(uint64_t a, uint64_t b)
{
    return a < b;
}

ShardConnection::ShardConnection(Client* client_, uint64_t nodeID_, Endpoint& endpoint_)
{
    client = client_;
    nodeID = nodeID_;
    endpoint = endpoint_;
    autoFlush = false;
//    submitRequest.Init();
    Connect();
}

void ShardConnection::Connect()
{
//    Log_Debug("Connecting to %s", endpoint.ToString());
    MessageConnection::Connect(endpoint);
}

bool ShardConnection::SendRequest(Request* request)
{
    SDBPRequestMessage  msg;

    sentRequests.Append(request);

    msg.request = request;
    Write(msg);
    request->numTry++;
    request->requestTime = EventLoop::Now();
    //request->requestTime = NowClock();

//    if (request->numTry > 1)
//        Log_Debug("Resending, commandID: %U, conn: %s", request->commandID, endpoint.ToString());

    Log_Debug("Sending conn: %s, writeBuffer = %B", endpoint.ToString(), writeBuffer);

    // buffer is saturated
    if (writeBuffer->GetLength() >= MESSAGING_BUFFER_THRESHOLD)
        return false;

    return true;
}

void ShardConnection::SendSubmit(uint64_t /*quorumID*/)
{
//    Log_Debug("Flushing, conn: %s", endpoint.ToString());
//    SDBPRequestMessage  msg;
//
//    // TODO: optimize away submitRequest and msg by writing the buffer in constructor
//    submitRequest.Submit(quorumID);
//    msg.request = &submitRequest;
//    Write(msg);

    Flush();
}

void ShardConnection::Flush()
{
    FlushWriteBuffer();
}

uint64_t ShardConnection::GetNodeID()
{
    return nodeID;
}

Endpoint& ShardConnection::GetEndpoint()
{
    return endpoint;
}

bool ShardConnection::IsWritePending()
{
    return tcpwrite.active;
}

void ShardConnection::SetQuorumMembership(uint64_t quorumID)
{
    // SortedList takes care of unique IDs
    quorums.Add(quorumID, true);
}

void ShardConnection::ClearQuorumMembership(uint64_t quorumID)
{
    quorums.Remove(quorumID);
}

void ShardConnection::ClearQuorumMemberships()
{
    quorums.Clear();
}

SortedList<uint64_t>& ShardConnection::GetQuorumList()
{
    return quorums;
}

bool ShardConnection::OnMessage(ReadBuffer& rbuf)
{
    SDBPResponseMessage msg;
    Request*            it;
    uint64_t            quorumID;

    CLIENT_MUTEX_GUARD_DECLARE();

    Log_Debug("Shard conn: %s, message: %R", endpoint.ToString(), &rbuf);

    response.Init();
    msg.response = &response;
    if (!msg.Read(rbuf))
        return false;

    // find the request in sent requests by commandID
    FOREACH (it, sentRequests)
    {
        if (it->commandID == response.commandID)
        {
            // TODO: what to do when the first in the queue returns NOSERVICE
            // but the others return OK ?!?

            // TODO: invalidate quorum state on NOSERVICE response
            if (response.type == CLIENTRESPONSE_NOSERVICE)
            {
                quorumID = it->quorumID;
                InvalidateQuorum(quorumID);
                return false;
            }

            sentRequests.Remove(it);
            break;
        }
    }

    client->result->AppendRequestResponse(&response);
    response.Init();

    return false;
}

void ShardConnection::OnWrite()
{
    CLIENT_MUTEX_GUARD_DECLARE();

    MessageConnection::OnWrite();
    SendQuorumRequests();
}

void ShardConnection::OnConnect()
{
    Log_Trace();
    Log_Debug("Shard connection connected, endpoint: %s", endpoint.ToString());

    CLIENT_MUTEX_GUARD_DECLARE();

    MessageConnection::OnConnect();
    SendQuorumRequests();
}

void ShardConnection::OnClose()
{
//    Log_Debug("Shard connection closing: %s", endpoint.ToString());

    Request*    it;
    Request*    prev;
    uint64_t*   itQuorum;
    uint64_t*   itNext;

    CLIENT_MUTEX_GUARD_DECLARE();

    // close the socket and try reconnecting
    MessageConnection::OnClose();

    // invalidate quorums
    for (itQuorum = quorums.First(); itQuorum != NULL; itQuorum = itNext)
    {
        itNext = quorums.Next(itQuorum);
        InvalidateQuorum(*itQuorum);
    }

    // put back requests that have no response to the client's quorum queue
    for (it = sentRequests.Last(); it != NULL; it = prev)
    {
        prev = sentRequests.Prev(it);
        sentRequests.Remove(it);
        client->AddRequestToQuorum(it, false);
    }
}

void ShardConnection::InvalidateQuorum(uint64_t quorumID)
{
    Request*    it;
    Request*    prev;

    for (it = sentRequests.Last(); it != NULL; it = prev)
    {
        prev = sentRequests.Prev(it);
        if (it->quorumID == quorumID)
        {
            sentRequests.Remove(it);
            client->AddRequestToQuorum(it, false);
        }
    }

    client->InvalidateQuorum(quorumID, nodeID);
}

void ShardConnection::SendQuorumRequests()
{
    uint64_t*   qit;

    // notify the client so that it can assign the requests to the connection
    FOREACH (qit, quorums)
        client->SendQuorumRequest(this, *qit);
}
<commit_msg>Removed Log_Debug from client.<commit_after>#include "SDBPShardConnection.h"
#include "SDBPClient.h"
#include "Application/Common/ClientResponse.h"
#include "Application/SDBP/SDBPRequestMessage.h"
#include "Application/SDBP/SDBPResponseMessage.h"

#define CONN_BUFSIZE    4096

#define CLIENT_MUTEX_GUARD_DECLARE()    MutexGuard mutexGuard(client->mutex)
#define CLIENT_MUTEX_LOCK()             mutexGuard.Lock()
#define CLIENT_MUTEX_UNLOCK()           mutexGuard.Unlock()

using namespace SDBPClient;

static bool LessThan(uint64_t a, uint64_t b)
{
    return a < b;
}

ShardConnection::ShardConnection(Client* client_, uint64_t nodeID_, Endpoint& endpoint_)
{
    client = client_;
    nodeID = nodeID_;
    endpoint = endpoint_;
    autoFlush = false;
//    submitRequest.Init();
    Connect();
}

void ShardConnection::Connect()
{
//    Log_Debug("Connecting to %s", endpoint.ToString());
    MessageConnection::Connect(endpoint);
}

bool ShardConnection::SendRequest(Request* request)
{
    SDBPRequestMessage  msg;

    sentRequests.Append(request);

    msg.request = request;
    Write(msg);
    request->numTry++;
    request->requestTime = EventLoop::Now();
    //request->requestTime = NowClock();

//    if (request->numTry > 1)
//        Log_Debug("Resending, commandID: %U, conn: %s", request->commandID, endpoint.ToString());

    //Log_Debug("Sending conn: %s, writeBuffer = %B", endpoint.ToString(), writeBuffer);

    // buffer is saturated
    if (writeBuffer->GetLength() >= MESSAGING_BUFFER_THRESHOLD)
        return false;

    return true;
}

void ShardConnection::SendSubmit(uint64_t /*quorumID*/)
{
//    Log_Debug("Flushing, conn: %s", endpoint.ToString());
//    SDBPRequestMessage  msg;
//
//    // TODO: optimize away submitRequest and msg by writing the buffer in constructor
//    submitRequest.Submit(quorumID);
//    msg.request = &submitRequest;
//    Write(msg);

    Flush();
}

void ShardConnection::Flush()
{
    FlushWriteBuffer();
}

uint64_t ShardConnection::GetNodeID()
{
    return nodeID;
}

Endpoint& ShardConnection::GetEndpoint()
{
    return endpoint;
}

bool ShardConnection::IsWritePending()
{
    return tcpwrite.active;
}

void ShardConnection::SetQuorumMembership(uint64_t quorumID)
{
    // SortedList takes care of unique IDs
    quorums.Add(quorumID, true);
}

void ShardConnection::ClearQuorumMembership(uint64_t quorumID)
{
    quorums.Remove(quorumID);
}

void ShardConnection::ClearQuorumMemberships()
{
    quorums.Clear();
}

SortedList<uint64_t>& ShardConnection::GetQuorumList()
{
    return quorums;
}

bool ShardConnection::OnMessage(ReadBuffer& rbuf)
{
    SDBPResponseMessage msg;
    Request*            it;
    uint64_t            quorumID;

    CLIENT_MUTEX_GUARD_DECLARE();

    //Log_Debug("Shard conn: %s, message: %R", endpoint.ToString(), &rbuf);

    response.Init();
    msg.response = &response;
    if (!msg.Read(rbuf))
        return false;

    // find the request in sent requests by commandID
    FOREACH (it, sentRequests)
    {
        if (it->commandID == response.commandID)
        {
            // TODO: what to do when the first in the queue returns NOSERVICE
            // but the others return OK ?!?

            // TODO: invalidate quorum state on NOSERVICE response
            if (response.type == CLIENTRESPONSE_NOSERVICE)
            {
                quorumID = it->quorumID;
                InvalidateQuorum(quorumID);
                return false;
            }

            sentRequests.Remove(it);
            break;
        }
    }

    client->result->AppendRequestResponse(&response);
    response.Init();

    return false;
}

void ShardConnection::OnWrite()
{
    CLIENT_MUTEX_GUARD_DECLARE();

    MessageConnection::OnWrite();
    SendQuorumRequests();
}

void ShardConnection::OnConnect()
{
    Log_Trace();
    //Log_Debug("Shard connection connected, endpoint: %s", endpoint.ToString());

    CLIENT_MUTEX_GUARD_DECLARE();

    MessageConnection::OnConnect();
    SendQuorumRequests();
}

void ShardConnection::OnClose()
{
//    Log_Debug("Shard connection closing: %s", endpoint.ToString());

    Request*    it;
    Request*    prev;
    uint64_t*   itQuorum;
    uint64_t*   itNext;

    CLIENT_MUTEX_GUARD_DECLARE();

    // close the socket and try reconnecting
    MessageConnection::OnClose();

    // invalidate quorums
    for (itQuorum = quorums.First(); itQuorum != NULL; itQuorum = itNext)
    {
        itNext = quorums.Next(itQuorum);
        InvalidateQuorum(*itQuorum);
    }

    // put back requests that have no response to the client's quorum queue
    for (it = sentRequests.Last(); it != NULL; it = prev)
    {
        prev = sentRequests.Prev(it);
        sentRequests.Remove(it);
        client->AddRequestToQuorum(it, false);
    }
}

void ShardConnection::InvalidateQuorum(uint64_t quorumID)
{
    Request*    it;
    Request*    prev;

    for (it = sentRequests.Last(); it != NULL; it = prev)
    {
        prev = sentRequests.Prev(it);
        if (it->quorumID == quorumID)
        {
            sentRequests.Remove(it);
            client->AddRequestToQuorum(it, false);
        }
    }

    client->InvalidateQuorum(quorumID, nodeID);
}

void ShardConnection::SendQuorumRequests()
{
    uint64_t*   qit;

    // notify the client so that it can assign the requests to the connection
    FOREACH (qit, quorums)
        client->SendQuorumRequest(this, *qit);
}
<|endoftext|>


<commit_before>MAIN_ENV

//========================================================================
// Global definitions
//========================================================================

typedef struct {
  int n;
  int total;
  LOCKDEC(totalLock)
  int maxProfit;
  LOCKDEC(profitLock)
  int* maxBoard;
  LOCKDEC(boardLock)
  int p;
} GM;

GM *gm;

//========================================================================
// Helper methods
//========================================================================

void printBoard(int* board) {
  register int i, j;
  int row, bit;
  int n = gm->n;

  for (i = 0; i < n; i++) {
    bit = board[i];
    row = bit ^ (bit & (bit - 1));

    for (j = 0; j < n; j++) {
      if ((row >> j) & 1) printf("Q ");
      else printf("_ ");
    }
    printf("\n");
  }
}

void printResults() {
  printf("Maximum profit board\n");
  printf("Max profit: %d\n", gm->maxProfit);
  printf("Total solutions: %d\n", gm->total);
  printf("Maximum profit board\n");
  printBoard(gm->maxBoard);
}

int bitsToValue(int bits){
  if (!bits) return 0;

  int counter = -1;

  while (bits > 0) {
    bits = bits >> 1;
    counter++;
  }
  return counter;
}

//========================================================================
// Parallel N-Queens Algorithm
//========================================================================
//
//  The sequential algorithm that the following code was derived from is
//  based heavily on optimizations published online by Jeff Somers, and
//  can be found at jsomers.com/nqueen_demo/nqueens.html
//
//========================================================================

void pnqueens(int bits, int n, char middle) {
  int localTotal = 0;
  int localMaxProfit = 0;
  int localMaxBoard[n];
  int results[n];

  int stack[n+2];
  register int* stackPointer;

  int columns[n];
  int updiags[n];
  int dndiags[n];

  register int row=1;
  register int lsb;

  int mask = (1 << n) - 1;

  stack[0] = -1;
  stackPointer = stack;
  *stackPointer = 0;
  stackPointer++;
  row = 1;

  results[0] = bits;
  columns[0] = 0;
  columns[1] = bits;
  updiags[0] = 0;
  updiags[1] = bits << 1;
  dndiags[0] = 0;
  dndiags[1] = bits >> 1;

  bits = mask & ~(columns[1] | updiags[1] | dndiags[1]);

  while(1) {
    if (!bits) {
      stackPointer--;
      if (stackPointer == stack) {
        break;
      }
      bits = *stackPointer;
      row--;
    }
    else {
      lsb = bits ^ (bits & (bits - 1));
      bits &= ~lsb;

      results[row] = lsb;

      if (row < n-1) {
        int rowLast = row;
        row++;
        columns[row] = columns[rowLast] | lsb;
        updiags[row] = ( updiags[rowLast] | lsb ) << 1;
        dndiags[row] = ( dndiags[rowLast] | lsb ) >> 1;

        *stackPointer = bits;
        stackPointer++;

        bits = mask & ~(columns[row] | updiags[row] | dndiags[row]);
      }
      else {
        if (!middle) {
          localTotal += 2;
          register int k;
          register int profit0 = 0;
          register int profit1 = 0;

          for (k = 0; k < n; k++) {
            profit0 += abs(k - bitsToValue(results[k]));
            profit1 += abs((n - 1 - k) - bitsToValue(results[k]));
          }

          if ((profit0 > localMaxProfit) && (profit0 >= profit1)) {
            localMaxProfit = profit0;
            for (k = 0; k < n; k++) {
              localMaxBoard[k] = results[k];
            }
          }
          else if (profit1 > localMaxProfit) {
            localMaxProfit = profit1;
            for (k = 0; k < n; k++) {
              localMaxBoard[k] = results[k];
            }
          }
        }
        else {
          localTotal++;
          register int k;
          register int profit = 0;

          for (k = 0; k < n; k++) {
            profit += abs(k - bitsToValue(results[k]));
          }

          if (profit > localMaxProfit) {
            localMaxProfit = profit;
            for (k = 0; k < n; k++) {
              localMaxBoard[k] = results[k];
            }
          }
        }

        stackPointer--;
        bits = *stackPointer;
        row--;
      }
    }
  }

  // All solutions for this initial position found
  LOCK(gm->totalLock)
  gm->total += localTotal;
  UNLOCK(gm->totalLock)

  LOCK(gm->profitLock)
  if (localMaxProfit > gm->maxProfit) {
    register int k;

    gm->maxProfit = localMaxProfit;
    LOCK(gm->boardLock)
    for (k = 0; k < n; k++) {
      gm->maxBoard[k] = localMaxBoard[k];
    }
    UNLOCK(gm->boardLock)
  }
  UNLOCK(gm->profitLock)
}

void wrapper(void) {
  int pid;
  int n, p, i;

  GET_PID(pid);
  n = gm->n;
  p = gm->p;

  for (i = 0+pid; i < (n + 1)/2; i+=p) {
    char middle = (i == (n+1)/2 -1);
    int bits = (1 << i);
    pnqueens(bits, n, middle);
  }
}

//========================================================================
// Main
//========================================================================

int main (int argc, char **argv) {
  int i, n, p, total, maxProfit;
  int* maxBoard;
  unsigned int t1, t2, t3;

  MAIN_INITENV

  //Enforce arguments
  if (argc != 3) {
    printf("Usage: nqueens-seq <P> <N>\nAborting.\n");
    exit(0);
  }

  gm = (GM*)G_MALLOC(sizeof(GM));
  p = gm->p = atoi(argv[1]);
  n = gm->n = atoi(argv[2]);

  assert(p > 0);
  assert(p <= 8);

  gm->total = 0;
  gm->maxProfit = 0;
  gm->maxBoard = (int*)G_MALLOC(n*sizeof(int));

  LOCKINIT(gm->totalLock);
  LOCKINIT(gm->profitLock);
  LOCKINIT(gm->boardLock);

  for (i = 0; i < p-1; i++) CREATE(wrapper)

  CLOCK(t1)
  wrapper();
  WAIT_FOR_END(p-1)
  CLOCK(t2)
  printResults();
  CLOCK(t3)
  printf("Computation time: %u microseconds\n", t2-t1);
  printf("Printing time:    %u microseconds\n", t3-t2);
  G_FREE(maxBoard,n*sizeof(int))
  MAIN_END
  return 0;
}
<commit_msg>oops, bug fixed<commit_after>MAIN_ENV

//========================================================================
// Global definitions
//========================================================================

typedef struct {
  int n;
  int total;
  LOCKDEC(totalLock)
  int maxProfit;
  LOCKDEC(profitLock)
  int* maxBoard;
  LOCKDEC(boardLock)
  int p;
} GM;

GM *gm;

//========================================================================
// Helper methods
//========================================================================

void printBoard(int* board) {
  register int i, j;
  int row, bit;
  int n = gm->n;

  for (i = 0; i < n; i++) {
    bit = board[i];
    row = bit ^ (bit & (bit - 1));

    for (j = 0; j < n; j++) {
      if ((row >> j) & 1) printf("Q ");
      else printf("_ ");
    }
    printf("\n");
  }
}

void printResults() {
  printf("Maximum profit board\n");
  printf("Max profit: %d\n", gm->maxProfit);
  printf("Total solutions: %d\n", gm->total);
  printf("Maximum profit board\n");
  printBoard(gm->maxBoard);
}

int bitsToValue(int bits){
  if (!bits) return 0;

  int counter = -1;

  while (bits > 0) {
    bits = bits >> 1;
    counter++;
  }
  return counter;
}

//========================================================================
// Parallel N-Queens Algorithm
//========================================================================
//
//  The sequential algorithm that the following code was derived from is
//  based heavily on optimizations published online by Jeff Somers, and
//  can be found at jsomers.com/nqueen_demo/nqueens.html
//
//========================================================================

void pnqueens(int bits, int n, char middle) {
  int localTotal = 0;
  int localMaxProfit = 0;
  int localMaxBoard[n];
  int results[n];

  int stack[n+2];
  register int* stackPointer;

  int columns[n];
  int updiags[n];
  int dndiags[n];

  register int row=1;
  register int lsb;

  int mask = (1 << n) - 1;

  stack[0] = -1;
  stackPointer = stack;
  *stackPointer = 0;
  stackPointer++;
  row = 1;

  results[0] = bits;
  columns[0] = 0;
  columns[1] = bits;
  updiags[0] = 0;
  updiags[1] = bits << 1;
  dndiags[0] = 0;
  dndiags[1] = bits >> 1;

  bits = mask & ~(columns[1] | updiags[1] | dndiags[1]);

  while(1) {
    if (!bits) {
      stackPointer--;
      if (stackPointer == stack) {
        break;
      }
      bits = *stackPointer;
      row--;
    }
    else {
      lsb = bits ^ (bits & (bits - 1));
      bits &= ~lsb;

      results[row] = lsb;

      if (row < n-1) {
        int rowLast = row;
        row++;
        columns[row] = columns[rowLast] | lsb;
        updiags[row] = ( updiags[rowLast] | lsb ) << 1;
        dndiags[row] = ( dndiags[rowLast] | lsb ) >> 1;

        *stackPointer = bits;
        stackPointer++;

        bits = mask & ~(columns[row] | updiags[row] | dndiags[row]);
      }
      else {
        if (!middle) {
          localTotal += 2;
          register int k;
          register int profit0 = 0;
          register int profit1 = 0;

          for (k = 0; k < n; k++) {
            profit0 += abs(k - bitsToValue(results[k]));
            profit1 += abs((n - 1 - k) - bitsToValue(results[k]));
          }

          if ((profit0 > localMaxProfit) && (profit0 >= profit1)) {
            localMaxProfit = profit0;
            for (k = 0; k < n; k++) {
              localMaxBoard[k] = results[k];
            }
          }
          else if (profit1 > localMaxProfit) {
            localMaxProfit = profit1;
            for (k = 0; k < n; k++) {
              localMaxBoard[k] = results[k];
            }
          }
        }
        else {
          localTotal++;
          register int k;
          register int profit = 0;

          for (k = 0; k < n; k++) {
            profit += abs(k - bitsToValue(results[k]));
          }

          if (profit > localMaxProfit) {
            localMaxProfit = profit;
            for (k = 0; k < n; k++) {
              localMaxBoard[k] = results[k];
            }
          }
        }

        stackPointer--;
        bits = *stackPointer;
        row--;
      }
    }
  }

  // All solutions for this initial position found
  LOCK(gm->totalLock)
  gm->total += localTotal;
  UNLOCK(gm->totalLock)

  LOCK(gm->profitLock)
  if (localMaxProfit > gm->maxProfit) {
    register int k;

    gm->maxProfit = localMaxProfit;
    LOCK(gm->boardLock)
    for (k = 0; k < n; k++) {
      gm->maxBoard[k] = localMaxBoard[k];
    }
    UNLOCK(gm->boardLock)
  }
  UNLOCK(gm->profitLock)
}

void wrapper(void) {
  int pid;
  int n, p, i;

  GET_PID(pid);
  n = gm->n;
  p = gm->p;

  for (i = 0+pid; i < (n + 1)/2; i+=p) {
    char middle = ((i == (n+1)/2 -1) & (n & 1));
    int bits = (1 << i);
    pnqueens(bits, n, middle);
  }
}

//========================================================================
// Main
//========================================================================

int main (int argc, char **argv) {
  int i, n, p, total, maxProfit;
  int* maxBoard;
  unsigned int t1, t2, t3;

  MAIN_INITENV

  //Enforce arguments
  if (argc != 3) {
    printf("Usage: nqueens-seq <P> <N>\nAborting.\n");
    exit(0);
  }

  gm = (GM*)G_MALLOC(sizeof(GM));
  p = gm->p = atoi(argv[1]);
  n = gm->n = atoi(argv[2]);

  assert(p > 0);
  assert(p <= 8);

  gm->total = 0;
  gm->maxProfit = 0;
  gm->maxBoard = (int*)G_MALLOC(n*sizeof(int));

  LOCKINIT(gm->totalLock);
  LOCKINIT(gm->profitLock);
  LOCKINIT(gm->boardLock);

  for (i = 0; i < p-1; i++) CREATE(wrapper)

  CLOCK(t1)
  wrapper();
  WAIT_FOR_END(p-1)
  CLOCK(t2)
  printResults();
  CLOCK(t3)
  printf("Computation time: %u microseconds\n", t2-t1);
  printf("Printing time:    %u microseconds\n", t3-t2);
  G_FREE(maxBoard,n*sizeof(int))
  MAIN_END
  return 0;
}
<|endoftext|>


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

 QGroundControl Open Source Ground Control Station

 (c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>

 This file is part of the QGROUNDCONTROL project

 QGROUNDCONTROL 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.

 QGROUNDCONTROL 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 General Public License for more details.

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

 ======================================================================*/

#include "PX4AutoPilotPlugin.h"
#include "AutoPilotPluginManager.h"
#include "PX4AirframeLoader.h"
#include "FlightModesComponentController.h"
#include "AirframeComponentController.h"
#include "UAS.h"
#include "FirmwarePlugin/PX4/PX4ParameterMetaData.h"  // FIXME: Hack
#include "FirmwarePlugin/PX4/PX4FirmwarePlugin.h"  // FIXME: Hack
#include "QGCApplication.h"

/// @file
///     @brief This is the AutoPilotPlugin implementatin for the MAV_AUTOPILOT_PX4 type.
///     @author Don Gagne <don@thegagnes.com>

enum PX4_CUSTOM_MAIN_MODE {
    PX4_CUSTOM_MAIN_MODE_MANUAL = 1,
    PX4_CUSTOM_MAIN_MODE_ALTCTL,
    PX4_CUSTOM_MAIN_MODE_POSCTL,
    PX4_CUSTOM_MAIN_MODE_AUTO,
    PX4_CUSTOM_MAIN_MODE_ACRO,
    PX4_CUSTOM_MAIN_MODE_OFFBOARD,
    PX4_CUSTOM_MAIN_MODE_STABILIZED,
};

enum PX4_CUSTOM_SUB_MODE_AUTO {
    PX4_CUSTOM_SUB_MODE_AUTO_READY = 1,
    PX4_CUSTOM_SUB_MODE_AUTO_TAKEOFF,
    PX4_CUSTOM_SUB_MODE_AUTO_LOITER,
    PX4_CUSTOM_SUB_MODE_AUTO_MISSION,
    PX4_CUSTOM_SUB_MODE_AUTO_RTL,
    PX4_CUSTOM_SUB_MODE_AUTO_LAND,
    PX4_CUSTOM_SUB_MODE_AUTO_RTGS
};

union px4_custom_mode {
    struct {
        uint16_t reserved;
        uint8_t main_mode;
        uint8_t sub_mode;
    };
    uint32_t data;
    float data_float;
};

PX4AutoPilotPlugin::PX4AutoPilotPlugin(Vehicle* vehicle, QObject* parent) :
    AutoPilotPlugin(vehicle, parent),
    _airframeComponent(NULL),
    _radioComponent(NULL),
    _esp8266Component(NULL),
    _flightModesComponent(NULL),
    _sensorsComponent(NULL),
    _safetyComponent(NULL),
    _powerComponent(NULL),
    _incorrectParameterVersion(false)
{
    Q_ASSERT(vehicle);

    _airframeFacts = new PX4AirframeLoader(this, _vehicle->uas(), this);
    Q_CHECK_PTR(_airframeFacts);

    PX4AirframeLoader::loadAirframeFactMetaData();
}

PX4AutoPilotPlugin::~PX4AutoPilotPlugin()
{
    delete _airframeFacts;
}

const QVariantList& PX4AutoPilotPlugin::vehicleComponents(void)
{
    if (_components.count() == 0 && !_incorrectParameterVersion) {
        Q_ASSERT(_vehicle);

        if (parametersReady()) {
            _airframeComponent = new AirframeComponent(_vehicle, this);
            _airframeComponent->setupTriggerSignals();
            _components.append(QVariant::fromValue((VehicleComponent*)_airframeComponent));

            _radioComponent = new PX4RadioComponent(_vehicle, this);
            _radioComponent->setupTriggerSignals();
            _components.append(QVariant::fromValue((VehicleComponent*)_radioComponent));

            //-- Is there an ESP8266 Connected?
#ifdef QT_DEBUG
#ifndef __mobile__
            //-- Unit test barfs if I ask for a parameter that does not exists. The whole poing of the
            //   test below is to behave differently if ESP8266 is present or not.
    if (!qgcApp()->runningUnitTests()) {
#endif
#endif
            Fact* espVersion = getFact(FactSystem::ParameterProvider, MAV_COMP_ID_UDP_BRIDGE, "SW_VER");
            if(espVersion && espVersion->componentId() == MAV_COMP_ID_UDP_BRIDGE) {
                _esp8266Component = new PX4ESP8266Component(_vehicle, this);
                _esp8266Component->setupTriggerSignals();
                _components.append(QVariant::fromValue((VehicleComponent*)_esp8266Component));
            }
#ifdef QT_DEBUG
#ifndef __mobile__
    }
#endif
#endif

            _flightModesComponent = new FlightModesComponent(_vehicle, this);
            _flightModesComponent->setupTriggerSignals();
            _components.append(QVariant::fromValue((VehicleComponent*)_flightModesComponent));

            _sensorsComponent = new SensorsComponent(_vehicle, this);
            _sensorsComponent->setupTriggerSignals();
            _components.append(QVariant::fromValue((VehicleComponent*)_sensorsComponent));

            _powerComponent = new PowerComponent(_vehicle, this);
            _powerComponent->setupTriggerSignals();
            _components.append(QVariant::fromValue((VehicleComponent*)_powerComponent));

            _safetyComponent = new SafetyComponent(_vehicle, this);
            _safetyComponent->setupTriggerSignals();
            _components.append(QVariant::fromValue((VehicleComponent*)_safetyComponent));

            _tuningComponent = new PX4TuningComponent(_vehicle, this);
            _tuningComponent->setupTriggerSignals();
            _components.append(QVariant::fromValue((VehicleComponent*)_tuningComponent));
        } else {
            qWarning() << "Call to vehicleCompenents prior to parametersReady";
        }
    }

    return _components;
}

/// This will perform various checks prior to signalling that the plug in ready
void PX4AutoPilotPlugin::_parametersReadyPreChecks(bool missingParameters)
{
    // Check for older parameter version set
    // FIXME: Firmware is moving to version stamp parameter set. Once that is complete the version stamp
    // should be used instead.
    if (parameterExists(FactSystem::defaultComponentId, "SENS_GYRO_XOFF")) {
        _incorrectParameterVersion = true;
        qgcApp()->showMessage("This version of GroundControl can only perform vehicle setup on a newer version of firmware. "
                              "Please perform a Firmware Upgrade if you wish to use Vehicle Setup.");
	}

    _parametersReady = true;
    _missingParameters = missingParameters;
    emit missingParametersChanged(_missingParameters);
    emit parametersReadyChanged(_parametersReady);
}
<commit_msg>Using proper Fact testing to test if the WiFi Bridge is present.<commit_after>/*=====================================================================

 QGroundControl Open Source Ground Control Station

 (c) 2009 - 2014 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>

 This file is part of the QGROUNDCONTROL project

 QGROUNDCONTROL 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.

 QGROUNDCONTROL 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 General Public License for more details.

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

 ======================================================================*/

#include "PX4AutoPilotPlugin.h"
#include "AutoPilotPluginManager.h"
#include "PX4AirframeLoader.h"
#include "FlightModesComponentController.h"
#include "AirframeComponentController.h"
#include "UAS.h"
#include "FirmwarePlugin/PX4/PX4ParameterMetaData.h"  // FIXME: Hack
#include "FirmwarePlugin/PX4/PX4FirmwarePlugin.h"  // FIXME: Hack
#include "QGCApplication.h"

/// @file
///     @brief This is the AutoPilotPlugin implementatin for the MAV_AUTOPILOT_PX4 type.
///     @author Don Gagne <don@thegagnes.com>

enum PX4_CUSTOM_MAIN_MODE {
    PX4_CUSTOM_MAIN_MODE_MANUAL = 1,
    PX4_CUSTOM_MAIN_MODE_ALTCTL,
    PX4_CUSTOM_MAIN_MODE_POSCTL,
    PX4_CUSTOM_MAIN_MODE_AUTO,
    PX4_CUSTOM_MAIN_MODE_ACRO,
    PX4_CUSTOM_MAIN_MODE_OFFBOARD,
    PX4_CUSTOM_MAIN_MODE_STABILIZED,
};

enum PX4_CUSTOM_SUB_MODE_AUTO {
    PX4_CUSTOM_SUB_MODE_AUTO_READY = 1,
    PX4_CUSTOM_SUB_MODE_AUTO_TAKEOFF,
    PX4_CUSTOM_SUB_MODE_AUTO_LOITER,
    PX4_CUSTOM_SUB_MODE_AUTO_MISSION,
    PX4_CUSTOM_SUB_MODE_AUTO_RTL,
    PX4_CUSTOM_SUB_MODE_AUTO_LAND,
    PX4_CUSTOM_SUB_MODE_AUTO_RTGS
};

union px4_custom_mode {
    struct {
        uint16_t reserved;
        uint8_t main_mode;
        uint8_t sub_mode;
    };
    uint32_t data;
    float data_float;
};

PX4AutoPilotPlugin::PX4AutoPilotPlugin(Vehicle* vehicle, QObject* parent) :
    AutoPilotPlugin(vehicle, parent),
    _airframeComponent(NULL),
    _radioComponent(NULL),
    _esp8266Component(NULL),
    _flightModesComponent(NULL),
    _sensorsComponent(NULL),
    _safetyComponent(NULL),
    _powerComponent(NULL),
    _incorrectParameterVersion(false)
{
    Q_ASSERT(vehicle);

    _airframeFacts = new PX4AirframeLoader(this, _vehicle->uas(), this);
    Q_CHECK_PTR(_airframeFacts);

    PX4AirframeLoader::loadAirframeFactMetaData();
}

PX4AutoPilotPlugin::~PX4AutoPilotPlugin()
{
    delete _airframeFacts;
}

const QVariantList& PX4AutoPilotPlugin::vehicleComponents(void)
{
    if (_components.count() == 0 && !_incorrectParameterVersion) {
        Q_ASSERT(_vehicle);

        if (parametersReady()) {
            _airframeComponent = new AirframeComponent(_vehicle, this);
            _airframeComponent->setupTriggerSignals();
            _components.append(QVariant::fromValue((VehicleComponent*)_airframeComponent));

            _radioComponent = new PX4RadioComponent(_vehicle, this);
            _radioComponent->setupTriggerSignals();
            _components.append(QVariant::fromValue((VehicleComponent*)_radioComponent));

            //-- Is there an ESP8266 Connected?
            if(factExists(FactSystem::ParameterProvider, MAV_COMP_ID_UDP_BRIDGE, "SW_VER")) {
                _esp8266Component = new PX4ESP8266Component(_vehicle, this);
                _esp8266Component->setupTriggerSignals();
                _components.append(QVariant::fromValue((VehicleComponent*)_esp8266Component));
            }

            _flightModesComponent = new FlightModesComponent(_vehicle, this);
            _flightModesComponent->setupTriggerSignals();
            _components.append(QVariant::fromValue((VehicleComponent*)_flightModesComponent));

            _sensorsComponent = new SensorsComponent(_vehicle, this);
            _sensorsComponent->setupTriggerSignals();
            _components.append(QVariant::fromValue((VehicleComponent*)_sensorsComponent));

            _powerComponent = new PowerComponent(_vehicle, this);
            _powerComponent->setupTriggerSignals();
            _components.append(QVariant::fromValue((VehicleComponent*)_powerComponent));

            _safetyComponent = new SafetyComponent(_vehicle, this);
            _safetyComponent->setupTriggerSignals();
            _components.append(QVariant::fromValue((VehicleComponent*)_safetyComponent));

            _tuningComponent = new PX4TuningComponent(_vehicle, this);
            _tuningComponent->setupTriggerSignals();
            _components.append(QVariant::fromValue((VehicleComponent*)_tuningComponent));
        } else {
            qWarning() << "Call to vehicleCompenents prior to parametersReady";
        }
    }

    return _components;
}

/// This will perform various checks prior to signalling that the plug in ready
void PX4AutoPilotPlugin::_parametersReadyPreChecks(bool missingParameters)
{
    // Check for older parameter version set
    // FIXME: Firmware is moving to version stamp parameter set. Once that is complete the version stamp
    // should be used instead.
    if (parameterExists(FactSystem::defaultComponentId, "SENS_GYRO_XOFF")) {
        _incorrectParameterVersion = true;
        qgcApp()->showMessage("This version of GroundControl can only perform vehicle setup on a newer version of firmware. "
                              "Please perform a Firmware Upgrade if you wish to use Vehicle Setup.");
	}

    _parametersReady = true;
    _missingParameters = missingParameters;
    emit missingParametersChanged(_missingParameters);
    emit parametersReadyChanged(_parametersReady);
}
<|endoftext|>


<commit_before>//
// Created by Silt on 23.04.2017.
//

#include <stdint.h>
#include <stdlib.h>
#include <chrono>
#include <thread>

#include "MachineOne.h"
#include "logger.h"

#include "ISR.h"
#include "Control.h"

#include "PulseMessageReceiverService.h"
#include "PulseMessageSenderService.h"

#include "Calibration.h"

#include "LightSystemService.h"
#include "LightSystemHal.h"
#include "LightSystemController.h"
#include "BLightSystem.h"

#include "PuckManager.h"
#include "PuckSignal.h"

#include "LightSystemEnum.h"

#include "HeightMeasurementController.h"
#include "HeightService.h"

#include "ActorHandler.h"

#include "SignalDistributer.h"
#include "SortingSwichtControl.h"

SETUP(MachineOne){
	REG_TEST(programm_m1, 1, "Just Create some distance trackers an let them run (no changes on the way)");
};

BEFORE_TC(MachineOne){return 1;}

AFTER_TC(MachineOne){return 1;}

BEFORE(MachineOne){return 1;}

AFTER(MachineOne){return 1;}

TEST_IMPL(MachineOne, programm_m1){

	//----------INIT------------

	//INIT MAIN CHANNEL
	PulseMessageReceiverService mainChannel; ///Main communication channel
	int mainChid = mainChannel.newChannel(); ///Chid of main com

	//INIT ISR
	Control isrCntrl(mainChid);
	ISR isr(&isrCntrl);
	std::thread isr_th(ref(isr));

	//INIT Serial
	//Init PMR
	rcv::PulseMessageReceiverService pmrSer1;
	int pmrSer1Chid = pmrSer1.newChannel();

	//Init PMS
	rcv::PulseMessageReceiverService pmsChannelCreatorSer1;
	int pmsSer1Chid = pmsChannelCreatorSer1.newChannel();
	PulseMessageSenderService pmsSer1(pmsSer1Chid);

	//Init Sender & Receiver
	char ser1_path[] = "/dev/ser1";
	SerialSender senderSer1(ser1_path);
	SerialReceiver receiverSer1(ser1_path);

	//Init Protocol
	SerialProtocoll protoSer1(SENDER);

	//Init Serial
	Serial ser1(receiverSer1, senderSer1, protoSer1, pmsSer1Chid, pmrSer1Chid);

	//Init SerialService
	SerialService serialService(pmsSer1Chid);

	//INIT CBS
	ConveyorBeltService cbs;

	//INIT CALIBRATION AND CALIBRATE
	Calibration& calibration = Calibration::getInstance();
	std::cout << "start Hightcal" << "\n";
	cout.flush();
	//calibration.calibrateHeighMeasurement();
	std::cout << "start distancecal" << "\n";
	cout.flush();
	calibration.loadFromDisk("/Calibration.dat");

	//INIT LIGHTSYSTEM
	/*PulseMessageReceiverService lightsystemChannel; ///Lightsystem cntrl channel
	int lightsystemChid = ChannelCreate_r(0); //lightsystemChannel.newChannel();

	std::cout << "LightSystemChid" <<lightsystemChid << "\n";
	cout.flush();
	BLightSystem *lsHal = new LightSystemHal();
	LightSystemController *lightSystemCntrl = new LightSystemController(lightsystemChid, lsHal);
	LightSystemService *lightSystem = new LightSystemService(lightsystemChid);
	lightSystem->setWarningLevel(WARNING_OCCURED);*/

	//INIT HEIGHTMEASUREMENT
	PulseMessageReceiverService heightMChannelCreator; ///Create channel for heightm
	int heightMChid = heightMChannelCreator.newChannel();
	HeightMeasurementController::CalibrationData calData = calibration.getHmCalibration();
	HeightMeasurementController hmController(heightMChid, mainChid, &calData);
	HeightService heightService(heightMChid);

	//INIT SWITCH CONTROL
	SortingSwichtControl ssCntrl(mainChid);

	//Init actor handler
	ActorHandler actorHandler(cbs, heightService, ssCntrl, serialService);

	//INIT PUCK MNG
	PuckManager puckManager(mainChid);

	//INIT SIGNAL DISTRIBUTER
	SignalDistributer signalDistributer(&puckManager, &ssCntrl, &actorHandler);

	//TESTLOOP
	rcv::msg_t event;

	while(1){
		event = mainChannel.receivePulseMessage();
		std::cout << "Got something \n";
		switch(event.code){
			case 0: std::cout << "\n\n Height \n"; break; //Height
			case 2: std::cout << "\n\n Serial \n";break; //Serial
			case 4: std::cout << "\n\n Serial \n";break; //Serial
			case 5: std::cout << "\n\n ISR \n";break; //ISR
		}
		cout.flush();

		if(event.value == interrupts::BUTTON_RESET){
			cbs.changeState(ConveyorBeltState::STOP);
			std::cout << "\n\n RESET \n";
			puckManager = PuckManager(mainChid);
		}

		signalDistributer.process(event);
	}

}

<commit_msg>start serial<commit_after>//
// Created by Silt on 23.04.2017.
//

#include <stdint.h>
#include <stdlib.h>
#include <chrono>
#include <thread>

#include "MachineOne.h"
#include "logger.h"

#include "ISR.h"
#include "Control.h"

#include "PulseMessageReceiverService.h"
#include "PulseMessageSenderService.h"

#include "Calibration.h"

#include "LightSystemService.h"
#include "LightSystemHal.h"
#include "LightSystemController.h"
#include "BLightSystem.h"

#include "PuckManager.h"
#include "PuckSignal.h"

#include "LightSystemEnum.h"

#include "HeightMeasurementController.h"
#include "HeightService.h"

#include "ActorHandler.h"

#include "SignalDistributer.h"
#include "SortingSwichtControl.h"

#include <thread>

SETUP(MachineOne){
	REG_TEST(programm_m1, 1, "Just Create some distance trackers an let them run (no changes on the way)");
};

BEFORE_TC(MachineOne){return 1;}

AFTER_TC(MachineOne){return 1;}

BEFORE(MachineOne){return 1;}

AFTER(MachineOne){return 1;}

TEST_IMPL(MachineOne, programm_m1){

	//----------INIT------------

	//INIT MAIN CHANNEL
	PulseMessageReceiverService mainChannel; ///Main communication channel
	int mainChid = mainChannel.newChannel(); ///Chid of main com

	//INIT ISR
	Control isrCntrl(mainChid);
	ISR isr(&isrCntrl);
	std::thread isr_th(ref(isr));

	//INIT Serial
	//Init PMR
	rcv::PulseMessageReceiverService pmrSer1;
	int pmrSer1Chid = pmrSer1.newChannel();

	//Init PMS
	rcv::PulseMessageReceiverService pmsChannelCreatorSer1;
	int pmsSer1Chid = pmsChannelCreatorSer1.newChannel();
	PulseMessageSenderService pmsSer1(pmsSer1Chid);

	//Init Sender & Receiver
	char ser1_path[] = "/dev/ser1";
	SerialSender senderSer1(ser1_path);
	SerialReceiver receiverSer1(ser1_path);

	//Init Protocol
	SerialProtocoll protoSer1(SENDER);

	//Init Serial
	Serial ser1(receiverSer1, senderSer1, protoSer1, pmsSer1Chid, pmrSer1Chid);

	//Init SerialService
	SerialService serialService(pmsSer1Chid);

	std::thread ser1_thread(ref(ser1));

	//INIT CBS
	ConveyorBeltService cbs;

	//INIT CALIBRATION AND CALIBRATE
	Calibration& calibration = Calibration::getInstance();
	std::cout << "start Hightcal" << "\n";
	cout.flush();
	//calibration.calibrateHeighMeasurement();
	std::cout << "start distancecal" << "\n";
	cout.flush();
	calibration.loadFromDisk("/Calibration.dat");

	//INIT LIGHTSYSTEM
	/*PulseMessageReceiverService lightsystemChannel; ///Lightsystem cntrl channel
	int lightsystemChid = ChannelCreate_r(0); //lightsystemChannel.newChannel();

	std::cout << "LightSystemChid" <<lightsystemChid << "\n";
	cout.flush();
	BLightSystem *lsHal = new LightSystemHal();
	LightSystemController *lightSystemCntrl = new LightSystemController(lightsystemChid, lsHal);
	LightSystemService *lightSystem = new LightSystemService(lightsystemChid);
	lightSystem->setWarningLevel(WARNING_OCCURED);*/

	//INIT HEIGHTMEASUREMENT
	PulseMessageReceiverService heightMChannelCreator; ///Create channel for heightm
	int heightMChid = heightMChannelCreator.newChannel();
	HeightMeasurementController::CalibrationData calData = calibration.getHmCalibration();
	HeightMeasurementController hmController(heightMChid, mainChid, &calData);
	HeightService heightService(heightMChid);

	//INIT SWITCH CONTROL
	SortingSwichtControl ssCntrl(mainChid);

	//Init actor handler
	ActorHandler actorHandler(cbs, heightService, ssCntrl, serialService);

	//INIT PUCK MNG
	PuckManager puckManager(mainChid);

	//INIT SIGNAL DISTRIBUTER
	SignalDistributer signalDistributer(&puckManager, &ssCntrl, &actorHandler);

	//TESTLOOP
	rcv::msg_t event;

	while(1){
		event = mainChannel.receivePulseMessage();
		std::cout << "Got something \n";
		switch(event.code){
			case 0: std::cout << "\n\n Height \n"; break; //Height
			case 2: std::cout << "\n\n Serial \n";break; //Serial
			case 4: std::cout << "\n\n Serial \n";break; //Serial
			case 5: std::cout << "\n\n ISR \n";break; //ISR
		}
		cout.flush();

		if(event.value == interrupts::BUTTON_RESET){
			cbs.changeState(ConveyorBeltState::STOP);
			std::cout << "\n\n RESET \n";
			puckManager = PuckManager(mainChid);
		}

		signalDistributer.process(event);
	}

}

<|endoftext|>