<commit_before>/*************************************************************************
 *
 *  $RCSfile: ZConnectionWrapper.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2004-08-02 16:54:00 $
 *
 *  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 _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_
#include "ZConnectionWrapper.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif

using namespace connectivity;
//------------------------------------------------------------------------------
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
// --------------------------------------------------------------------------------
OConnectionWeakWrapper::OConnectionWeakWrapper(Reference< XAggregation >& _xConnection)
    : OConnectionWeakWrapper_BASE(m_aMutex)
{
    setDelegation(_xConnection,m_refCount);
    OSL_ENSURE(m_xConnection.is(),"OConnectionWeakWrapper: Connection must be valid!");
}
//-----------------------------------------------------------------------------
OConnectionWeakWrapper::~OConnectionWeakWrapper()
{
}
// XServiceInfo
// --------------------------------------------------------------------------------
IMPLEMENT_SERVICE_INFO(OConnectionWeakWrapper, "com.sun.star.sdbc.drivers.OConnectionWeakWrapper", "com.sun.star.sdbc.Connection")

// --------------------------------------------------------------------------------
Reference< XStatement > SAL_CALL OConnectionWeakWrapper::createStatement(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->createStatement();
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OConnectionWeakWrapper::prepareStatement( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->prepareStatement(sql);
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OConnectionWeakWrapper::prepareCall( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->prepareCall(sql);
}
// --------------------------------------------------------------------------------
::rtl::OUString SAL_CALL OConnectionWeakWrapper::nativeSQL( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->nativeSQL(sql);
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::setAutoCommit( sal_Bool autoCommit ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->setAutoCommit(autoCommit);
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL OConnectionWeakWrapper::getAutoCommit(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->getAutoCommit();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::commit(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->commit();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::rollback(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->rollback();
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL OConnectionWeakWrapper::isClosed(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );

    return m_xConnection->isClosed();
}
// --------------------------------------------------------------------------------
Reference< XDatabaseMetaData > SAL_CALL OConnectionWeakWrapper::getMetaData(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->getMetaData();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::setReadOnly( sal_Bool readOnly ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->setReadOnly(readOnly);
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL OConnectionWeakWrapper::isReadOnly(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->isReadOnly();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::setCatalog( const ::rtl::OUString& catalog ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->setCatalog(catalog);
}
// --------------------------------------------------------------------------------
::rtl::OUString SAL_CALL OConnectionWeakWrapper::getCatalog(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->getCatalog();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::setTransactionIsolation( sal_Int32 level ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->setTransactionIsolation(level);
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL OConnectionWeakWrapper::getTransactionIsolation(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->getTransactionIsolation();
}
// --------------------------------------------------------------------------------
Reference< ::com::sun::star::container::XNameAccess > SAL_CALL OConnectionWeakWrapper::getTypeMap(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->getTypeMap();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::setTypeMap( const Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->setTypeMap(typeMap);
}
// --------------------------------------------------------------------------------
// XCloseable
void SAL_CALL OConnectionWeakWrapper::close(  ) throw(SQLException, RuntimeException)
{
    {
        ::osl::MutexGuard aGuard( m_aMutex );
        checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    }
    dispose();
}
//------------------------------------------------------------------------------
void OConnectionWeakWrapper::disposing()
{
    ::osl::MutexGuard aGuard(m_aMutex);

    OConnectionWeakWrapper_BASE::disposing();
    OConnectionWrapper::disposing();
}
// -----------------------------------------------------------------------------
// com::sun::star::lang::XUnoTunnel
IMPLEMENT_FORWARD_XINTERFACE2(OConnectionWeakWrapper,OConnectionWeakWrapper_BASE,OConnectionWrapper)
IMPLEMENT_FORWARD_XTYPEPROVIDER2(OConnectionWeakWrapper,OConnectionWeakWrapper_BASE,OConnectionWrapper)

<commit_msg>INTEGRATION: CWS dba22 (1.6.44); FILE MERGED 2004/12/16 09:03:38 oj 1.6.44.1: #i39123# some clean ups<commit_after>/*************************************************************************
 *
 *  $RCSfile: ZConnectionWrapper.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: kz $ $Date: 2005-01-21 16:38: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 _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_
#include "ZConnectionWrapper.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_COLUMNVALUE_HPP_
#include <com/sun/star/sdbc/ColumnValue.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _CPPUHELPER_TYPEPROVIDER_HXX_
#include <cppuhelper/typeprovider.hxx>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif

using namespace connectivity;
//------------------------------------------------------------------------------
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
// --------------------------------------------------------------------------------
OConnectionWeakWrapper::OConnectionWeakWrapper(Reference< XAggregation >& _xConnection)
    : OConnectionWeakWrapper_BASE(m_aMutex)
{
    setDelegation(_xConnection,m_refCount);
    OSL_ENSURE(m_xConnection.is(),"OConnectionWeakWrapper: Connection must be valid!");
}
//-----------------------------------------------------------------------------
OConnectionWeakWrapper::~OConnectionWeakWrapper()
{
    if ( !OConnectionWeakWrapper_BASE::rBHelper.bDisposed )
    {
        osl_incrementInterlockedCount( &m_refCount );
        dispose();
    }
}
// XServiceInfo
// --------------------------------------------------------------------------------
IMPLEMENT_SERVICE_INFO(OConnectionWeakWrapper, "com.sun.star.sdbc.drivers.OConnectionWeakWrapper", "com.sun.star.sdbc.Connection")

// --------------------------------------------------------------------------------
Reference< XStatement > SAL_CALL OConnectionWeakWrapper::createStatement(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->createStatement();
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OConnectionWeakWrapper::prepareStatement( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->prepareStatement(sql);
}
// --------------------------------------------------------------------------------
Reference< XPreparedStatement > SAL_CALL OConnectionWeakWrapper::prepareCall( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->prepareCall(sql);
}
// --------------------------------------------------------------------------------
::rtl::OUString SAL_CALL OConnectionWeakWrapper::nativeSQL( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->nativeSQL(sql);
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::setAutoCommit( sal_Bool autoCommit ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->setAutoCommit(autoCommit);
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL OConnectionWeakWrapper::getAutoCommit(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->getAutoCommit();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::commit(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->commit();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::rollback(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->rollback();
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL OConnectionWeakWrapper::isClosed(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );

    return m_xConnection->isClosed();
}
// --------------------------------------------------------------------------------
Reference< XDatabaseMetaData > SAL_CALL OConnectionWeakWrapper::getMetaData(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->getMetaData();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::setReadOnly( sal_Bool readOnly ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->setReadOnly(readOnly);
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL OConnectionWeakWrapper::isReadOnly(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->isReadOnly();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::setCatalog( const ::rtl::OUString& catalog ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->setCatalog(catalog);
}
// --------------------------------------------------------------------------------
::rtl::OUString SAL_CALL OConnectionWeakWrapper::getCatalog(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->getCatalog();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::setTransactionIsolation( sal_Int32 level ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->setTransactionIsolation(level);
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL OConnectionWeakWrapper::getTransactionIsolation(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->getTransactionIsolation();
}
// --------------------------------------------------------------------------------
Reference< ::com::sun::star::container::XNameAccess > SAL_CALL OConnectionWeakWrapper::getTypeMap(  ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    return m_xConnection->getTypeMap();
}
// --------------------------------------------------------------------------------
void SAL_CALL OConnectionWeakWrapper::setTypeMap( const Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard( m_aMutex );
    checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    m_xConnection->setTypeMap(typeMap);
}
// --------------------------------------------------------------------------------
// XCloseable
void SAL_CALL OConnectionWeakWrapper::close(  ) throw(SQLException, RuntimeException)
{
    {
        ::osl::MutexGuard aGuard( m_aMutex );
        checkDisposed(OConnectionWeakWrapper_BASE::rBHelper.bDisposed);

    }
    dispose();
}
//------------------------------------------------------------------------------
void OConnectionWeakWrapper::disposing()
{
    ::osl::MutexGuard aGuard(m_aMutex);

    OConnectionWeakWrapper_BASE::disposing();
    OConnectionWrapper::disposing();
}
// -----------------------------------------------------------------------------
// com::sun::star::lang::XUnoTunnel
#ifdef N_DEBUG
IMPLEMENT_FORWARD_XINTERFACE2(OConnectionWeakWrapper,OConnectionWeakWrapper_BASE,OConnectionWrapper)
#else
IMPLEMENT_FORWARD_REFCOUNT( OConnectionWeakWrapper, OConnectionWeakWrapper_BASE ) \
::com::sun::star::uno::Any SAL_CALL OConnectionWeakWrapper::queryInterface( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException) \
{ \
    ::com::sun::star::uno::Any aReturn = OConnectionWeakWrapper_BASE::queryInterface( _rType ); \
    if ( !aReturn.hasValue() ) \
        aReturn = OConnectionWrapper::queryInterface( _rType ); \
    return aReturn; \
}
#endif
IMPLEMENT_FORWARD_XTYPEPROVIDER2(OConnectionWeakWrapper,OConnectionWeakWrapper_BASE,OConnectionWrapper)

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: accesslog.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2005-09-23 11:41:13 $
 *
 *  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 CONNECTIVITY_HSQLDB_ACCESSLOG_HXX
#define CONNECTIVITY_HSQLDB_ACCESSLOG_HXX

#ifdef HSQLDB_DBG

#include <stdio.h>
#include <jni.h>

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif

namespace connectivity { namespace hsqldb
{
    class LogFile
    {
    private:
        ::rtl::OUString     m_sFileName;

    public:
        LogFile( JNIEnv* env, jstring streamName, const sal_Char* _pAsciiSuffix );

    public:
                void    writeString( const sal_Char* _pString, bool _bEndLine = true );
                void    create() { getLogFile(); }
        virtual void    close();

    protected:
        FILE*&  getLogFile();
    };

    class OperationLogFile : public LogFile
    {
    public:
        OperationLogFile( JNIEnv* env, jstring streamName, const sal_Char* _pAsciiSuffix )
            :LogFile( env, streamName, ( ::rtl::OString( _pAsciiSuffix ) += ".op" ).getStr() )
        {
        }

        void logOperation( const sal_Char* _pOp )
        {
            writeString( _pOp, true );
        }

        void logOperation( const sal_Char* _pOp, jlong _nLongArg )
        {
            ::rtl::OString sLine( _pOp );
            sLine += "( ";
            sLine += ::rtl::OString::valueOf( _nLongArg );
            sLine += " )";
            writeString( sLine.getStr(), true );
        }

        void logReturn( jlong _nRetVal )
        {
            ::rtl::OString sLine( " -> " );
            sLine += ::rtl::OString::valueOf( _nRetVal );
            writeString( sLine.getStr(), true );
        }

        void logReturn( jint _nRetVal )
        {
            ::rtl::OString sLine( " -> " );
            sLine += ::rtl::OString::valueOf( _nRetVal );
            writeString( sLine.getStr(), true );
        }

        virtual void close()
        {
            writeString( "-------------------------------", true );
            writeString( "", true );
            LogFile::close();
        }
    };

    class DataLogFile : public LogFile
    {
    public:
        DataLogFile( JNIEnv* env, jstring streamName, const sal_Char* _pAsciiSuffix )
            :LogFile( env, streamName, _pAsciiSuffix )
        {
        }

        void write( jint value )
        {
            fputc( value, getLogFile() );
            fflush( getLogFile() );
        }

        void write( const sal_Int8* buffer, sal_Int32 bytesRead )
        {
            fwrite( buffer, sizeof(sal_Int8), bytesRead, getLogFile() );
            fflush( getLogFile() );
        }

        sal_Int64 seek( sal_Int64 pos )
        {
            FILE* pFile = getLogFile();
            fseek( pFile, 0, SEEK_END );
            if ( ftell( pFile ) < pos )
            {
                sal_Int8 filler( 0 );
                while ( ftell( pFile ) < pos )
                    fwrite( &filler, sizeof( sal_Int8 ), 1, pFile );
                fflush( pFile );
            }
            fseek( pFile, pos, SEEK_SET );
            return ftell( pFile );
        }

        sal_Int64 tell()
        {
            return ftell( getLogFile() );
        }
    };

} }
#endif

#endif // CONNECTIVITY_HSQLDB_ACCESSLOG_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.4.366); FILE MERGED 2008/04/01 15:08:50 thb 1.4.366.2: #i85898# Stripping all external header guards 2008/03/28 15:23:40 rt 1.4.366.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: accesslog.hxx,v $
 * $Revision: 1.5 $
 *
 * 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 CONNECTIVITY_HSQLDB_ACCESSLOG_HXX
#define CONNECTIVITY_HSQLDB_ACCESSLOG_HXX

#ifdef HSQLDB_DBG

#include <stdio.h>
#include <jni.h>
#include <rtl/ustring.hxx>
#include <rtl/string.hxx>

namespace connectivity { namespace hsqldb
{
    class LogFile
    {
    private:
        ::rtl::OUString     m_sFileName;

    public:
        LogFile( JNIEnv* env, jstring streamName, const sal_Char* _pAsciiSuffix );

    public:
                void    writeString( const sal_Char* _pString, bool _bEndLine = true );
                void    create() { getLogFile(); }
        virtual void    close();

    protected:
        FILE*&  getLogFile();
    };

    class OperationLogFile : public LogFile
    {
    public:
        OperationLogFile( JNIEnv* env, jstring streamName, const sal_Char* _pAsciiSuffix )
            :LogFile( env, streamName, ( ::rtl::OString( _pAsciiSuffix ) += ".op" ).getStr() )
        {
        }

        void logOperation( const sal_Char* _pOp )
        {
            writeString( _pOp, true );
        }

        void logOperation( const sal_Char* _pOp, jlong _nLongArg )
        {
            ::rtl::OString sLine( _pOp );
            sLine += "( ";
            sLine += ::rtl::OString::valueOf( _nLongArg );
            sLine += " )";
            writeString( sLine.getStr(), true );
        }

        void logReturn( jlong _nRetVal )
        {
            ::rtl::OString sLine( " -> " );
            sLine += ::rtl::OString::valueOf( _nRetVal );
            writeString( sLine.getStr(), true );
        }

        void logReturn( jint _nRetVal )
        {
            ::rtl::OString sLine( " -> " );
            sLine += ::rtl::OString::valueOf( _nRetVal );
            writeString( sLine.getStr(), true );
        }

        virtual void close()
        {
            writeString( "-------------------------------", true );
            writeString( "", true );
            LogFile::close();
        }
    };

    class DataLogFile : public LogFile
    {
    public:
        DataLogFile( JNIEnv* env, jstring streamName, const sal_Char* _pAsciiSuffix )
            :LogFile( env, streamName, _pAsciiSuffix )
        {
        }

        void write( jint value )
        {
            fputc( value, getLogFile() );
            fflush( getLogFile() );
        }

        void write( const sal_Int8* buffer, sal_Int32 bytesRead )
        {
            fwrite( buffer, sizeof(sal_Int8), bytesRead, getLogFile() );
            fflush( getLogFile() );
        }

        sal_Int64 seek( sal_Int64 pos )
        {
            FILE* pFile = getLogFile();
            fseek( pFile, 0, SEEK_END );
            if ( ftell( pFile ) < pos )
            {
                sal_Int8 filler( 0 );
                while ( ftell( pFile ) < pos )
                    fwrite( &filler, sizeof( sal_Int8 ), 1, pFile );
                fflush( pFile );
            }
            fseek( pFile, pos, SEEK_SET );
            return ftell( pFile );
        }

        sal_Int64 tell()
        {
            return ftell( getLogFile() );
        }
    };

} }
#endif

#endif // CONNECTIVITY_HSQLDB_ACCESSLOG_HXX
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/android/content_startup_flags.h"

#include "base/android/build_info.h"
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/sys_info.h"
#include "cc/base/switches.h"
#include "cc/trees/layer_tree_settings.h"
#include "content/public/browser/android/compositor.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_switches.h"
#include "gpu/command_buffer/service/gpu_switches.h"
#include "ui/base/ui_base_switches.h"
#include "ui/native_theme/native_theme_switches.h"

namespace content {

void SetContentCommandLineFlags(bool single_process,
                                const std::string& plugin_descriptor) {
  // May be called multiple times, to cover all possible program entry points.
  static bool already_initialized = false;
  if (already_initialized)
    return;
  already_initialized = true;

  base::CommandLine* parsed_command_line =
      base::CommandLine::ForCurrentProcess();

  int command_line_renderer_limit = -1;
  if (parsed_command_line->HasSwitch(switches::kRendererProcessLimit)) {
    std::string limit = parsed_command_line->GetSwitchValueASCII(
        switches::kRendererProcessLimit);
    int value;
    if (base::StringToInt(limit, &value)) {
      command_line_renderer_limit = std::max(0, value);
    }
  }

  if (command_line_renderer_limit > 0) {
    int limit = std::min(command_line_renderer_limit,
                         static_cast<int>(kMaxRendererProcessCount));
    RenderProcessHost::SetMaxRendererProcessCount(limit);
  }

  if (single_process || command_line_renderer_limit == 0) {
    // Need to ensure the command line flag is consistent as a lot of chrome
    // internal code checks this directly, but it wouldn't normally get set when
    // we are implementing an embedded WebView.
    parsed_command_line->AppendSwitch(switches::kSingleProcess);
  }

  parsed_command_line->AppendSwitch(cc::switches::kEnableBeginFrameScheduling);

  parsed_command_line->AppendSwitch(switches::kEnablePinch);
  parsed_command_line->AppendSwitch(switches::kEnableOverlayFullscreenVideo);
  parsed_command_line->AppendSwitch(switches::kEnableOverlayScrollbar);
  parsed_command_line->AppendSwitch(switches::kValidateInputEventStream);

  // There is no software fallback on Android, so don't limit GPU crashes.
  parsed_command_line->AppendSwitch(switches::kDisableGpuProcessCrashLimit);

  // On legacy low-memory devices the behavior has not been studied with regard
  // to having an extra process with similar priority as the foreground renderer
  // and given that the system will often be looking for a process to be killed
  // on such systems.
  if (base::SysInfo::IsLowEndDevice())
    parsed_command_line->AppendSwitch(switches::kInProcessGPU);

  parsed_command_line->AppendSwitch(switches::kEnableViewportMeta);
  parsed_command_line->AppendSwitch(
      switches::kMainFrameResizesAreOrientationChanges);

  // Disable anti-aliasing.
  parsed_command_line->AppendSwitch(
      cc::switches::kDisableCompositedAntialiasing);

  parsed_command_line->AppendSwitch(switches::kUIPrioritizeInGpuProcess);

  parsed_command_line->AppendSwitch(switches::kEnableDelegatedRenderer);

  if (!plugin_descriptor.empty()) {
    parsed_command_line->AppendSwitchNative(
      switches::kRegisterPepperPlugins, plugin_descriptor);
  }

  // Disable profiler timing by default.
  if (!parsed_command_line->HasSwitch(switches::kProfilerTiming)) {
    parsed_command_line->AppendSwitchASCII(
        switches::kProfilerTiming, switches::kProfilerTimingDisabledValue);
  }

  cc::LayerSettings layer_settings;
  if (parsed_command_line->HasSwitch(
          switches::kEnableAndroidCompositorAnimationTimelines))
    layer_settings.use_compositor_animation_timelines = true;
  Compositor::SetLayerSettings(layer_settings);
}

}  // namespace content
<commit_msg>[Android] Conditionally enable M text selection features<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/android/content_startup_flags.h"

#include "base/android/build_info.h"
#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/sys_info.h"
#include "cc/base/switches.h"
#include "cc/trees/layer_tree_settings.h"
#include "content/public/browser/android/compositor.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_constants.h"
#include "content/public/common/content_switches.h"
#include "gpu/command_buffer/service/gpu_switches.h"
#include "ui/base/ui_base_switches.h"
#include "ui/native_theme/native_theme_switches.h"

namespace content {

void SetContentCommandLineFlags(bool single_process,
                                const std::string& plugin_descriptor) {
  // May be called multiple times, to cover all possible program entry points.
  static bool already_initialized = false;
  if (already_initialized)
    return;
  already_initialized = true;

  base::CommandLine* parsed_command_line =
      base::CommandLine::ForCurrentProcess();

  int command_line_renderer_limit = -1;
  if (parsed_command_line->HasSwitch(switches::kRendererProcessLimit)) {
    std::string limit = parsed_command_line->GetSwitchValueASCII(
        switches::kRendererProcessLimit);
    int value;
    if (base::StringToInt(limit, &value)) {
      command_line_renderer_limit = std::max(0, value);
    }
  }

  if (command_line_renderer_limit > 0) {
    int limit = std::min(command_line_renderer_limit,
                         static_cast<int>(kMaxRendererProcessCount));
    RenderProcessHost::SetMaxRendererProcessCount(limit);
  }

  if (single_process || command_line_renderer_limit == 0) {
    // Need to ensure the command line flag is consistent as a lot of chrome
    // internal code checks this directly, but it wouldn't normally get set when
    // we are implementing an embedded WebView.
    parsed_command_line->AppendSwitch(switches::kSingleProcess);
  }

  parsed_command_line->AppendSwitch(cc::switches::kEnableBeginFrameScheduling);

  parsed_command_line->AppendSwitch(switches::kEnablePinch);
  parsed_command_line->AppendSwitch(switches::kEnableOverlayFullscreenVideo);
  parsed_command_line->AppendSwitch(switches::kEnableOverlayScrollbar);
  parsed_command_line->AppendSwitch(switches::kValidateInputEventStream);

  // TODO(jdduke): Use the proper SDK version when available, crbug.com/466749.
  if (base::android::BuildInfo::GetInstance()->sdk_int() >
      base::android::SDK_VERSION_LOLLIPOP_MR1) {
    parsed_command_line->AppendSwitch(switches::kEnableLongpressDragSelection);
    parsed_command_line->AppendSwitchASCII(
        switches::kTouchTextSelectionStrategy, "direction");
  }

  // There is no software fallback on Android, so don't limit GPU crashes.
  parsed_command_line->AppendSwitch(switches::kDisableGpuProcessCrashLimit);

  // On legacy low-memory devices the behavior has not been studied with regard
  // to having an extra process with similar priority as the foreground renderer
  // and given that the system will often be looking for a process to be killed
  // on such systems.
  if (base::SysInfo::IsLowEndDevice())
    parsed_command_line->AppendSwitch(switches::kInProcessGPU);

  parsed_command_line->AppendSwitch(switches::kEnableViewportMeta);
  parsed_command_line->AppendSwitch(
      switches::kMainFrameResizesAreOrientationChanges);

  // Disable anti-aliasing.
  parsed_command_line->AppendSwitch(
      cc::switches::kDisableCompositedAntialiasing);

  parsed_command_line->AppendSwitch(switches::kUIPrioritizeInGpuProcess);

  parsed_command_line->AppendSwitch(switches::kEnableDelegatedRenderer);

  if (!plugin_descriptor.empty()) {
    parsed_command_line->AppendSwitchNative(
      switches::kRegisterPepperPlugins, plugin_descriptor);
  }

  // Disable profiler timing by default.
  if (!parsed_command_line->HasSwitch(switches::kProfilerTiming)) {
    parsed_command_line->AppendSwitchASCII(
        switches::kProfilerTiming, switches::kProfilerTimingDisabledValue);
  }

  cc::LayerSettings layer_settings;
  if (parsed_command_line->HasSwitch(
          switches::kEnableAndroidCompositorAnimationTimelines))
    layer_settings.use_compositor_animation_timelines = true;
  Compositor::SetLayerSettings(layer_settings);
}

}  // namespace content
<|endoftext|>


<commit_before>/**
 * \file
 * \brief ThreadControlBlock class header
 *
 * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2015-01-22
 */

#ifndef INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
#define INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_

#include "distortos/scheduler/RoundRobinQuantum.hpp"
#include "distortos/scheduler/ThreadControlBlockList-types.hpp"
#include "distortos/scheduler/MutexControlBlockList.hpp"

#include "distortos/architecture/Stack.hpp"

#include "distortos/SchedulingPolicy.hpp"

#include <functional>

namespace distortos
{

namespace scheduler
{

class ThreadControlBlockList;

/// ThreadControlBlock class is a simple description of a Thread
class ThreadControlBlock
{
public:

	/// state of the thread
	enum class State : uint8_t
	{
		/// state in which thread is created, before being added to Scheduler
		New,
		/// thread is runnable
		Runnable,
		/// thread is sleeping
		Sleeping,
		/// thread is blocked on Semaphore
		BlockedOnSemaphore,
		/// thread is suspended
		Suspended,
		/// thread is terminated
		Terminated,
		/// thread is blocked on Mutex
		BlockedOnMutex,
		/// thread is blocked on ConditionVariable
		BlockedOnConditionVariable,
	};

	/// reason of thread unblocking
	enum class UnblockReason : uint8_t
	{
		/// explicit request to unblock the thread - normal unblock
		UnblockRequest,
		/// timeout - unblock via software timer
		Timeout,
	};

	/// type of object used as storage for ThreadControlBlockList elements - 3 pointers
	using Link = std::array<std::aligned_storage<sizeof(void*), alignof(void*)>::type, 3>;

	/**
	 * \brief ThreadControlBlock constructor.
	 *
	 * \param [in] buffer is a pointer to stack's buffer
	 * \param [in] size is the size of stack's buffer, bytes
	 * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
	 * \param [in] schedulingPolicy is the scheduling policy of the thread
	 */

	ThreadControlBlock(void* buffer, size_t size, uint8_t priority, SchedulingPolicy schedulingPolicy);

	/**
	 * \return effective priority of ThreadControlBlock
	 */

	uint8_t getEffectivePriority() const
	{
		return std::max(priority_, boostedPriority_);
	}

	/**
	 * \return iterator to the element on the list, valid only when list_ != nullptr
	 */

	ThreadControlBlockListIterator getIterator() const
	{
		return iterator_;
	}

	/**
	 * \return reference to internal storage for list link
	 */

	Link& getLink()
	{
		return link_;
	}

	/**
	 * \return const reference to internal storage for list link
	 */

	const Link& getLink() const
	{
		return link_;
	}

	/**
	 * \return pointer to list that has this object
	 */

	ThreadControlBlockList* getList() const
	{
		return list_;
	}

	/**
	 * \return reference to list of mutex control blocks with enabled priority protocol owned by this thread
	 */

	MutexControlBlockList& getOwnedProtocolMutexControlBlocksList()
	{
		return ownedProtocolMutexControlBlocksList_;
	}

	/**
	 * \return const reference to list of mutex control blocks with enabled priority protocol owned by this thread
	 */

	const MutexControlBlockList& getOwnedProtocolMutexControlBlocksList() const
	{
		return ownedProtocolMutexControlBlocksList_;
	}

	/**
	 * \return priority of ThreadControlBlock
	 */

	uint8_t getPriority() const
	{
		return priority_;
	}

	/**
	 * \return reference to internal RoundRobinQuantum object
	 */

	RoundRobinQuantum& getRoundRobinQuantum()
	{
		return roundRobinQuantum_;
	}

	/**
	 * \return const reference to internal RoundRobinQuantum object
	 */

	const RoundRobinQuantum& getRoundRobinQuantum() const
	{
		return roundRobinQuantum_;
	}

	/**
	 * \return scheduling policy of the thread
	 */

	SchedulingPolicy getSchedulingPolicy() const
	{
		return schedulingPolicy_;
	}

	/**
	 * \return reference to internal Stack object
	 */

	architecture::Stack& getStack()
	{
		return stack_;
	}

	/**
	 * \return const reference to internal Stack object
	 */

	const architecture::Stack& getStack() const
	{
		return stack_;
	}

	/**
	 * \return current state of object
	 */

	State getState() const
	{
		return state_;
	}

	/**
	 * \brief Sets the iterator to the element on the list.
	 *
	 * \param [in] iterator is an iterator to the element on the list
	 */

	void setIterator(const ThreadControlBlockListIterator iterator)
	{
		iterator_ = iterator;
	}

	/**
	 * \brief Sets the list that has this object.
	 *
	 * \param [in] list is a pointer to list that has this object
	 */

	void setList(ThreadControlBlockList* const list)
	{
		list_ = list;
	}

	/**
	 * \brief Changes priority of thread.
	 *
	 * If the priority really changes, the position in the thread list is adjusted and context switch may be requested.
	 *
	 * \param [in] priority is the new priority of thread
	 * \param [in] alwaysBehind selects the method of ordering when lowering the priority
	 * - false - the thread is moved to the head of the group of threads with the new priority (default),
	 * - true - the thread is moved to the tail of the group of threads with the new priority.
	 */

	void setPriority(uint8_t priority, bool alwaysBehind = {});

	/**
	 * \param [in] priorityInheritanceMutexControlBlock is a pointer to MutexControlBlock (with PriorityInheritance
	 * protocol) that blocks this thread
	 */

	void setPriorityInheritanceMutexControlBlock(const synchronization::MutexControlBlock* const
			priorityInheritanceMutexControlBlock)
	{
		priorityInheritanceMutexControlBlock_ = priorityInheritanceMutexControlBlock;
	}

	/**
	 * param [in] schedulingPolicy is the new scheduling policy of the thread
	 */

	void setSchedulingPolicy(SchedulingPolicy schedulingPolicy);

	/**
	 * \param [in] state is the new state of object
	 */

	void setState(const State state)
	{
		state_ = state;
	}

	/**
	 * \brief Termination hook function of thread
	 *
	 * \attention This function should be called only by Scheduler::remove().
	 */

	void terminationHook()
	{
		terminationHook_();
	}

	/**
	 * \brief Updates boosted priority of the thread.
	 *
	 * This function should be called after all operations involving this thread and a mutex with enabled priority
	 * protocol.
	 *
	 * \param [in] boostedPriority is the initial boosted priority, this should be effective priority of the thread that
	 * is about to be blocked on a mutex owned by this thread, default - 0
	 */

	void updateBoostedPriority(uint8_t boostedPriority = {});

protected:

	/**
	 * \brief ThreadControlBlock constructor.
	 *
	 * This constructor is meant for MainThreadControlBlock.
	 *
	 * \param [in] stack is an rvalue reference to stack of main()
	 * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
	 * \param [in] schedulingPolicy is the scheduling policy of the thread
	 */

	ThreadControlBlock(architecture::Stack&& stack, uint8_t priority, SchedulingPolicy schedulingPolicy);

	/**
	 * \brief ThreadControlBlock's destructor
	 *
	 * \note Polymorphic objects of ThreadControlBlock type must not be deleted via pointer/reference
	 */

	~ThreadControlBlock()
	{

	}

private:

	/**
	 * \brief Thread runner function - entry point of threads.
	 *
	 * After return from actual thread function, thread is terminated, so this function never returns.
	 *
	 * \param [in] threadControlBlock is a reference to ThreadControlBlock object that is being run
	 */

	static void threadRunner(ThreadControlBlock& threadControlBlock) __attribute__ ((noreturn));

	/**
	 * \brief Repositions the thread on the list it's currently on.
	 *
	 * This function should be called when thread's effective priority changes.
	 *
	 * \attention list_ must not be nullptr
	 *
	 * \param [in] loweringBefore selects the method of ordering when lowering the priority (it must be false when the
	 * priority is raised!):
	 * - true - the thread is moved to the head of the group of threads with the new priority, this is accomplished by
	 * temporarily boosting effective priority by 1,
	 * - false - the thread is moved to the tail of the group of threads with the new priority.
	 */

	void reposition(bool loweringBefore);

	/**
	 * \brief "Run" function of thread
	 *
	 * This should be overridden by derived classes.
	 */

	virtual void run() = 0;

	/**
	 * \brief Termination hook function of thread
	 *
	 * This function is called after run() completes.
	 *
	 * This should be overridden by derived classes.
	 */

	virtual void terminationHook_() = 0;

	/// internal stack object
	architecture::Stack stack_;

	/// storage for list link
	Link link_;

	/// list of mutex control blocks with enabled priority protocol owned by this thread
	MutexControlBlockList ownedProtocolMutexControlBlocksList_;

	/// pointer to MutexControlBlock (with PriorityInheritance protocol) that blocks this thread
	const synchronization::MutexControlBlock* priorityInheritanceMutexControlBlock_;

	/// pointer to list that has this object
	ThreadControlBlockList* list_;

	/// iterator to the element on the list, valid only when list_ != nullptr
	ThreadControlBlockListIterator iterator_;

	/// thread's priority, 0 - lowest, UINT8_MAX - highest
	uint8_t priority_;

	/// thread's boosted priority, 0 - no boosting
	uint8_t boostedPriority_;

	/// round-robin quantum
	RoundRobinQuantum roundRobinQuantum_;

	/// scheduling policy of the thread
	SchedulingPolicy schedulingPolicy_;

	/// current state of object
	State state_;

	/// reason of previous unblocking of the thread
	UnblockReason unblockReason_;
};

}	// namespace scheduler

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
<commit_msg>ThreadControlBlock: add ThreadControlBlock::getUnblockReason() and ThreadControlBlock::setUnblockReason() accessors<commit_after>/**
 * \file
 * \brief ThreadControlBlock class header
 *
 * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2015-01-22
 */

#ifndef INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
#define INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_

#include "distortos/scheduler/RoundRobinQuantum.hpp"
#include "distortos/scheduler/ThreadControlBlockList-types.hpp"
#include "distortos/scheduler/MutexControlBlockList.hpp"

#include "distortos/architecture/Stack.hpp"

#include "distortos/SchedulingPolicy.hpp"

#include <functional>

namespace distortos
{

namespace scheduler
{

class ThreadControlBlockList;

/// ThreadControlBlock class is a simple description of a Thread
class ThreadControlBlock
{
public:

	/// state of the thread
	enum class State : uint8_t
	{
		/// state in which thread is created, before being added to Scheduler
		New,
		/// thread is runnable
		Runnable,
		/// thread is sleeping
		Sleeping,
		/// thread is blocked on Semaphore
		BlockedOnSemaphore,
		/// thread is suspended
		Suspended,
		/// thread is terminated
		Terminated,
		/// thread is blocked on Mutex
		BlockedOnMutex,
		/// thread is blocked on ConditionVariable
		BlockedOnConditionVariable,
	};

	/// reason of thread unblocking
	enum class UnblockReason : uint8_t
	{
		/// explicit request to unblock the thread - normal unblock
		UnblockRequest,
		/// timeout - unblock via software timer
		Timeout,
	};

	/// type of object used as storage for ThreadControlBlockList elements - 3 pointers
	using Link = std::array<std::aligned_storage<sizeof(void*), alignof(void*)>::type, 3>;

	/**
	 * \brief ThreadControlBlock constructor.
	 *
	 * \param [in] buffer is a pointer to stack's buffer
	 * \param [in] size is the size of stack's buffer, bytes
	 * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
	 * \param [in] schedulingPolicy is the scheduling policy of the thread
	 */

	ThreadControlBlock(void* buffer, size_t size, uint8_t priority, SchedulingPolicy schedulingPolicy);

	/**
	 * \return effective priority of ThreadControlBlock
	 */

	uint8_t getEffectivePriority() const
	{
		return std::max(priority_, boostedPriority_);
	}

	/**
	 * \return iterator to the element on the list, valid only when list_ != nullptr
	 */

	ThreadControlBlockListIterator getIterator() const
	{
		return iterator_;
	}

	/**
	 * \return reference to internal storage for list link
	 */

	Link& getLink()
	{
		return link_;
	}

	/**
	 * \return const reference to internal storage for list link
	 */

	const Link& getLink() const
	{
		return link_;
	}

	/**
	 * \return pointer to list that has this object
	 */

	ThreadControlBlockList* getList() const
	{
		return list_;
	}

	/**
	 * \return reference to list of mutex control blocks with enabled priority protocol owned by this thread
	 */

	MutexControlBlockList& getOwnedProtocolMutexControlBlocksList()
	{
		return ownedProtocolMutexControlBlocksList_;
	}

	/**
	 * \return const reference to list of mutex control blocks with enabled priority protocol owned by this thread
	 */

	const MutexControlBlockList& getOwnedProtocolMutexControlBlocksList() const
	{
		return ownedProtocolMutexControlBlocksList_;
	}

	/**
	 * \return priority of ThreadControlBlock
	 */

	uint8_t getPriority() const
	{
		return priority_;
	}

	/**
	 * \return reference to internal RoundRobinQuantum object
	 */

	RoundRobinQuantum& getRoundRobinQuantum()
	{
		return roundRobinQuantum_;
	}

	/**
	 * \return const reference to internal RoundRobinQuantum object
	 */

	const RoundRobinQuantum& getRoundRobinQuantum() const
	{
		return roundRobinQuantum_;
	}

	/**
	 * \return scheduling policy of the thread
	 */

	SchedulingPolicy getSchedulingPolicy() const
	{
		return schedulingPolicy_;
	}

	/**
	 * \return reference to internal Stack object
	 */

	architecture::Stack& getStack()
	{
		return stack_;
	}

	/**
	 * \return const reference to internal Stack object
	 */

	const architecture::Stack& getStack() const
	{
		return stack_;
	}

	/**
	 * \return current state of object
	 */

	State getState() const
	{
		return state_;
	}

	/**
	 * \return reason of previous unblocking of the thread
	 */

	UnblockReason getUnblockReason() const
	{
		return unblockReason_;
	}

	/**
	 * \brief Sets the iterator to the element on the list.
	 *
	 * \param [in] iterator is an iterator to the element on the list
	 */

	void setIterator(const ThreadControlBlockListIterator iterator)
	{
		iterator_ = iterator;
	}

	/**
	 * \brief Sets the list that has this object.
	 *
	 * \param [in] list is a pointer to list that has this object
	 */

	void setList(ThreadControlBlockList* const list)
	{
		list_ = list;
	}

	/**
	 * \brief Changes priority of thread.
	 *
	 * If the priority really changes, the position in the thread list is adjusted and context switch may be requested.
	 *
	 * \param [in] priority is the new priority of thread
	 * \param [in] alwaysBehind selects the method of ordering when lowering the priority
	 * - false - the thread is moved to the head of the group of threads with the new priority (default),
	 * - true - the thread is moved to the tail of the group of threads with the new priority.
	 */

	void setPriority(uint8_t priority, bool alwaysBehind = {});

	/**
	 * \param [in] priorityInheritanceMutexControlBlock is a pointer to MutexControlBlock (with PriorityInheritance
	 * protocol) that blocks this thread
	 */

	void setPriorityInheritanceMutexControlBlock(const synchronization::MutexControlBlock* const
			priorityInheritanceMutexControlBlock)
	{
		priorityInheritanceMutexControlBlock_ = priorityInheritanceMutexControlBlock;
	}

	/**
	 * param [in] schedulingPolicy is the new scheduling policy of the thread
	 */

	void setSchedulingPolicy(SchedulingPolicy schedulingPolicy);

	/**
	 * \param [in] state is the new state of object
	 */

	void setState(const State state)
	{
		state_ = state;
	}

	/**
	 * \param [in] unblockReason is the new reason of unblocking of the thread
	 */

	void setUnblockReason(const UnblockReason unblockReason)
	{
		unblockReason_ = unblockReason;
	}

	/**
	 * \brief Termination hook function of thread
	 *
	 * \attention This function should be called only by Scheduler::remove().
	 */

	void terminationHook()
	{
		terminationHook_();
	}

	/**
	 * \brief Updates boosted priority of the thread.
	 *
	 * This function should be called after all operations involving this thread and a mutex with enabled priority
	 * protocol.
	 *
	 * \param [in] boostedPriority is the initial boosted priority, this should be effective priority of the thread that
	 * is about to be blocked on a mutex owned by this thread, default - 0
	 */

	void updateBoostedPriority(uint8_t boostedPriority = {});

protected:

	/**
	 * \brief ThreadControlBlock constructor.
	 *
	 * This constructor is meant for MainThreadControlBlock.
	 *
	 * \param [in] stack is an rvalue reference to stack of main()
	 * \param [in] priority is the thread's priority, 0 - lowest, UINT8_MAX - highest
	 * \param [in] schedulingPolicy is the scheduling policy of the thread
	 */

	ThreadControlBlock(architecture::Stack&& stack, uint8_t priority, SchedulingPolicy schedulingPolicy);

	/**
	 * \brief ThreadControlBlock's destructor
	 *
	 * \note Polymorphic objects of ThreadControlBlock type must not be deleted via pointer/reference
	 */

	~ThreadControlBlock()
	{

	}

private:

	/**
	 * \brief Thread runner function - entry point of threads.
	 *
	 * After return from actual thread function, thread is terminated, so this function never returns.
	 *
	 * \param [in] threadControlBlock is a reference to ThreadControlBlock object that is being run
	 */

	static void threadRunner(ThreadControlBlock& threadControlBlock) __attribute__ ((noreturn));

	/**
	 * \brief Repositions the thread on the list it's currently on.
	 *
	 * This function should be called when thread's effective priority changes.
	 *
	 * \attention list_ must not be nullptr
	 *
	 * \param [in] loweringBefore selects the method of ordering when lowering the priority (it must be false when the
	 * priority is raised!):
	 * - true - the thread is moved to the head of the group of threads with the new priority, this is accomplished by
	 * temporarily boosting effective priority by 1,
	 * - false - the thread is moved to the tail of the group of threads with the new priority.
	 */

	void reposition(bool loweringBefore);

	/**
	 * \brief "Run" function of thread
	 *
	 * This should be overridden by derived classes.
	 */

	virtual void run() = 0;

	/**
	 * \brief Termination hook function of thread
	 *
	 * This function is called after run() completes.
	 *
	 * This should be overridden by derived classes.
	 */

	virtual void terminationHook_() = 0;

	/// internal stack object
	architecture::Stack stack_;

	/// storage for list link
	Link link_;

	/// list of mutex control blocks with enabled priority protocol owned by this thread
	MutexControlBlockList ownedProtocolMutexControlBlocksList_;

	/// pointer to MutexControlBlock (with PriorityInheritance protocol) that blocks this thread
	const synchronization::MutexControlBlock* priorityInheritanceMutexControlBlock_;

	/// pointer to list that has this object
	ThreadControlBlockList* list_;

	/// iterator to the element on the list, valid only when list_ != nullptr
	ThreadControlBlockListIterator iterator_;

	/// thread's priority, 0 - lowest, UINT8_MAX - highest
	uint8_t priority_;

	/// thread's boosted priority, 0 - no boosting
	uint8_t boostedPriority_;

	/// round-robin quantum
	RoundRobinQuantum roundRobinQuantum_;

	/// scheduling policy of the thread
	SchedulingPolicy schedulingPolicy_;

	/// current state of object
	State state_;

	/// reason of previous unblocking of the thread
	UnblockReason unblockReason_;
};

}	// namespace scheduler

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_SCHEDULER_THREADCONTROLBLOCK_HPP_
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2012 Artem Pavlenko
 *
 * This library 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 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_JSON_GEOMETRY_GENERATOR_GRAMMAR_HPP
#define MAPNIK_JSON_GEOMETRY_GENERATOR_GRAMMAR_HPP

// mapnik
#include <mapnik/global.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/util/path_iterator.hpp>
#include <mapnik/util/container_adapter.hpp>
#include <mapnik/vertex.hpp>    // for CommandType::SEG_MOVETO

// boost
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>
#include <boost/math/special_functions/trunc.hpp> // for vc++ and android whose c++11 libs lack std::trunc

//stl
#include <tuple>

namespace mapnik { namespace json {

namespace karma = boost::spirit::karma;

namespace detail {

template <typename Geometry>
struct get_type
{
    using result_type = int;
    result_type operator() (Geometry const& geom) const
    {
        return static_cast<int>(geom.type());
    }
};

template <typename Geometry>
struct get_first
{
    using result_type = typename Geometry::value_type const;
    result_type operator() (Geometry const& geom) const
    {
        typename Geometry::value_type coord;
        geom.rewind(0);
        std::get<0>(coord) = geom.vertex(&std::get<1>(coord),&std::get<2>(coord));
        return coord;
    }
};

template <typename GeometryContainer>
struct multi_geometry_type
{
    using result_type = std::tuple<unsigned,bool> ;
    result_type operator() (GeometryContainer const& cont) const
    {
        unsigned type = 0u;
        bool collection = false;
        for (auto const& geom : cont)
        {
            if (type != 0u && geom.type() != type)
            {
                collection = true;
                break;
            }
            type = geom.type();
        }
        if (cont.size() > 1) type +=3;
        return std::tuple<unsigned,bool>(type, collection);
    }
};

template <typename GeometryContainer>
struct not_empty
{
    using result_type = bool;
    result_type operator() (GeometryContainer const& cont) const
    {
        for (auto const& geom : cont)
        {
            if (geom.size() > 0) return true;
        }
        return false;
    }
};

template <typename T>
struct json_coordinate_policy : karma::real_policies<T>
{
    using base_type = boost::spirit::karma::real_policies<T>;
    static int floatfield(T n) { return base_type::fmtflags::fixed; }

    static unsigned precision(T n)
    {
        if (n == 0.0) return 0;
        using namespace boost::spirit;
        return static_cast<unsigned>(14 - boost::math::trunc(log10(traits::get_absolute_value(n))));
    }

    template <typename OutputIterator>
    static bool dot(OutputIterator& sink, T n, unsigned precision)
    {
        if (n == 0) return true;
        return base_type::dot(sink, n, precision);
    }

    template <typename OutputIterator>
    static bool fraction_part(OutputIterator& sink, T n
                              , unsigned adjprec, unsigned precision)
    {
        if (n == 0) return true;
        return base_type::fraction_part(sink, n, adjprec, precision);
    }
};

}

template <typename OutputIterator, typename Geometry>
struct geometry_generator_grammar :
        karma::grammar<OutputIterator, Geometry const& ()>
{
    using geometry_type = Geometry;
    using coord_type = typename std::remove_pointer<typename geometry_type::value_type>::type;
    geometry_generator_grammar();
    karma::rule<OutputIterator, geometry_type const& ()> coordinates;
    karma::rule<OutputIterator, geometry_type const& ()> point;
    karma::rule<OutputIterator, geometry_type const& ()> linestring;
    karma::rule<OutputIterator, geometry_type const& ()> polygon;
    karma::rule<OutputIterator, geometry_type const& ()> coords;
    karma::rule<OutputIterator, karma::locals<unsigned>, geometry_type const& ()> coords2;
    karma::rule<OutputIterator, coord_type()> point_coord;
    karma::rule<OutputIterator, coord_type(unsigned& )> polygon_coord;
    boost::phoenix::function<detail::get_type<geometry_type> > _type;
    boost::phoenix::function<detail::get_first<geometry_type> > _first;
    karma::real_generator<double, detail::json_coordinate_policy<double> > coordinate;
};

template <typename OutputIterator, typename GeometryContainer>
struct multi_geometry_generator_grammar :
        karma::grammar<OutputIterator, karma::locals<std::tuple<unsigned,bool> >,
                       GeometryContainer const& ()>
{
    using geometry_type = typename std::remove_pointer<typename GeometryContainer::value_type>::type;
    multi_geometry_generator_grammar();
    karma::rule<OutputIterator, karma::locals<std::tuple<unsigned,bool> >,
                geometry_container const&()> start;
    karma::rule<OutputIterator, karma::locals<std::tuple<unsigned,bool> >,
                geometry_container const&()> geometry_collection;
    karma::rule<OutputIterator, karma::locals<std::tuple<unsigned,bool> >,
                geometry_container const&()> geometry;
    karma::rule<OutputIterator, karma::locals<unsigned>,
                geometry_type const&()> geometry2;
    karma::rule<OutputIterator, geometry_container const&()> coordinates;
    geometry_generator_grammar<OutputIterator, geometry_type>  path;
    // phoenix functions
    boost::phoenix::function<detail::multi_geometry_type<GeometryContainer> > multi_type_;
    boost::phoenix::function<detail::get_type<geometry_type> > type_;
    boost::phoenix::function<detail::not_empty<GeometryContainer> > not_empty_;
    karma::symbols<unsigned, char const*> geometry_types;
};

}}

#endif // MAPNIK_JSON_GEOMETRY_GENERATOR_GRAMMAR_HPP
<commit_msg>finish templating the json geometry generator on geometry container<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2012 Artem Pavlenko
 *
 * This library 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 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_JSON_GEOMETRY_GENERATOR_GRAMMAR_HPP
#define MAPNIK_JSON_GEOMETRY_GENERATOR_GRAMMAR_HPP

// mapnik
#include <mapnik/global.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/util/path_iterator.hpp>
#include <mapnik/util/container_adapter.hpp>
#include <mapnik/vertex.hpp>    // for CommandType::SEG_MOVETO

// boost
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>
#include <boost/math/special_functions/trunc.hpp> // for vc++ and android whose c++11 libs lack std::trunc

//stl
#include <tuple>

namespace mapnik { namespace json {

namespace karma = boost::spirit::karma;

namespace detail {

template <typename Geometry>
struct get_type
{
    using result_type = int;
    result_type operator() (Geometry const& geom) const
    {
        return static_cast<int>(geom.type());
    }
};

template <typename Geometry>
struct get_first
{
    using result_type = typename Geometry::value_type const;
    result_type operator() (Geometry const& geom) const
    {
        typename Geometry::value_type coord;
        geom.rewind(0);
        std::get<0>(coord) = geom.vertex(&std::get<1>(coord),&std::get<2>(coord));
        return coord;
    }
};

template <typename GeometryContainer>
struct multi_geometry_type
{
    using result_type = std::tuple<unsigned,bool> ;
    result_type operator() (GeometryContainer const& cont) const
    {
        unsigned type = 0u;
        bool collection = false;
        for (auto const& geom : cont)
        {
            if (type != 0u && geom.type() != type)
            {
                collection = true;
                break;
            }
            type = geom.type();
        }
        if (cont.size() > 1) type +=3;
        return std::tuple<unsigned,bool>(type, collection);
    }
};

template <typename GeometryContainer>
struct not_empty
{
    using result_type = bool;
    result_type operator() (GeometryContainer const& cont) const
    {
        for (auto const& geom : cont)
        {
            if (geom.size() > 0) return true;
        }
        return false;
    }
};

template <typename T>
struct json_coordinate_policy : karma::real_policies<T>
{
    using base_type = boost::spirit::karma::real_policies<T>;
    static int floatfield(T n) { return base_type::fmtflags::fixed; }

    static unsigned precision(T n)
    {
        if (n == 0.0) return 0;
        using namespace boost::spirit;
        return static_cast<unsigned>(14 - boost::math::trunc(log10(traits::get_absolute_value(n))));
    }

    template <typename OutputIterator>
    static bool dot(OutputIterator& sink, T n, unsigned precision)
    {
        if (n == 0) return true;
        return base_type::dot(sink, n, precision);
    }

    template <typename OutputIterator>
    static bool fraction_part(OutputIterator& sink, T n
                              , unsigned adjprec, unsigned precision)
    {
        if (n == 0) return true;
        return base_type::fraction_part(sink, n, adjprec, precision);
    }
};

}

template <typename OutputIterator, typename Geometry>
struct geometry_generator_grammar :
        karma::grammar<OutputIterator, Geometry const& ()>
{
    using geometry_type = Geometry;
    using coord_type = typename std::remove_pointer<typename geometry_type::value_type>::type;
    geometry_generator_grammar();
    karma::rule<OutputIterator, geometry_type const& ()> coordinates;
    karma::rule<OutputIterator, geometry_type const& ()> point;
    karma::rule<OutputIterator, geometry_type const& ()> linestring;
    karma::rule<OutputIterator, geometry_type const& ()> polygon;
    karma::rule<OutputIterator, geometry_type const& ()> coords;
    karma::rule<OutputIterator, karma::locals<unsigned>, geometry_type const& ()> coords2;
    karma::rule<OutputIterator, coord_type()> point_coord;
    karma::rule<OutputIterator, coord_type(unsigned& )> polygon_coord;
    boost::phoenix::function<detail::get_type<geometry_type> > _type;
    boost::phoenix::function<detail::get_first<geometry_type> > _first;
    karma::real_generator<double, detail::json_coordinate_policy<double> > coordinate;
};

template <typename OutputIterator, typename GeometryContainer>
struct multi_geometry_generator_grammar :
        karma::grammar<OutputIterator, karma::locals<std::tuple<unsigned,bool> >,
                       GeometryContainer const& ()>
{
    using geometry_type = typename std::remove_pointer<typename GeometryContainer::value_type>::type;
    multi_geometry_generator_grammar();
    karma::rule<OutputIterator, karma::locals<std::tuple<unsigned,bool> >,
                GeometryContainer const&()> start;
    karma::rule<OutputIterator, karma::locals<std::tuple<unsigned,bool> >,
                GeometryContainer const&()> geometry_collection;
    karma::rule<OutputIterator, karma::locals<std::tuple<unsigned,bool> >,
                GeometryContainer const&()> geometry;
    karma::rule<OutputIterator, karma::locals<unsigned>,
                geometry_type const&()> geometry2;
    karma::rule<OutputIterator, GeometryContainer const&()> coordinates;
    geometry_generator_grammar<OutputIterator, geometry_type>  path;
    // phoenix functions
    boost::phoenix::function<detail::multi_geometry_type<GeometryContainer> > multi_type_;
    boost::phoenix::function<detail::get_type<geometry_type> > type_;
    boost::phoenix::function<detail::not_empty<GeometryContainer> > not_empty_;
    karma::symbols<unsigned, char const*> geometry_types;
};

}}

#endif // MAPNIK_JSON_GEOMETRY_GENERATOR_GRAMMAR_HPP
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// Copyright (c) 2015 RT Corporation
// All rights reserved.

// License: BSD

// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:

// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.

// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.

// * Neither the name of RT Corporation nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.

// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
#include <math.h>

#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

#include <sstream>

/**********************************************************************************************************
 *
 * Constants
 *
 **********************************************************************************************************/

namespace RtUsbImu
{
  class Consts
  {
    public:
      //IMU Data table constants
      enum{
        IMU_FIRMWARE = 6,
        IMU_TIMESTAMP = 7,
        IMU_ACC_X_L = 8,
        IMU_ACC_X_H = 9,
        IMU_ACC_Y_L = 10,
        IMU_ACC_Y_H = 11,
        IMU_ACC_Z_L = 12,
        IMU_ACC_Z_H = 13,
        IMU_TEMP_L = 14,
        IMU_TEMP_H = 15,
        IMU_GYRO_X_L = 16,
        IMU_GYRO_X_H = 17,
        IMU_GYRO_Y_L = 18,
        IMU_GYRO_Y_H = 19,
        IMU_GYRO_Z_L = 20,
        IMU_GYRO_Z_H = 21,
        IMU_MAG_X_L = 22,
        IMU_MAG_X_H = 23,
        IMU_MAG_Y_L = 24,
        IMU_MAG_Y_H = 25,
        IMU_MAG_Z_L = 26,
        IMU_MAG_Z_H = 27,
        IMU_DATA_SIZE = 28,
      };
      //Convertor
      const double CONVERTOR_RAW2G;
      const double CONVERTOR_RAW2DPS;
      double CONVERTOR_RAW2UT;
      double CONVERTOR_RAW2C_1;
      double CONVERTOR_RAW2C_2;
      const double CONVERTOR_G2A;
      const double CONVERTOR_D2R;
      const double CONVERTOR_UT2T;
      const double DEFAULT_LINEAR_ACCELERATION_STDDEV;
      const double DEFAULT_ANGULAR_VELOCITY_STDDEV;
      const double DEFAULT_MAGNETIC_FIELD_STDDEV;

      Consts()
      : CONVERTOR_RAW2G(2048)      // for linear_acceleration (raw data to [g])
      , CONVERTOR_RAW2DPS(16.4)    // for angular_velocity (raw data to [degree/s])
      , CONVERTOR_RAW2UT(0.3)      // for magnetic_field (raw data to [uT])
      , CONVERTOR_RAW2C_1(340)     // for temperature (raw data to celsius)
      , CONVERTOR_RAW2C_2(35)      // for temperature (raw data to celsius)
      , CONVERTOR_G2A(9.80665)     // for linear_acceleration (g to m/s^2)
      , CONVERTOR_D2R(M_PI/180.0)  // for angular_velocity (degree to radian)
      , CONVERTOR_UT2T(1000000)    // for magnetic_field (uT to Tesla)
      , DEFAULT_LINEAR_ACCELERATION_STDDEV(0.023145)    // Default of square root of the linear_acceleration_covariance diagonal elements in m/s^2.
      , DEFAULT_ANGULAR_VELOCITY_STDDEV(0.0010621)      // Default of square root of the angular_velocity_covariance diagonal elements in rad/s.
      , DEFAULT_MAGNETIC_FIELD_STDDEV(0.00000080786)    // Default of square root of the magnetic_field_covariance diagonal elements in Tesla.
      {}

      ~Consts(){
      }

      //Method to adjust convertors to firmware version
      void ChangeConvertor(const int firmware_ver) {
        if(firmware_ver == 5) {
          CONVERTOR_RAW2UT = 0.3;
          CONVERTOR_RAW2C_1 = 340;
          CONVERTOR_RAW2C_2 = 35;
        }
        else if(firmware_ver >= 6) {
          CONVERTOR_RAW2UT = 0.15;
          CONVERTOR_RAW2C_1 = 333.87;
          CONVERTOR_RAW2C_2 = 21;
        }
      }
  };

/**********************************************************************************************************
 *
 * Serial port abstraction
 *
 **********************************************************************************************************/

  class SerialPort
  {
    private:
      std::string port_name; // ex) "/dev/ttyACM0"
      int port_fd;

    public:
      SerialPort(const char* port = "") : port_name(port), port_fd(-1){
      }

      ~SerialPort() {
        Close();
      }

      bool Open(const char* port) {
        port_name = port;
        return Open();
      }

      bool Open() {
        int fd = 0;

        if(port_fd > 0) {
          return true;
        }

        fd = open(port_name.c_str(), O_RDWR | O_NOCTTY);  //Open serial port
        if(fd < 0) {
          return false;  //Port open error
        }

        port_fd = fd;

        return (fd > 0);

      }

      void Close() {
        if(port_fd > 0) {
          close(port_fd);  //Close serial port
          port_fd = -1;
        }
      }

      int Read(unsigned char* buf, unsigned int buf_len) {
        if(port_fd < 0) {
          return -1;
        }

        unsigned int left_len = buf_len;
        unsigned char* p = buf;
        while(left_len > 0) {
          //Read device file and put the data into buf (max size is (buf_len) bytes)
          int size = read(port_fd, p, left_len);
          if(size < 0) {
            return -1;
          }
          p += size;
          left_len -= size;
        }

        return (buf_len - left_len);
      }

      int Write(unsigned char* data, unsigned int data_len) {
        if(port_fd < 0) {
          return -1;
        }

        return write(port_fd, data, data_len);
      }
  };

  /**************************************************************************
   *
   * IMU
   *
   **************************************************************************/

  //Class to store either raw integer imu data or converted physical quantity
  template <typename Type> class ImuData
  {
    public:
      int firmware_ver;
      int timestamp;
      Type ax, ay, az, gx, gy, gz, mx, my, mz, temperature;

      ImuData() {
        Reset();
      }

      ~ImuData(){
      }

      inline void Reset() {
        firmware_ver = 5;
        timestamp = -1;
        ax = ay = az = gx = gy = gz = mx = my = mz = temperature = 0;
      }
  };

  class SensorData
  {
    private:
      ImuData<signed short> imu_rawdata;
      ImuData<double> imu;
      Consts consts;

    public:
      SensorData() {
        Reset();
      }

      ~SensorData(){
      }

      void Reset() {
        imu_rawdata.Reset();
        imu.Reset();
      }

      void UpdateImuRaw(ImuData<signed short>& i) {
        imu_rawdata = i;
      }

      //Method to convert raw integer imu data to physical quantity
      void ConvertRawdata() {
        //Adjust convertors to firmware version
        consts.ChangeConvertor(imu_rawdata.firmware_ver);

        imu.firmware_ver = imu_rawdata.firmware_ver;
        imu.timestamp = imu_rawdata.timestamp;

        // Convert raw data to [g]
        imu.ax = imu_rawdata.ax/consts.CONVERTOR_RAW2G;
        imu.ay = imu_rawdata.ay/consts.CONVERTOR_RAW2G;
        imu.az = imu_rawdata.az/consts.CONVERTOR_RAW2G;

        // Convert raw data to [degree/s]
        imu.gx = imu_rawdata.gx/consts.CONVERTOR_RAW2DPS;
        imu.gy = imu_rawdata.gy/consts.CONVERTOR_RAW2DPS;
        imu.gz = imu_rawdata.gz/consts.CONVERTOR_RAW2DPS;

        // Convert raw data to [uT]
        imu.mx = imu_rawdata.mx*consts.CONVERTOR_RAW2UT;
        imu.my = imu_rawdata.my*consts.CONVERTOR_RAW2UT;
        imu.mz = imu_rawdata.mz*consts.CONVERTOR_RAW2UT;

        // Convert raw data to celsius
        imu.temperature = imu_rawdata.temperature/consts.CONVERTOR_RAW2C_1 + consts.CONVERTOR_RAW2C_2;
      }

      ImuData<double> OutputImuData() {
        return imu;
      }
  };
};
<commit_msg>Add serial port settings after port open()<commit_after>//------------------------------------------------------------------------------
// Copyright (c) 2015 RT Corporation
// All rights reserved.

// License: BSD

// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:

// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.

// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.

// * Neither the name of RT Corporation nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.

// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
#include <math.h>

#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>

#include <sstream>

/**********************************************************************************************************
 *
 * Constants
 *
 **********************************************************************************************************/

namespace RtUsbImu
{
  class Consts
  {
    public:
      //IMU Data table constants
      enum{
        IMU_FIRMWARE = 6,
        IMU_TIMESTAMP = 7,
        IMU_ACC_X_L = 8,
        IMU_ACC_X_H = 9,
        IMU_ACC_Y_L = 10,
        IMU_ACC_Y_H = 11,
        IMU_ACC_Z_L = 12,
        IMU_ACC_Z_H = 13,
        IMU_TEMP_L = 14,
        IMU_TEMP_H = 15,
        IMU_GYRO_X_L = 16,
        IMU_GYRO_X_H = 17,
        IMU_GYRO_Y_L = 18,
        IMU_GYRO_Y_H = 19,
        IMU_GYRO_Z_L = 20,
        IMU_GYRO_Z_H = 21,
        IMU_MAG_X_L = 22,
        IMU_MAG_X_H = 23,
        IMU_MAG_Y_L = 24,
        IMU_MAG_Y_H = 25,
        IMU_MAG_Z_L = 26,
        IMU_MAG_Z_H = 27,
        IMU_DATA_SIZE = 28,
      };
      //Convertor
      const double CONVERTOR_RAW2G;
      const double CONVERTOR_RAW2DPS;
      double CONVERTOR_RAW2UT;
      double CONVERTOR_RAW2C_1;
      double CONVERTOR_RAW2C_2;
      const double CONVERTOR_G2A;
      const double CONVERTOR_D2R;
      const double CONVERTOR_UT2T;
      const double DEFAULT_LINEAR_ACCELERATION_STDDEV;
      const double DEFAULT_ANGULAR_VELOCITY_STDDEV;
      const double DEFAULT_MAGNETIC_FIELD_STDDEV;

      Consts()
      : CONVERTOR_RAW2G(2048)      // for linear_acceleration (raw data to [g])
      , CONVERTOR_RAW2DPS(16.4)    // for angular_velocity (raw data to [degree/s])
      , CONVERTOR_RAW2UT(0.3)      // for magnetic_field (raw data to [uT])
      , CONVERTOR_RAW2C_1(340)     // for temperature (raw data to celsius)
      , CONVERTOR_RAW2C_2(35)      // for temperature (raw data to celsius)
      , CONVERTOR_G2A(9.80665)     // for linear_acceleration (g to m/s^2)
      , CONVERTOR_D2R(M_PI/180.0)  // for angular_velocity (degree to radian)
      , CONVERTOR_UT2T(1000000)    // for magnetic_field (uT to Tesla)
      , DEFAULT_LINEAR_ACCELERATION_STDDEV(0.023145)    // Default of square root of the linear_acceleration_covariance diagonal elements in m/s^2.
      , DEFAULT_ANGULAR_VELOCITY_STDDEV(0.0010621)      // Default of square root of the angular_velocity_covariance diagonal elements in rad/s.
      , DEFAULT_MAGNETIC_FIELD_STDDEV(0.00000080786)    // Default of square root of the magnetic_field_covariance diagonal elements in Tesla.
      {}

      ~Consts(){
      }

      //Method to adjust convertors to firmware version
      void ChangeConvertor(const int firmware_ver) {
        if(firmware_ver == 5) {
          CONVERTOR_RAW2UT = 0.3;
          CONVERTOR_RAW2C_1 = 340;
          CONVERTOR_RAW2C_2 = 35;
        }
        else if(firmware_ver >= 6) {
          CONVERTOR_RAW2UT = 0.15;
          CONVERTOR_RAW2C_1 = 333.87;
          CONVERTOR_RAW2C_2 = 21;
        }
      }
  };

/**********************************************************************************************************
 *
 * Serial port abstraction
 *
 **********************************************************************************************************/

  class SerialPort
  {
    private:
      std::string port_name; // ex) "/dev/ttyACM0"
      int port_fd;

    public:
      SerialPort(const char* port = "") : port_name(port), port_fd(-1){
      }

      ~SerialPort() {
        Close();
      }

      bool Open(const char* port) {
        port_name = port;
        return Open();
      }

      bool Open() {
        int fd = 0;

        if(port_fd > 0) {
          return true;
        }

        fd = open(port_name.c_str(), O_RDWR | O_NOCTTY);  //Open serial port
        if(fd < 0) {
          return false;  //Port open error
        }

        struct termios settings;
        settings.c_cflag += CREAD; //Enable receiving
        settings.c_cflag += CLOCAL;//Local line
        settings.c_cflag += CS8;   //DataBit : 8bit
        settings.c_cflag += 0;     //StopBit : 1bit
        settings.c_cflag += 0;     //Parity  : None

        cfsetispeed(&settings, B57600);
        cfmakeraw(&settings);

        tcsetattr(fd, TCSANOW, &settings);
        ioctl(fd, TCSETS, &settings);

        port_fd = fd;

        return (fd > 0);

      }

      void Close() {
        if(port_fd > 0) {
          close(port_fd);  //Close serial port
          port_fd = -1;
        }
      }

      int Read(unsigned char* buf, unsigned int buf_len) {
        if(port_fd < 0) {
          return -1;
        }

        unsigned int left_len = buf_len;
        unsigned char* p = buf;
        while(left_len > 0) {
          //Read device file and put the data into buf (max size is (buf_len) bytes)
          int size = read(port_fd, p, left_len);
          if(size < 0) {
            return -1;
          }
          p += size;
          left_len -= size;
        }

        return (buf_len - left_len);
      }

      int Write(unsigned char* data, unsigned int data_len) {
        if(port_fd < 0) {
          return -1;
        }

        return write(port_fd, data, data_len);
      }
  };

  /**************************************************************************
   *
   * IMU
   *
   **************************************************************************/

  //Class to store either raw integer imu data or converted physical quantity
  template <typename Type> class ImuData
  {
    public:
      int firmware_ver;
      int timestamp;
      Type ax, ay, az, gx, gy, gz, mx, my, mz, temperature;

      ImuData() {
        Reset();
      }

      ~ImuData(){
      }

      inline void Reset() {
        firmware_ver = 5;
        timestamp = -1;
        ax = ay = az = gx = gy = gz = mx = my = mz = temperature = 0;
      }
  };

  class SensorData
  {
    private:
      ImuData<signed short> imu_rawdata;
      ImuData<double> imu;
      Consts consts;

    public:
      SensorData() {
        Reset();
      }

      ~SensorData(){
      }

      void Reset() {
        imu_rawdata.Reset();
        imu.Reset();
      }

      void UpdateImuRaw(ImuData<signed short>& i) {
        imu_rawdata = i;
      }

      //Method to convert raw integer imu data to physical quantity
      void ConvertRawdata() {
        //Adjust convertors to firmware version
        consts.ChangeConvertor(imu_rawdata.firmware_ver);

        imu.firmware_ver = imu_rawdata.firmware_ver;
        imu.timestamp = imu_rawdata.timestamp;

        // Convert raw data to [g]
        imu.ax = imu_rawdata.ax/consts.CONVERTOR_RAW2G;
        imu.ay = imu_rawdata.ay/consts.CONVERTOR_RAW2G;
        imu.az = imu_rawdata.az/consts.CONVERTOR_RAW2G;

        // Convert raw data to [degree/s]
        imu.gx = imu_rawdata.gx/consts.CONVERTOR_RAW2DPS;
        imu.gy = imu_rawdata.gy/consts.CONVERTOR_RAW2DPS;
        imu.gz = imu_rawdata.gz/consts.CONVERTOR_RAW2DPS;

        // Convert raw data to [uT]
        imu.mx = imu_rawdata.mx*consts.CONVERTOR_RAW2UT;
        imu.my = imu_rawdata.my*consts.CONVERTOR_RAW2UT;
        imu.mz = imu_rawdata.mz*consts.CONVERTOR_RAW2UT;

        // Convert raw data to celsius
        imu.temperature = imu_rawdata.temperature/consts.CONVERTOR_RAW2C_1 + consts.CONVERTOR_RAW2C_2;
      }

      ImuData<double> OutputImuData() {
        return imu;
      }
  };
};
<|endoftext|>