<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: BUser.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 05:24:40 $
 *
 *  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_ADABAS_USER_HXX_
#include "adabas/BUser.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_GROUPS_HXX_
#include "adabas/BGroups.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _CONNECTIVITY_ADABAS_BCONNECTION_HXX_
#include "adabas/BConnection.hxx"
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include "connectivity/dbtools.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBCX_PRIVILEGE_HPP_
#include <com/sun/star/sdbcx/Privilege.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_PRIVILEGEOBJECT_HPP_
#include <com/sun/star/sdbcx/PrivilegeObject.hpp>
#endif

using namespace connectivity::adabas;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
// -------------------------------------------------------------------------
OAdabasUser::OAdabasUser(   OAdabasConnection* _pConnection) : connectivity::sdbcx::OUser(sal_True)
                ,m_pConnection(_pConnection)
{
    construct();
}
// -------------------------------------------------------------------------
OAdabasUser::OAdabasUser(   OAdabasConnection* _pConnection,
                const ::rtl::OUString& _Name
            ) : connectivity::sdbcx::OUser(_Name,sal_True)
                ,m_pConnection(_pConnection)
{
    construct();
}
// -------------------------------------------------------------------------
void OAdabasUser::refreshGroups()
{
    if(!m_pConnection)
        return;

    TStringVector aVector;
    aVector.reserve(7); // we don't know the excatly count of users but this should fit the normal need
    Reference< XStatement > xStmt = m_pConnection->createStatement(  );
    ::rtl::OUString aSql = ::rtl::OUString::createFromAscii("SELECT DISTINCT GROUPNAME FROM DOMAIN.USERS WHERE GROUPNAME IS NOT NULL AND GROUPNAME <> ' ' AND USERNAME = '");
    aSql += getName( );
    aSql += ::rtl::OUString::createFromAscii("'");

    Reference< XResultSet > xResult = xStmt->executeQuery(aSql);
    if(xResult.is())
    {
                Reference< XRow > xRow(xResult,UNO_QUERY);
        while(xResult->next())
            aVector.push_back(xRow->getString(1));
        ::comphelper::disposeComponent(xResult);
    }
    ::comphelper::disposeComponent(xStmt);

    if(m_pGroups)
        m_pGroups->reFill(aVector);
    else
        m_pGroups = new OGroups(*this,m_aMutex,aVector,m_pConnection,this);
}
// -------------------------------------------------------------------------
OUserExtend::OUserExtend(   OAdabasConnection* _pConnection) : OAdabasUser(_pConnection)
{
    construct();
}
// -------------------------------------------------------------------------
OUserExtend::OUserExtend(   OAdabasConnection* _pConnection,const ::rtl::OUString& _Name) : OAdabasUser(_pConnection,_Name)
{
    construct();
}
// -------------------------------------------------------------------------
typedef connectivity::sdbcx::OUser  OUser_TYPEDEF;
void OUserExtend::construct()
{

    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD),    PROPERTY_ID_PASSWORD,0,&m_Password,::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
}
// -----------------------------------------------------------------------------
cppu::IPropertyArrayHelper* OUserExtend::createArrayHelper() const
{
    Sequence< Property > aProps;
    describeProperties(aProps);
    return new cppu::OPropertyArrayHelper(aProps);
}
// -------------------------------------------------------------------------
cppu::IPropertyArrayHelper & OUserExtend::getInfoHelper()
{
    return *OUserExtend_PROP::getArrayHelper();
}
typedef connectivity::sdbcx::OUser_BASE OUser_BASE_RBHELPER;
// -----------------------------------------------------------------------------
sal_Int32 SAL_CALL OAdabasUser::getPrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OUser_BASE_RBHELPER::rBHelper.bDisposed);

    sal_Int32 nRights,nRightsWithGrant;
    findPrivilegesAndGrantPrivileges(objName,objType,nRights,nRightsWithGrant);
    return nRights;
}
// -----------------------------------------------------------------------------
void OAdabasUser::findPrivilegesAndGrantPrivileges(const ::rtl::OUString& objName, sal_Int32 objType,sal_Int32& nRights,sal_Int32& nRightsWithGrant) throw(SQLException, RuntimeException)
{
    nRightsWithGrant = nRights = 0;
    // first we need to create the sql stmt to select the privs
    Reference<XDatabaseMetaData> xMeta = m_pConnection->getMetaData();
    ::rtl::OUString sCatalog,sSchema,sTable;
    ::dbtools::qualifiedNameComponents(xMeta,objName,sCatalog,sSchema,sTable,::dbtools::eInDataManipulation);
    Reference<XStatement> xStmt = m_pConnection->createStatement();
    ::rtl::OUString sSql = ::rtl::OUString::createFromAscii("SELECT REFTABLENAME,PRIVILEGES FROM DOMAIN.USR_USES_TAB WHERE REFOBJTYPE <> 'SYSTEM' AND DEFUSERNAME = '");
    sSql += m_Name;
    sSql += ::rtl::OUString::createFromAscii("' AND REFTABLENAME = '");
    sSql += sTable;
    sSql += ::rtl::OUString::createFromAscii("'");
    if(xStmt.is())
    {
        Reference<XResultSet> xRes = xStmt->executeQuery(sSql);
        if(xRes.is())
        {
            Reference<XRow> xRow(xRes,UNO_QUERY);
            if(xRow.is() && xRes->next())
            {
                ::rtl::OUString sPrivs = xRow->getString(2);
                static const ::rtl::OUString sInsert    = ::rtl::OUString::createFromAscii("INS");
                static const ::rtl::OUString sDelete    = ::rtl::OUString::createFromAscii("DEL");
                static const ::rtl::OUString sUpdate    = ::rtl::OUString::createFromAscii("UPD");
                static const ::rtl::OUString sAlter     = ::rtl::OUString::createFromAscii("ALT");
                static const ::rtl::OUString sSelect    = ::rtl::OUString::createFromAscii("SEL");
                static const ::rtl::OUString sReference = ::rtl::OUString::createFromAscii("REF");
                static const ::rtl::OUString sGrant     = ::rtl::OUString::createFromAscii("+");

                sal_Int32 nIndex = -1;
                if(nIndex = sPrivs.indexOf(sInsert) != -1)
                {
                    nRights |= Privilege::INSERT;
                    if(sGrant == sPrivs.copy(nIndex+2,1))
                        nRightsWithGrant |= Privilege::INSERT;
                }
                if(nIndex = sPrivs.indexOf(sDelete) != -1)
                {
                    nRights |= Privilege::DELETE;
                    if(sGrant == sPrivs.copy(nIndex+2,1))
                        nRightsWithGrant |= Privilege::DELETE;
                }
                if(nIndex = sPrivs.indexOf(sUpdate) != -1)
                {
                    nRights |= Privilege::UPDATE;
                    if(sGrant == sPrivs.copy(nIndex+2,1))
                        nRightsWithGrant |= Privilege::UPDATE;
                }
                if(nIndex = sPrivs.indexOf(sAlter) != -1)
                {
                    nRights |= Privilege::ALTER;
                    if(sGrant == sPrivs.copy(nIndex+2,1))
                        nRightsWithGrant |= Privilege::ALTER;
                }
                if(nIndex = sPrivs.indexOf(sSelect) != -1)
                {
                    nRights |= Privilege::SELECT;
                    if(sGrant == sPrivs.copy(nIndex+2,1))
                        nRightsWithGrant |= Privilege::SELECT;
                }
                if(nIndex = sPrivs.indexOf(sReference) != -1)
                {
                    nRights |= Privilege::REFERENCE;
                    if(sGrant == sPrivs.copy(nIndex+2,1))
                        nRightsWithGrant |= Privilege::REFERENCE;
                }
            }
            ::comphelper::disposeComponent(xRes);
        }
        ::comphelper::disposeComponent(xStmt);
    }
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OAdabasUser::getGrantablePrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OUser_BASE_RBHELPER::rBHelper.bDisposed);

    sal_Int32 nRights,nRightsWithGrant;
    findPrivilegesAndGrantPrivileges(objName,objType,nRights,nRightsWithGrant);
    return nRightsWithGrant;
}
// -------------------------------------------------------------------------
void SAL_CALL OAdabasUser::grantPrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);

    ::rtl::OUString sPrivs = getPrivilegeString(objPrivileges);
    if(sPrivs.getLength())
    {
        ::rtl::OUString sGrant;
        sGrant += ::rtl::OUString::createFromAscii("GRANT ");
        sGrant += sPrivs;
        sGrant += ::rtl::OUString::createFromAscii(" ON ");
        Reference<XDatabaseMetaData> xMeta = m_pConnection->getMetaData();
        sGrant += ::dbtools::quoteTableName(xMeta,objName,::dbtools::eInDataManipulation);
        sGrant += ::rtl::OUString::createFromAscii(" TO ");
        sGrant += m_Name;

        Reference<XStatement> xStmt = m_pConnection->createStatement();
        if(xStmt.is())
            xStmt->execute(sGrant);
        ::comphelper::disposeComponent(xStmt);
    }
}
// -------------------------------------------------------------------------
void SAL_CALL OAdabasUser::revokePrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OUser_BASE_RBHELPER::rBHelper.bDisposed);
    ::rtl::OUString sPrivs = getPrivilegeString(objPrivileges);
    if(sPrivs.getLength())
    {
        ::rtl::OUString sGrant;
        sGrant += ::rtl::OUString::createFromAscii("REVOKE ");
        sGrant += sPrivs;
        sGrant += ::rtl::OUString::createFromAscii(" ON ");
        Reference<XDatabaseMetaData> xMeta = m_pConnection->getMetaData();
        sGrant += ::dbtools::quoteTableName(xMeta,objName,::dbtools::eInDataManipulation);
        sGrant += ::rtl::OUString::createFromAscii(" FROM ");
        sGrant += m_Name;

        Reference<XStatement> xStmt = m_pConnection->createStatement();
        if(xStmt.is())
            xStmt->execute(sGrant);
        ::comphelper::disposeComponent(xStmt);
    }
}
// -----------------------------------------------------------------------------
// XUser
void SAL_CALL OAdabasUser::changePassword( const ::rtl::OUString& objPassword, const ::rtl::OUString& newPassword ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OUser_BASE_RBHELPER::rBHelper.bDisposed);
    ::rtl::OUString sAlterPwd;
    sAlterPwd = ::rtl::OUString::createFromAscii("ALTER PASSWORD \"");
    sAlterPwd += objPassword.toAsciiUpperCase();
    sAlterPwd += ::rtl::OUString::createFromAscii("\" TO \"") ;
    sAlterPwd += newPassword.toAsciiUpperCase();
    sAlterPwd += ::rtl::OUString::createFromAscii("\"") ;

    sal_Bool bDisposeConnection = sal_False;
    Reference<XConnection> xConnection = m_pConnection;
    if(m_pConnection->getMetaData()->getUserName() != m_Name)
    {
        OAdabasConnection* pNewConnection = new OAdabasConnection(m_pConnection->getDriverHandle(),m_pConnection->getDriver());
        xConnection = pNewConnection;
        if(pNewConnection)
        {
            Sequence< PropertyValue> aSeq(2);
            aSeq.getArray()[0].Name     = ::rtl::OUString::createFromAscii("user") ;
            aSeq.getArray()[0].Value    <<= m_Name;
            aSeq.getArray()[1].Name     = ::rtl::OUString::createFromAscii("password") ;
            aSeq.getArray()[1].Value    <<= objPassword;
            pNewConnection->Construct(m_pConnection->getMetaData()->getURL(),aSeq);
        }
        bDisposeConnection = sal_True;
    }
    if(xConnection.is())
    {
        Reference<XStatement> xStmt = xConnection->createStatement();
        if(xStmt.is())
            xStmt->execute(sAlterPwd);
        ::comphelper::disposeComponent(xStmt);
        if(bDisposeConnection)
            ::comphelper::disposeComponent(xConnection);
    }
    else
        ::dbtools::throwFunctionSequenceException(*this);
}
// -----------------------------------------------------------------------------
::rtl::OUString OAdabasUser::getPrivilegeString(sal_Int32 nRights) const
{
    ::rtl::OUString sPrivs;
    if((nRights & Privilege::INSERT) == Privilege::INSERT)
        sPrivs += ::rtl::OUString::createFromAscii("INSERT");

    if((nRights & Privilege::DELETE) == Privilege::DELETE)
    {
        if(sPrivs.getLength())
            sPrivs += ::rtl::OUString::createFromAscii(",");
        sPrivs += ::rtl::OUString::createFromAscii("DELETE");
    }

    if((nRights & Privilege::UPDATE) == Privilege::UPDATE)
    {
        if(sPrivs.getLength())
            sPrivs += ::rtl::OUString::createFromAscii(",");
        sPrivs += ::rtl::OUString::createFromAscii("UPDATE");
    }

    if((nRights & Privilege::ALTER) == Privilege::ALTER)
    {
        if(sPrivs.getLength())
            sPrivs += ::rtl::OUString::createFromAscii(",");
        sPrivs += ::rtl::OUString::createFromAscii("ALTER");
    }

    if((nRights & Privilege::SELECT) == Privilege::SELECT)
    {
        if(sPrivs.getLength())
            sPrivs += ::rtl::OUString::createFromAscii(",");
        sPrivs += ::rtl::OUString::createFromAscii("SELECT");
    }

    if((nRights & Privilege::REFERENCE) == Privilege::REFERENCE)
    {
        if(sPrivs.getLength())
            sPrivs += ::rtl::OUString::createFromAscii(",");
        sPrivs += ::rtl::OUString::createFromAscii("REFERENCES");
    }

    return sPrivs;
}
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS warnings01 (1.14.30); FILE MERGED 2005/12/22 11:44:30 fs 1.14.30.2: #i57457# warning-free code 2005/11/16 12:58:50 fs 1.14.30.1: #i57457# warning free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: BUser.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 01:11:15 $
 *
 *  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_ADABAS_USER_HXX_
#include "adabas/BUser.hxx"
#endif
#ifndef _CONNECTIVITY_ADABAS_GROUPS_HXX_
#include "adabas/BGroups.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _CONNECTIVITY_ADABAS_BCONNECTION_HXX_
#include "adabas/BConnection.hxx"
#endif
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include "connectivity/dbtools.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBCX_PRIVILEGE_HPP_
#include <com/sun/star/sdbcx/Privilege.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_PRIVILEGEOBJECT_HPP_
#include <com/sun/star/sdbcx/PrivilegeObject.hpp>
#endif

using namespace connectivity::adabas;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
// -------------------------------------------------------------------------
OAdabasUser::OAdabasUser(   OAdabasConnection* _pConnection) : connectivity::sdbcx::OUser(sal_True)
                ,m_pConnection(_pConnection)
{
    construct();
}
// -------------------------------------------------------------------------
OAdabasUser::OAdabasUser(   OAdabasConnection* _pConnection,
                const ::rtl::OUString& _Name
            ) : connectivity::sdbcx::OUser(_Name,sal_True)
                ,m_pConnection(_pConnection)
{
    construct();
}
// -------------------------------------------------------------------------
void OAdabasUser::refreshGroups()
{
    if(!m_pConnection)
        return;

    TStringVector aVector;
    aVector.reserve(7); // we don't know the excatly count of users but this should fit the normal need
    Reference< XStatement > xStmt = m_pConnection->createStatement(  );
    ::rtl::OUString aSql = ::rtl::OUString::createFromAscii("SELECT DISTINCT GROUPNAME FROM DOMAIN.USERS WHERE GROUPNAME IS NOT NULL AND GROUPNAME <> ' ' AND USERNAME = '");
    aSql += getName( );
    aSql += ::rtl::OUString::createFromAscii("'");

    Reference< XResultSet > xResult = xStmt->executeQuery(aSql);
    if(xResult.is())
    {
                Reference< XRow > xRow(xResult,UNO_QUERY);
        while(xResult->next())
            aVector.push_back(xRow->getString(1));
        ::comphelper::disposeComponent(xResult);
    }
    ::comphelper::disposeComponent(xStmt);

    if(m_pGroups)
        m_pGroups->reFill(aVector);
    else
        m_pGroups = new OGroups(*this,m_aMutex,aVector,m_pConnection,this);
}
// -------------------------------------------------------------------------
OUserExtend::OUserExtend(   OAdabasConnection* _pConnection) : OAdabasUser(_pConnection)
{
    construct();
}
// -------------------------------------------------------------------------
OUserExtend::OUserExtend(   OAdabasConnection* _pConnection,const ::rtl::OUString& _Name) : OAdabasUser(_pConnection,_Name)
{
    construct();
}
// -------------------------------------------------------------------------
typedef connectivity::sdbcx::OUser  OUser_TYPEDEF;
void OUserExtend::construct()
{

    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_PASSWORD),    PROPERTY_ID_PASSWORD,0,&m_Password,::getCppuType(reinterpret_cast< ::rtl::OUString*>(NULL)));
}
// -----------------------------------------------------------------------------
cppu::IPropertyArrayHelper* OUserExtend::createArrayHelper() const
{
    Sequence< Property > aProps;
    describeProperties(aProps);
    return new cppu::OPropertyArrayHelper(aProps);
}
// -------------------------------------------------------------------------
cppu::IPropertyArrayHelper & OUserExtend::getInfoHelper()
{
    return *OUserExtend_PROP::getArrayHelper();
}
typedef connectivity::sdbcx::OUser_BASE OUser_BASE_RBHELPER;
// -----------------------------------------------------------------------------
sal_Int32 SAL_CALL OAdabasUser::getPrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(SQLException, RuntimeException)
{
    if ( objType != PrivilegeObject::TABLE )
        return 0;

    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OUser_BASE_RBHELPER::rBHelper.bDisposed);

    sal_Int32 nRights,nRightsWithGrant;
    getAnyTablePrivileges(objName,nRights,nRightsWithGrant);
    return nRights;
}
// -----------------------------------------------------------------------------
void OAdabasUser::getAnyTablePrivileges(const ::rtl::OUString& objName, sal_Int32& nRights,sal_Int32& nRightsWithGrant) throw(SQLException, RuntimeException)
{
    nRightsWithGrant = nRights = 0;
    // first we need to create the sql stmt to select the privs
    Reference<XDatabaseMetaData> xMeta = m_pConnection->getMetaData();
    ::rtl::OUString sCatalog,sSchema,sTable;
    ::dbtools::qualifiedNameComponents(xMeta,objName,sCatalog,sSchema,sTable,::dbtools::eInDataManipulation);
    Reference<XStatement> xStmt = m_pConnection->createStatement();
    ::rtl::OUString sSql = ::rtl::OUString::createFromAscii("SELECT REFTABLENAME,PRIVILEGES FROM DOMAIN.USR_USES_TAB WHERE REFOBJTYPE <> 'SYSTEM' AND DEFUSERNAME = '");
    sSql += m_Name;
    sSql += ::rtl::OUString::createFromAscii("' AND REFTABLENAME = '");
    sSql += sTable;
    sSql += ::rtl::OUString::createFromAscii("'");
    if(xStmt.is())
    {
        Reference<XResultSet> xRes = xStmt->executeQuery(sSql);
        if(xRes.is())
        {
            Reference<XRow> xRow(xRes,UNO_QUERY);
            if(xRow.is() && xRes->next())
            {
                ::rtl::OUString sPrivs = xRow->getString(2);

                struct _priv_nam
                {
                    const sal_Char* pAsciiName;
                    sal_Int32       nNumericValue;
                } privileges[] =
                {
                    { "INS", Privilege::INSERT },
                    { "DEL", Privilege::DELETE },
                    { "UPD", Privilege::UPDATE },
                    { "ALT", Privilege::ALTER },
                    { "SEL", Privilege::SELECT },
                    { "REF", Privilege::REFERENCE }
                };
                for ( size_t i = 0; i < sizeof( privileges ) / sizeof( privileges[0] ); ++i )
                {
                    sal_Int32 nIndex = sPrivs.indexOf( ::rtl::OUString::createFromAscii( privileges[i].pAsciiName ) );
                    if ( nIndex == -1 )
                        continue;

                    nRights |= privileges[i].nNumericValue;
                    if ( sPrivs.copy( nIndex + 2, 1 ).equalsAscii( "+" ) )
                        nRightsWithGrant |= privileges[i].nNumericValue;
                }
            }
            ::comphelper::disposeComponent(xRes);
        }
        ::comphelper::disposeComponent(xStmt);
    }
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL OAdabasUser::getGrantablePrivileges( const ::rtl::OUString& objName, sal_Int32 objType ) throw(SQLException, RuntimeException)
{
    if ( objType != PrivilegeObject::TABLE )
        return 0;

    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OUser_BASE_RBHELPER::rBHelper.bDisposed);

    sal_Int32 nRights,nRightsWithGrant;
    getAnyTablePrivileges(objName,nRights,nRightsWithGrant);
    return nRightsWithGrant;
}
// -------------------------------------------------------------------------
void SAL_CALL OAdabasUser::grantPrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(SQLException, RuntimeException)
{
    if ( objType != PrivilegeObject::TABLE )
        ::dbtools::throwSQLException( "Privilege not granted: Only table privileges can be granted", "01007", *this );

    ::osl::MutexGuard aGuard(m_aMutex);
    ::rtl::OUString sPrivs = getPrivilegeString(objPrivileges);
    if(sPrivs.getLength())
    {
        ::rtl::OUString sGrant;
        sGrant += ::rtl::OUString::createFromAscii("GRANT ");
        sGrant += sPrivs;
        sGrant += ::rtl::OUString::createFromAscii(" ON ");
        Reference<XDatabaseMetaData> xMeta = m_pConnection->getMetaData();
        sGrant += ::dbtools::quoteTableName(xMeta,objName,::dbtools::eInDataManipulation);
        sGrant += ::rtl::OUString::createFromAscii(" TO ");
        sGrant += m_Name;

        Reference<XStatement> xStmt = m_pConnection->createStatement();
        if(xStmt.is())
            xStmt->execute(sGrant);
        ::comphelper::disposeComponent(xStmt);
    }
}
// -------------------------------------------------------------------------
void SAL_CALL OAdabasUser::revokePrivileges( const ::rtl::OUString& objName, sal_Int32 objType, sal_Int32 objPrivileges ) throw(SQLException, RuntimeException)
{
    if ( objType != PrivilegeObject::TABLE )
        ::dbtools::throwSQLException( "Privilege not revoked: Only table privileges can be revoked", "01006", *this );

    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OUser_BASE_RBHELPER::rBHelper.bDisposed);
    ::rtl::OUString sPrivs = getPrivilegeString(objPrivileges);
    if(sPrivs.getLength())
    {
        ::rtl::OUString sGrant;
        sGrant += ::rtl::OUString::createFromAscii("REVOKE ");
        sGrant += sPrivs;
        sGrant += ::rtl::OUString::createFromAscii(" ON ");
        Reference<XDatabaseMetaData> xMeta = m_pConnection->getMetaData();
        sGrant += ::dbtools::quoteTableName(xMeta,objName,::dbtools::eInDataManipulation);
        sGrant += ::rtl::OUString::createFromAscii(" FROM ");
        sGrant += m_Name;

        Reference<XStatement> xStmt = m_pConnection->createStatement();
        if(xStmt.is())
            xStmt->execute(sGrant);
        ::comphelper::disposeComponent(xStmt);
    }
}
// -----------------------------------------------------------------------------
// XUser
void SAL_CALL OAdabasUser::changePassword( const ::rtl::OUString& objPassword, const ::rtl::OUString& newPassword ) throw(SQLException, RuntimeException)
{
    ::osl::MutexGuard aGuard(m_aMutex);
    checkDisposed(OUser_BASE_RBHELPER::rBHelper.bDisposed);
    ::rtl::OUString sAlterPwd;
    sAlterPwd = ::rtl::OUString::createFromAscii("ALTER PASSWORD \"");
    sAlterPwd += objPassword.toAsciiUpperCase();
    sAlterPwd += ::rtl::OUString::createFromAscii("\" TO \"") ;
    sAlterPwd += newPassword.toAsciiUpperCase();
    sAlterPwd += ::rtl::OUString::createFromAscii("\"") ;

    sal_Bool bDisposeConnection = sal_False;
    Reference<XConnection> xConnection = m_pConnection;
    if(m_pConnection->getMetaData()->getUserName() != m_Name)
    {
        OAdabasConnection* pNewConnection = new OAdabasConnection(m_pConnection->getDriverHandle(),m_pConnection->getDriver());
        xConnection = pNewConnection;
        if(pNewConnection)
        {
            Sequence< PropertyValue> aSeq(2);
            aSeq.getArray()[0].Name     = ::rtl::OUString::createFromAscii("user") ;
            aSeq.getArray()[0].Value    <<= m_Name;
            aSeq.getArray()[1].Name     = ::rtl::OUString::createFromAscii("password") ;
            aSeq.getArray()[1].Value    <<= objPassword;
            pNewConnection->Construct(m_pConnection->getMetaData()->getURL(),aSeq);
        }
        bDisposeConnection = sal_True;
    }
    if(xConnection.is())
    {
        Reference<XStatement> xStmt = xConnection->createStatement();
        if(xStmt.is())
            xStmt->execute(sAlterPwd);
        ::comphelper::disposeComponent(xStmt);
        if(bDisposeConnection)
            ::comphelper::disposeComponent(xConnection);
    }
    else
        ::dbtools::throwFunctionSequenceException(*this);
}
// -----------------------------------------------------------------------------
::rtl::OUString OAdabasUser::getPrivilegeString(sal_Int32 nRights) const
{
    ::rtl::OUString sPrivs;
    if((nRights & Privilege::INSERT) == Privilege::INSERT)
        sPrivs += ::rtl::OUString::createFromAscii("INSERT");

    if((nRights & Privilege::DELETE) == Privilege::DELETE)
    {
        if(sPrivs.getLength())
            sPrivs += ::rtl::OUString::createFromAscii(",");
        sPrivs += ::rtl::OUString::createFromAscii("DELETE");
    }

    if((nRights & Privilege::UPDATE) == Privilege::UPDATE)
    {
        if(sPrivs.getLength())
            sPrivs += ::rtl::OUString::createFromAscii(",");
        sPrivs += ::rtl::OUString::createFromAscii("UPDATE");
    }

    if((nRights & Privilege::ALTER) == Privilege::ALTER)
    {
        if(sPrivs.getLength())
            sPrivs += ::rtl::OUString::createFromAscii(",");
        sPrivs += ::rtl::OUString::createFromAscii("ALTER");
    }

    if((nRights & Privilege::SELECT) == Privilege::SELECT)
    {
        if(sPrivs.getLength())
            sPrivs += ::rtl::OUString::createFromAscii(",");
        sPrivs += ::rtl::OUString::createFromAscii("SELECT");
    }

    if((nRights & Privilege::REFERENCE) == Privilege::REFERENCE)
    {
        if(sPrivs.getLength())
            sPrivs += ::rtl::OUString::createFromAscii(",");
        sPrivs += ::rtl::OUString::createFromAscii("REFERENCES");
    }

    return sPrivs;
}
// -----------------------------------------------------------------------------

<|endoftext|>


<commit_before>#include "glyphpreviewdialog.h"

#include <svgglyphctrl.h>

#include <wx/sizer.h>
#include <wx/stattext.h>
#include <wx/textctrl.h>

#include <array>

GlyphPreviewDialog::GlyphPreviewDialog(wxWindow *parent, const SvgGlyph &glyph): wxDialog(parent, wxID_ANY, wxEmptyString,
	wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)
{
	wxBoxSizer *sizer = new wxBoxSizer(wxVERTICAL);
	{
		wxBoxSizer *hSizer = new wxBoxSizer(wxHORIZONTAL);

		hSizer->Add(new SvgGlyphCtrl(this, wxID_ANY, glyph, 128), 0, wxALIGN_LEFT | wxALIGN_BOTTOM, 0);
		hSizer->Add(new SvgGlyphCtrl(this, wxID_ANY, glyph, 64), 0, wxALIGN_LEFT | wxALIGN_BOTTOM, 0);
		hSizer->Add(new SvgGlyphCtrl(this, wxID_ANY, glyph, 16), 0, wxALIGN_LEFT | wxALIGN_BOTTOM, 0);

		wxFlexGridSizer *gridSize = new wxFlexGridSizer(2, 5, 5);

		gridSize->AddGrowableCol(1, 1);

		gridSize->Add(new wxStaticText(this, wxID_ANY, L"Name"), 0, wxALIGN_CENTER_VERTICAL, 0);
		gridSize->Add(new wxTextCtrl(this, wxID_ANY, glyph.glyphName, wxDefaultPosition, wxDefaultSize, wxTE_READONLY), 0, wxALIGN_CENTER_VERTICAL, 0);

		wxString unicode;
		unicode.Printf("%04x", glyph.unicode[0]);

		gridSize->Add(new wxStaticText(this, wxID_ANY, L"Unicode"), 0, wxALIGN_CENTER_VERTICAL, 0);
		gridSize->Add(new wxTextCtrl(this, wxID_ANY, unicode, wxDefaultPosition, wxDefaultSize, wxTE_READONLY), 0, wxALIGN_CENTER_VERTICAL, 0);

		sizer->Add(hSizer, 1, wxALL | wxEXPAND, 5);
		sizer->Add(gridSize, 0, wxALL | wxEXPAND, 5);
	}

	sizer->Add(CreateButtonSizer(wxOK), 0, wxALL | wxEXPAND, 5);

	SetSizerAndFit(sizer);
	SetLabel(L"Preview");
}
<commit_msg>removed unused include<commit_after>#include "glyphpreviewdialog.h"

#include <svgglyphctrl.h>

#include <wx/sizer.h>
#include <wx/stattext.h>
#include <wx/textctrl.h>

GlyphPreviewDialog::GlyphPreviewDialog(wxWindow *parent, const SvgGlyph &glyph): wxDialog(parent, wxID_ANY, wxEmptyString,
	wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)
{
	wxBoxSizer *sizer = new wxBoxSizer(wxVERTICAL);
	{
		wxBoxSizer *hSizer = new wxBoxSizer(wxHORIZONTAL);

		hSizer->Add(new SvgGlyphCtrl(this, wxID_ANY, glyph, 128), 0, wxALIGN_LEFT | wxALIGN_BOTTOM, 0);
		hSizer->Add(new SvgGlyphCtrl(this, wxID_ANY, glyph, 64), 0, wxALIGN_LEFT | wxALIGN_BOTTOM, 0);
		hSizer->Add(new SvgGlyphCtrl(this, wxID_ANY, glyph, 16), 0, wxALIGN_LEFT | wxALIGN_BOTTOM, 0);

		wxFlexGridSizer *gridSize = new wxFlexGridSizer(2, 5, 5);

		gridSize->AddGrowableCol(1, 1);

		gridSize->Add(new wxStaticText(this, wxID_ANY, L"Name"), 0, wxALIGN_CENTER_VERTICAL, 0);
		gridSize->Add(new wxTextCtrl(this, wxID_ANY, glyph.glyphName, wxDefaultPosition, wxDefaultSize, wxTE_READONLY), 0, wxALIGN_CENTER_VERTICAL, 0);

		wxString unicode;
		unicode.Printf("%04x", glyph.unicode[0]);

		gridSize->Add(new wxStaticText(this, wxID_ANY, L"Unicode"), 0, wxALIGN_CENTER_VERTICAL, 0);
		gridSize->Add(new wxTextCtrl(this, wxID_ANY, unicode, wxDefaultPosition, wxDefaultSize, wxTE_READONLY), 0, wxALIGN_CENTER_VERTICAL, 0);

		sizer->Add(hSizer, 1, wxALL | wxEXPAND, 5);
		sizer->Add(gridSize, 0, wxALL | wxEXPAND, 5);
	}

	sizer->Add(CreateButtonSizer(wxOK), 0, wxALL | wxEXPAND, 5);

	SetSizerAndFit(sizer);
	SetLabel(L"Preview");
}
<|endoftext|>


<commit_before>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/XKBlib.h>
#include <GL/glx.h>
#include <GL/gl.h>
#include <GL/glu.h>

#include "SkWindow.h"

#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkColor.h"
#include "SkEvent.h"
#include "SkKey.h"
#include "SkWindow.h"
#include "XkeysToSkKeys.h"
extern "C" {
    #include "keysym2ucs.h"
}

const int WIDTH = 500;
const int HEIGHT = 500;

// Determine which events to listen for.
const long EVENT_MASK = StructureNotifyMask|ButtonPressMask|ButtonReleaseMask
        |ExposureMask|PointerMotionMask|KeyPressMask|KeyReleaseMask;

SkOSWindow::SkOSWindow(void* unused)
    : fVi(NULL)
    , fMSAASampleCount(0) {
    fUnixWindow.fDisplay = NULL;
    fUnixWindow.fGLContext = NULL;
    this->initWindow(0);
    this->resize(WIDTH, HEIGHT);
}

SkOSWindow::~SkOSWindow() {
    this->closeWindow();
}

void SkOSWindow::closeWindow() {
    if (NULL != fUnixWindow.fDisplay) {
        this->detach();
        SkASSERT(NULL != fUnixWindow.fGc);
        XFreeGC(fUnixWindow.fDisplay, fUnixWindow.fGc);
        fUnixWindow.fGc = NULL;
        XDestroyWindow(fUnixWindow.fDisplay, fUnixWindow.fWin);
        fVi = NULL;
        XCloseDisplay(fUnixWindow.fDisplay);
        fUnixWindow.fDisplay = NULL;
        fMSAASampleCount = 0;
    }
}

void SkOSWindow::initWindow(int requestedMSAASampleCount) {
    if (fMSAASampleCount != requestedMSAASampleCount) {
        this->closeWindow();
    }
    // presence of fDisplay means we already have a window
    if (NULL != fUnixWindow.fDisplay) {
        return;
    }
    fUnixWindow.fDisplay = XOpenDisplay(NULL);
    Display* dsp = fUnixWindow.fDisplay;
    if (NULL == dsp) {
        SkDebugf("Could not open an X Display");
        return;
    }
    // Attempt to create a window that supports GL
    GLint att[] = {
        GLX_RGBA,
        GLX_DEPTH_SIZE, 24,
        GLX_DOUBLEBUFFER,
        GLX_STENCIL_SIZE, 8,
        None
    };
    SkASSERT(NULL == fVi);
    if (requestedMSAASampleCount > 0) {
        static const GLint kAttCount = SK_ARRAY_COUNT(att);
        GLint msaaAtt[kAttCount + 4];
        memcpy(msaaAtt, att, sizeof(att));
        SkASSERT(None == msaaAtt[kAttCount - 1]);
        msaaAtt[kAttCount - 1] = GLX_SAMPLE_BUFFERS_ARB;
        msaaAtt[kAttCount + 0] = 1;
        msaaAtt[kAttCount + 1] = GLX_SAMPLES_ARB;
        msaaAtt[kAttCount + 2] = requestedMSAASampleCount;
        msaaAtt[kAttCount + 3] = None;
        fVi = glXChooseVisual(dsp, DefaultScreen(dsp), msaaAtt);
        fMSAASampleCount = requestedMSAASampleCount;
    }
    if (NULL == fVi) {
        fVi = glXChooseVisual(dsp, DefaultScreen(dsp), att);
        fMSAASampleCount = 0;
    }

    if (fVi) {
        Colormap colorMap = XCreateColormap(dsp,
                                            RootWindow(dsp, fVi->screen),
                                            fVi->visual,
                                             AllocNone);
        XSetWindowAttributes swa;
        swa.colormap = colorMap;
        swa.event_mask = EVENT_MASK;
        fUnixWindow.fWin = XCreateWindow(dsp,
                                         RootWindow(dsp, fVi->screen),
                                         0, 0, // x, y
                                         WIDTH, HEIGHT,
                                         0, // border width
                                         fVi->depth,
                                         InputOutput,
                                         fVi->visual,
                                         CWEventMask | CWColormap,
                                         &swa);
    } else {
        // Create a simple window instead.  We will not be able to show GL
        fUnixWindow.fWin = XCreateSimpleWindow(dsp,
                                               DefaultRootWindow(dsp),
                                               0, 0,  // x, y
                                               WIDTH, HEIGHT,
                                               0,     // border width
                                               0,     // border value
                                               0);    // background value
    }
    this->mapWindowAndWait();
    fUnixWindow.fGc = XCreateGC(dsp, fUnixWindow.fWin, 0, NULL);
}

void SkOSWindow::post_linuxevent() {
    // Put an event in the X queue to fire an SkEvent.
    if (NULL == fUnixWindow.fDisplay) {
        return;
    }
    long event_mask = NoEventMask;
    XClientMessageEvent event;
    event.type = ClientMessage;
    Atom myAtom(0);
    event.message_type = myAtom;
    event.format = 32;
    event.data.l[0] = 0;
    XSendEvent(fUnixWindow.fDisplay, fUnixWindow.fWin, false, 0,
               (XEvent*) &event);
    XFlush(fUnixWindow.fDisplay);
}

static unsigned getModifierKeys(const XEvent& evt) {
//    unsigned xmod = evt.xkey.state;
    return 0;   // TODO
}

void SkOSWindow::loop() {
    Display* dsp = fUnixWindow.fDisplay;
    if (NULL == dsp) {
        return;
    }
    XSelectInput(dsp, fUnixWindow.fWin, EVENT_MASK);

    bool loop = true;
    XEvent evt;
    while (loop) {
        XNextEvent(dsp, &evt);
        switch (evt.type) {
            case Expose:
                if (evt.xexpose.count == 0)
                    this->inval(NULL);
                break;
            case ConfigureNotify:
                this->resize(evt.xconfigure.width, evt.xconfigure.height);
                break;
            case ButtonPress:
                if (evt.xbutton.button == Button1)
                    this->handleClick(evt.xbutton.x, evt.xbutton.y,
                              SkView::Click::kDown_State, getModifierKeys(evt));
                break;
            case ButtonRelease:
                if (evt.xbutton.button == Button1)
                    this->handleClick(evt.xbutton.x, evt.xbutton.y,
                                  SkView::Click::kUp_State, getModifierKeys(evt));
                break;
            case MotionNotify:
                this->handleClick(evt.xmotion.x, evt.xmotion.y,
                              SkView::Click::kMoved_State, getModifierKeys(evt));
                break;
            case KeyPress: {
                KeySym keysym = XkbKeycodeToKeysym(dsp, evt.xkey.keycode, 0, 0);
                //SkDebugf("pressed key %i!\n\tKeySym:%i\n", evt.xkey.keycode, XKeycodeToKeysym(dsp, evt.xkey.keycode, 0));
                if (keysym == XK_Escape) {
                    loop = false;
                    break;
                }
                this->handleKey(XKeyToSkKey(keysym));
                long uni = keysym2ucs(keysym);
                if (uni != -1) {
                    this->handleChar((SkUnichar) uni);
                }
                break;
            }
            case KeyRelease:
                //SkDebugf("released key %i\n", evt.xkey.keycode);
                this->handleKeyUp(XKeyToSkKey(XkbKeycodeToKeysym(dsp, evt.xkey.keycode, 0, 0)));
                break;
            case ClientMessage:
                if (SkEvent::ProcessEvent()) {
                    this->post_linuxevent();
                }
                break;
            default:
                // Do nothing for other events
                break;
        }
    }
}

void SkOSWindow::mapWindowAndWait() {
    SkASSERT(NULL != fUnixWindow.fDisplay);
    Display* dsp = fUnixWindow.fDisplay;
    Window win = fUnixWindow.fWin;
    XMapWindow(dsp, win);

    long eventMask = StructureNotifyMask;
    XSelectInput(dsp, win, eventMask);

    // Wait until screen is ready.
    XEvent evt;
    do {
        XNextEvent(dsp, &evt);
    } while(evt.type != MapNotify);

}

bool SkOSWindow::attach(SkBackEndTypes /* attachType */, int msaaSampleCount) {
    this->initWindow(msaaSampleCount);
    if (NULL == fUnixWindow.fDisplay) {
        return false;
    }
    if (NULL == fUnixWindow.fGLContext) {
        SkASSERT(NULL != fVi);

        fUnixWindow.fGLContext = glXCreateContext(fUnixWindow.fDisplay,
                                                  fVi,
                                                  NULL,
                                                  GL_TRUE);
        if (NULL == fUnixWindow.fGLContext) {
            return false;
        }
    }
    glXMakeCurrent(fUnixWindow.fDisplay,
                   fUnixWindow.fWin,
                   fUnixWindow.fGLContext);
    glViewport(0, 0,
               SkScalarRound(this->width()), SkScalarRound(this->height()));
    glClearColor(0, 0, 0, 0);
    glClearStencil(0);
    glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    return true;
}

void SkOSWindow::detach() {
    if (NULL == fUnixWindow.fDisplay || NULL == fUnixWindow.fGLContext) {
        return;
    }
    glXMakeCurrent(fUnixWindow.fDisplay, None, NULL);
    glXDestroyContext(fUnixWindow.fDisplay, fUnixWindow.fGLContext);
    fUnixWindow.fGLContext = NULL;
}

void SkOSWindow::present() {
    if (NULL != fUnixWindow.fDisplay && NULL != fUnixWindow.fGLContext) {
        glXSwapBuffers(fUnixWindow.fDisplay, fUnixWindow.fWin);
    }
}

void SkOSWindow::onSetTitle(const char title[]) {
    if (NULL == fUnixWindow.fDisplay) {
        return;
    }
    XTextProperty textProp;
    textProp.value = (unsigned char*)title;
    textProp.format = 8;
    textProp.nitems = strlen((char*)textProp.value);
    textProp.encoding = XA_STRING;
    XSetWMName(fUnixWindow.fDisplay, fUnixWindow.fWin, &textProp);
}

void SkOSWindow::onHandleInval(const SkIRect&) {
    (new SkEvent("inval-imageview", this->getSinkID()))->post();
}

bool SkOSWindow::onEvent(const SkEvent& evt) {
    if (evt.isType("inval-imageview")) {
        update(NULL);
        if (NULL == fUnixWindow.fGLContext)
            this->doPaint();
        return true;
    }
    return INHERITED::onEvent(evt);
}

static bool convertBitmapToXImage(XImage& image, const SkBitmap& bitmap) {
    sk_bzero(&image, sizeof(image));

    int bitsPerPixel = bitmap.bytesPerPixel() * 8;
    image.width = bitmap.width();
    image.height = bitmap.height();
    image.format = ZPixmap;
    image.data = (char*) bitmap.getPixels();
    image.byte_order = LSBFirst;
    image.bitmap_unit = bitsPerPixel;
    image.bitmap_bit_order = LSBFirst;
    image.bitmap_pad = bitsPerPixel;
    image.depth = 24;
    image.bytes_per_line = bitmap.rowBytes() - bitmap.width() * bitmap.bytesPerPixel();
    image.bits_per_pixel = bitsPerPixel;
    return XInitImage(&image);
}

void SkOSWindow::doPaint() {
    if (NULL == fUnixWindow.fDisplay) {
        return;
    }
    // Draw the bitmap to the screen.
    const SkBitmap& bitmap = getBitmap();
    int width = bitmap.width();
    int height = bitmap.height();

    XImage image;
    if (!convertBitmapToXImage(image, bitmap)) {
        return;
    }

    XPutImage(fUnixWindow.fDisplay,
              fUnixWindow.fWin,
              fUnixWindow.fGc,
              &image,
              0, 0,     // src x,y
              0, 0,     // dst x,y
              width, height);
}

bool SkOSWindow::onHandleChar(SkUnichar) {
    return false;
}

bool SkOSWindow::onHandleKey(SkKey key) {
    return false;
}

bool SkOSWindow::onHandleKeyUp(SkKey key) {
    return false;
}
<commit_msg>fix linux build<commit_after>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/XKBlib.h>
#include <GL/glx.h>
#include <GL/gl.h>
#include <GL/glu.h>

#include "SkWindow.h"

#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkColor.h"
#include "SkEvent.h"
#include "SkKey.h"
#include "SkWindow.h"
#include "XkeysToSkKeys.h"
extern "C" {
    #include "keysym2ucs.h"
}

const int WIDTH = 500;
const int HEIGHT = 500;

// Determine which events to listen for.
const long EVENT_MASK = StructureNotifyMask|ButtonPressMask|ButtonReleaseMask
        |ExposureMask|PointerMotionMask|KeyPressMask|KeyReleaseMask;

SkOSWindow::SkOSWindow(void* unused)
    : fVi(NULL)
    , fMSAASampleCount(0) {
    fUnixWindow.fDisplay = NULL;
    fUnixWindow.fGLContext = NULL;
    this->initWindow(0);
    this->resize(WIDTH, HEIGHT);
}

SkOSWindow::~SkOSWindow() {
    this->closeWindow();
}

void SkOSWindow::closeWindow() {
    if (NULL != fUnixWindow.fDisplay) {
        this->detach();
        SkASSERT(NULL != fUnixWindow.fGc);
        XFreeGC(fUnixWindow.fDisplay, fUnixWindow.fGc);
        fUnixWindow.fGc = NULL;
        XDestroyWindow(fUnixWindow.fDisplay, fUnixWindow.fWin);
        fVi = NULL;
        XCloseDisplay(fUnixWindow.fDisplay);
        fUnixWindow.fDisplay = NULL;
        fMSAASampleCount = 0;
    }
}

void SkOSWindow::initWindow(int requestedMSAASampleCount) {
    if (fMSAASampleCount != requestedMSAASampleCount) {
        this->closeWindow();
    }
    // presence of fDisplay means we already have a window
    if (NULL != fUnixWindow.fDisplay) {
        return;
    }
    fUnixWindow.fDisplay = XOpenDisplay(NULL);
    Display* dsp = fUnixWindow.fDisplay;
    if (NULL == dsp) {
        SkDebugf("Could not open an X Display");
        return;
    }
    // Attempt to create a window that supports GL
    GLint att[] = {
        GLX_RGBA,
        GLX_DEPTH_SIZE, 24,
        GLX_DOUBLEBUFFER,
        GLX_STENCIL_SIZE, 8,
        None
    };
    SkASSERT(NULL == fVi);
    if (requestedMSAASampleCount > 0) {
        static const GLint kAttCount = SK_ARRAY_COUNT(att);
        GLint msaaAtt[kAttCount + 4];
        memcpy(msaaAtt, att, sizeof(att));
        SkASSERT(None == msaaAtt[kAttCount - 1]);
        msaaAtt[kAttCount - 1] = GLX_SAMPLE_BUFFERS_ARB;
        msaaAtt[kAttCount + 0] = 1;
        msaaAtt[kAttCount + 1] = GLX_SAMPLES_ARB;
        msaaAtt[kAttCount + 2] = requestedMSAASampleCount;
        msaaAtt[kAttCount + 3] = None;
        fVi = glXChooseVisual(dsp, DefaultScreen(dsp), msaaAtt);
        fMSAASampleCount = requestedMSAASampleCount;
    }
    if (NULL == fVi) {
        fVi = glXChooseVisual(dsp, DefaultScreen(dsp), att);
        fMSAASampleCount = 0;
    }

    if (fVi) {
        Colormap colorMap = XCreateColormap(dsp,
                                            RootWindow(dsp, fVi->screen),
                                            fVi->visual,
                                             AllocNone);
        XSetWindowAttributes swa;
        swa.colormap = colorMap;
        swa.event_mask = EVENT_MASK;
        fUnixWindow.fWin = XCreateWindow(dsp,
                                         RootWindow(dsp, fVi->screen),
                                         0, 0, // x, y
                                         WIDTH, HEIGHT,
                                         0, // border width
                                         fVi->depth,
                                         InputOutput,
                                         fVi->visual,
                                         CWEventMask | CWColormap,
                                         &swa);
    } else {
        // Create a simple window instead.  We will not be able to show GL
        fUnixWindow.fWin = XCreateSimpleWindow(dsp,
                                               DefaultRootWindow(dsp),
                                               0, 0,  // x, y
                                               WIDTH, HEIGHT,
                                               0,     // border width
                                               0,     // border value
                                               0);    // background value
    }
    this->mapWindowAndWait();
    fUnixWindow.fGc = XCreateGC(dsp, fUnixWindow.fWin, 0, NULL);
}

void SkOSWindow::post_linuxevent() {
    // Put an event in the X queue to fire an SkEvent.
    if (NULL == fUnixWindow.fDisplay) {
        return;
    }
    long event_mask = NoEventMask;
    XClientMessageEvent event;
    event.type = ClientMessage;
    Atom myAtom(0);
    event.message_type = myAtom;
    event.format = 32;
    event.data.l[0] = 0;
    XSendEvent(fUnixWindow.fDisplay, fUnixWindow.fWin, false, 0,
               (XEvent*) &event);
    XFlush(fUnixWindow.fDisplay);
}

static unsigned getModi(const XEvent& evt) {
//    unsigned xmod = evt.xkey.state;
    return 0;   // TODO
}

void SkOSWindow::loop() {
    Display* dsp = fUnixWindow.fDisplay;
    if (NULL == dsp) {
        return;
    }
    XSelectInput(dsp, fUnixWindow.fWin, EVENT_MASK);

    bool loop = true;
    XEvent evt;
    while (loop) {
        XNextEvent(dsp, &evt);
        switch (evt.type) {
            case Expose:
                if (evt.xexpose.count == 0)
                    this->inval(NULL);
                break;
            case ConfigureNotify:
                this->resize(evt.xconfigure.width, evt.xconfigure.height);
                break;
            case ButtonPress:
                if (evt.xbutton.button == Button1)
                    this->handleClick(evt.xbutton.x, evt.xbutton.y,
                                SkView::Click::kDown_State, NULL, getModi(evt));
                break;
            case ButtonRelease:
                if (evt.xbutton.button == Button1)
                    this->handleClick(evt.xbutton.x, evt.xbutton.y,
                                  SkView::Click::kUp_State, NULL, getModi(evt));
                break;
            case MotionNotify:
                this->handleClick(evt.xmotion.x, evt.xmotion.y,
                               SkView::Click::kMoved_State, NULL, getModi(evt));
                break;
            case KeyPress: {
                KeySym keysym = XkbKeycodeToKeysym(dsp, evt.xkey.keycode, 0, 0);
                //SkDebugf("pressed key %i!\n\tKeySym:%i\n", evt.xkey.keycode, XKeycodeToKeysym(dsp, evt.xkey.keycode, 0));
                if (keysym == XK_Escape) {
                    loop = false;
                    break;
                }
                this->handleKey(XKeyToSkKey(keysym));
                long uni = keysym2ucs(keysym);
                if (uni != -1) {
                    this->handleChar((SkUnichar) uni);
                }
                break;
            }
            case KeyRelease:
                //SkDebugf("released key %i\n", evt.xkey.keycode);
                this->handleKeyUp(XKeyToSkKey(XkbKeycodeToKeysym(dsp, evt.xkey.keycode, 0, 0)));
                break;
            case ClientMessage:
                if (SkEvent::ProcessEvent()) {
                    this->post_linuxevent();
                }
                break;
            default:
                // Do nothing for other events
                break;
        }
    }
}

void SkOSWindow::mapWindowAndWait() {
    SkASSERT(NULL != fUnixWindow.fDisplay);
    Display* dsp = fUnixWindow.fDisplay;
    Window win = fUnixWindow.fWin;
    XMapWindow(dsp, win);

    long eventMask = StructureNotifyMask;
    XSelectInput(dsp, win, eventMask);

    // Wait until screen is ready.
    XEvent evt;
    do {
        XNextEvent(dsp, &evt);
    } while(evt.type != MapNotify);

}

bool SkOSWindow::attach(SkBackEndTypes /* attachType */, int msaaSampleCount) {
    this->initWindow(msaaSampleCount);
    if (NULL == fUnixWindow.fDisplay) {
        return false;
    }
    if (NULL == fUnixWindow.fGLContext) {
        SkASSERT(NULL != fVi);

        fUnixWindow.fGLContext = glXCreateContext(fUnixWindow.fDisplay,
                                                  fVi,
                                                  NULL,
                                                  GL_TRUE);
        if (NULL == fUnixWindow.fGLContext) {
            return false;
        }
    }
    glXMakeCurrent(fUnixWindow.fDisplay,
                   fUnixWindow.fWin,
                   fUnixWindow.fGLContext);
    glViewport(0, 0,
               SkScalarRound(this->width()), SkScalarRound(this->height()));
    glClearColor(0, 0, 0, 0);
    glClearStencil(0);
    glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
    return true;
}

void SkOSWindow::detach() {
    if (NULL == fUnixWindow.fDisplay || NULL == fUnixWindow.fGLContext) {
        return;
    }
    glXMakeCurrent(fUnixWindow.fDisplay, None, NULL);
    glXDestroyContext(fUnixWindow.fDisplay, fUnixWindow.fGLContext);
    fUnixWindow.fGLContext = NULL;
}

void SkOSWindow::present() {
    if (NULL != fUnixWindow.fDisplay && NULL != fUnixWindow.fGLContext) {
        glXSwapBuffers(fUnixWindow.fDisplay, fUnixWindow.fWin);
    }
}

void SkOSWindow::onSetTitle(const char title[]) {
    if (NULL == fUnixWindow.fDisplay) {
        return;
    }
    XTextProperty textProp;
    textProp.value = (unsigned char*)title;
    textProp.format = 8;
    textProp.nitems = strlen((char*)textProp.value);
    textProp.encoding = XA_STRING;
    XSetWMName(fUnixWindow.fDisplay, fUnixWindow.fWin, &textProp);
}

void SkOSWindow::onHandleInval(const SkIRect&) {
    (new SkEvent("inval-imageview", this->getSinkID()))->post();
}

bool SkOSWindow::onEvent(const SkEvent& evt) {
    if (evt.isType("inval-imageview")) {
        update(NULL);
        if (NULL == fUnixWindow.fGLContext)
            this->doPaint();
        return true;
    }
    return INHERITED::onEvent(evt);
}

static bool convertBitmapToXImage(XImage& image, const SkBitmap& bitmap) {
    sk_bzero(&image, sizeof(image));

    int bitsPerPixel = bitmap.bytesPerPixel() * 8;
    image.width = bitmap.width();
    image.height = bitmap.height();
    image.format = ZPixmap;
    image.data = (char*) bitmap.getPixels();
    image.byte_order = LSBFirst;
    image.bitmap_unit = bitsPerPixel;
    image.bitmap_bit_order = LSBFirst;
    image.bitmap_pad = bitsPerPixel;
    image.depth = 24;
    image.bytes_per_line = bitmap.rowBytes() - bitmap.width() * bitmap.bytesPerPixel();
    image.bits_per_pixel = bitsPerPixel;
    return XInitImage(&image);
}

void SkOSWindow::doPaint() {
    if (NULL == fUnixWindow.fDisplay) {
        return;
    }
    // Draw the bitmap to the screen.
    const SkBitmap& bitmap = getBitmap();
    int width = bitmap.width();
    int height = bitmap.height();

    XImage image;
    if (!convertBitmapToXImage(image, bitmap)) {
        return;
    }

    XPutImage(fUnixWindow.fDisplay,
              fUnixWindow.fWin,
              fUnixWindow.fGc,
              &image,
              0, 0,     // src x,y
              0, 0,     // dst x,y
              width, height);
}

bool SkOSWindow::onHandleChar(SkUnichar) {
    return false;
}

bool SkOSWindow::onHandleKey(SkKey key) {
    return false;
}

bool SkOSWindow::onHandleKeyUp(SkKey key) {
    return false;
}
<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (c) 2020-2021 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

#include "FakeImu.hpp"

using namespace time_literals;

FakeImu::FakeImu() :
	ModuleParams(nullptr),
	ScheduledWorkItem(MODULE_NAME, px4::wq_configurations::hp_default),
	_px4_accel(1310988), // 1310988: DRV_IMU_DEVTYPE_SIM, BUS: 1, ADDR: 1, TYPE: SIMULATION
	_px4_gyro(1310988)   // 1310988: DRV_IMU_DEVTYPE_SIM, BUS: 1, ADDR: 1, TYPE: SIMULATION
{
	_sensor_interval_us = roundf(1.e6f / _px4_gyro.get_max_rate_hz());

	PX4_INFO("Rate %.3f, Interval: %d us", (double)_px4_gyro.get_max_rate_hz(), _sensor_interval_us);

	_px4_accel.set_range(2000.f); // don't care

	_px4_gyro.set_scale(math::radians(2000.f) / static_cast<float>(INT16_MAX - 1)); // 2000 degrees/second max
}

bool FakeImu::init()
{
	ScheduleOnInterval(_sensor_interval_us);
	return true;
}

void FakeImu::Run()
{
	if (should_exit()) {
		ScheduleClear();
		exit_and_cleanup();
		return;
	}

	sensor_gyro_fifo_s gyro{};
	gyro.timestamp_sample = hrt_absolute_time();
	gyro.samples = roundf(IMU_RATE_HZ / (1e6 / _sensor_interval_us));
	gyro.dt = 1e6 / IMU_RATE_HZ;

	const double dt_s = 1 / IMU_RATE_HZ;

	const double x_f0 = 0.0;    //    0 Hz X frequency start
	const double x_f1 = 10.0;   //   10 Hz X frequency stop

	const double y_f0 = 0.0;    //   10 Hz Y frequency start
	const double y_f1 = 100.0;  // 1000 Hz Y frequency stop

	const double z_f0 = 0.0;    //  100 Hz Z frequency start
	const double z_f1 = 1000.0; // 1000 Hz Z frequency stop

	// amplitude
	static constexpr double A = (INT16_MAX - 1);

	if (_time_start_us == 0) {
		_time_start_us = gyro.timestamp_sample;
	}

	// 10 second sweep
	const double T = 10.0;

	const double timestamp_sample_s = static_cast<double>(gyro.timestamp_sample - _time_start_us) / 1e6;

	float x_freq = 0;
	float y_freq = 0;
	float z_freq = 0;

	for (int n = 0; n < gyro.samples; n++) {
		// timestamp_sample corresponds to last sample
		const double t = timestamp_sample_s - (gyro.samples - n - 1) * dt_s;

		// linear-frequency chirp, see https://en.wikipedia.org/wiki/Chirp
		const double x_F = x_f0 + (x_f1 - x_f0) * t / (2 * T);
		const double y_F = y_f0 + (y_f1 - y_f0) * t / (2 * T);
		const double z_F = z_f0 + (z_f1 - z_f0) * t / (2 * T);

		gyro.x[n] = roundf(A * sin(2 * M_PI * x_F * t));
		gyro.y[n] = roundf(A * sin(2 * M_PI * y_F * t));
		gyro.z[n] = roundf(A * sin(2 * M_PI * z_F * t));

		if (n == 0) {
			x_freq = (x_f1 - x_f0) * (t / T) + x_f0;
			y_freq = (y_f1 - y_f0) * (t / T) + y_f0;
			z_freq = (z_f1 - z_f0) * (t / T) + z_f0;

			_px4_accel.update(gyro.timestamp_sample, x_freq, y_freq, z_freq);
		}
	}

	_px4_gyro.updateFIFO(gyro);

#if defined(FAKE_IMU_FAKE_ESC_STATUS)

	// publish fake esc status at ~10 Hz
	if (hrt_elapsed_time(&_esc_status_pub.get().timestamp) > 100_ms) {
		auto &esc_status = _esc_status_pub.get();

		esc_status.esc_count = 3;

		// ESC 0 follow X axis RPM
		if (!(timestamp_sample_s > 1.5 && timestamp_sample_s < 2.0)) {
			// simulate drop out at 1.5 to 2 seconds
			esc_status.esc[0].timestamp = hrt_absolute_time();
			esc_status.esc[0].esc_rpm = x_freq * 60;
		}

		// ESC 1 follow Y axis RPM
		if (!(timestamp_sample_s > 2.5 && timestamp_sample_s < 3.0)) {
			// simulate drop out at 2.5 to 3 seconds
			esc_status.esc[1].timestamp = hrt_absolute_time();
			esc_status.esc[1].esc_rpm = y_freq * 60;
		}

		// ESC 2 follow Z axis RPM
		if (!(timestamp_sample_s > 3.5 && timestamp_sample_s < 4.0)) {
			// simulate drop out at 3.5 to 4 seconds
			esc_status.esc[2].timestamp = hrt_absolute_time();
			esc_status.esc[2].esc_rpm = z_freq * 60;
		}

		// simulate brief dropout of all data
		if (timestamp_sample_s > 5.5 && timestamp_sample_s < 5.6) {
			esc_status.esc[0].esc_rpm = 0;
			esc_status.esc[1].esc_rpm = 0;
			esc_status.esc[2].esc_rpm = 0;
		}

		esc_status.timestamp = hrt_absolute_time();
		_esc_status_pub.update();
	}

#endif // FAKE_IMU_FAKE_ESC_STATUS
}

int FakeImu::task_spawn(int argc, char *argv[])
{
	FakeImu *instance = new FakeImu();

	if (instance) {
		_object.store(instance);
		_task_id = task_id_is_work_queue;

		if (instance->init()) {
			return PX4_OK;
		}

	} else {
		PX4_ERR("alloc failed");
	}

	delete instance;
	_object.store(nullptr);
	_task_id = -1;

	return PX4_ERROR;
}

int FakeImu::custom_command(int argc, char *argv[])
{
	return print_usage("unknown command");
}

int FakeImu::print_usage(const char *reason)
{
	if (reason) {
		PX4_WARN("%s\n", reason);
	}

	PRINT_MODULE_DESCRIPTION(
		R"DESCR_STR(
### Description

)DESCR_STR");

	PRINT_MODULE_USAGE_NAME("fake_imu", "driver");
	PRINT_MODULE_USAGE_COMMAND("start");
	PRINT_MODULE_USAGE_DEFAULT_COMMANDS();
	return 0;
}

extern "C" __EXPORT int fake_imu_main(int argc, char *argv[])
{
	return FakeImu::main(argc, argv);
}
<commit_msg>FakeImu:Use inttypes<commit_after>/****************************************************************************
 *
 *   Copyright (c) 2020-2021 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

#include "FakeImu.hpp"

using namespace time_literals;

FakeImu::FakeImu() :
	ModuleParams(nullptr),
	ScheduledWorkItem(MODULE_NAME, px4::wq_configurations::hp_default),
	_px4_accel(1310988), // 1310988: DRV_IMU_DEVTYPE_SIM, BUS: 1, ADDR: 1, TYPE: SIMULATION
	_px4_gyro(1310988)   // 1310988: DRV_IMU_DEVTYPE_SIM, BUS: 1, ADDR: 1, TYPE: SIMULATION
{
	_sensor_interval_us = roundf(1.e6f / _px4_gyro.get_max_rate_hz());

	PX4_INFO("Rate %.3f, Interval: %" PRId32 " us", (double)_px4_gyro.get_max_rate_hz(), _sensor_interval_us);

	_px4_accel.set_range(2000.f); // don't care

	_px4_gyro.set_scale(math::radians(2000.f) / static_cast<float>(INT16_MAX - 1)); // 2000 degrees/second max
}

bool FakeImu::init()
{
	ScheduleOnInterval(_sensor_interval_us);
	return true;
}

void FakeImu::Run()
{
	if (should_exit()) {
		ScheduleClear();
		exit_and_cleanup();
		return;
	}

	sensor_gyro_fifo_s gyro{};
	gyro.timestamp_sample = hrt_absolute_time();
	gyro.samples = roundf(IMU_RATE_HZ / (1e6 / _sensor_interval_us));
	gyro.dt = 1e6 / IMU_RATE_HZ;

	const double dt_s = 1 / IMU_RATE_HZ;

	const double x_f0 = 0.0;    //    0 Hz X frequency start
	const double x_f1 = 10.0;   //   10 Hz X frequency stop

	const double y_f0 = 0.0;    //   10 Hz Y frequency start
	const double y_f1 = 100.0;  // 1000 Hz Y frequency stop

	const double z_f0 = 0.0;    //  100 Hz Z frequency start
	const double z_f1 = 1000.0; // 1000 Hz Z frequency stop

	// amplitude
	static constexpr double A = (INT16_MAX - 1);

	if (_time_start_us == 0) {
		_time_start_us = gyro.timestamp_sample;
	}

	// 10 second sweep
	const double T = 10.0;

	const double timestamp_sample_s = static_cast<double>(gyro.timestamp_sample - _time_start_us) / 1e6;

	float x_freq = 0;
	float y_freq = 0;
	float z_freq = 0;

	for (int n = 0; n < gyro.samples; n++) {
		// timestamp_sample corresponds to last sample
		const double t = timestamp_sample_s - (gyro.samples - n - 1) * dt_s;

		// linear-frequency chirp, see https://en.wikipedia.org/wiki/Chirp
		const double x_F = x_f0 + (x_f1 - x_f0) * t / (2 * T);
		const double y_F = y_f0 + (y_f1 - y_f0) * t / (2 * T);
		const double z_F = z_f0 + (z_f1 - z_f0) * t / (2 * T);

		gyro.x[n] = roundf(A * sin(2 * M_PI * x_F * t));
		gyro.y[n] = roundf(A * sin(2 * M_PI * y_F * t));
		gyro.z[n] = roundf(A * sin(2 * M_PI * z_F * t));

		if (n == 0) {
			x_freq = (x_f1 - x_f0) * (t / T) + x_f0;
			y_freq = (y_f1 - y_f0) * (t / T) + y_f0;
			z_freq = (z_f1 - z_f0) * (t / T) + z_f0;

			_px4_accel.update(gyro.timestamp_sample, x_freq, y_freq, z_freq);
		}
	}

	_px4_gyro.updateFIFO(gyro);

#if defined(FAKE_IMU_FAKE_ESC_STATUS)

	// publish fake esc status at ~10 Hz
	if (hrt_elapsed_time(&_esc_status_pub.get().timestamp) > 100_ms) {
		auto &esc_status = _esc_status_pub.get();

		esc_status.esc_count = 3;

		// ESC 0 follow X axis RPM
		if (!(timestamp_sample_s > 1.5 && timestamp_sample_s < 2.0)) {
			// simulate drop out at 1.5 to 2 seconds
			esc_status.esc[0].timestamp = hrt_absolute_time();
			esc_status.esc[0].esc_rpm = x_freq * 60;
		}

		// ESC 1 follow Y axis RPM
		if (!(timestamp_sample_s > 2.5 && timestamp_sample_s < 3.0)) {
			// simulate drop out at 2.5 to 3 seconds
			esc_status.esc[1].timestamp = hrt_absolute_time();
			esc_status.esc[1].esc_rpm = y_freq * 60;
		}

		// ESC 2 follow Z axis RPM
		if (!(timestamp_sample_s > 3.5 && timestamp_sample_s < 4.0)) {
			// simulate drop out at 3.5 to 4 seconds
			esc_status.esc[2].timestamp = hrt_absolute_time();
			esc_status.esc[2].esc_rpm = z_freq * 60;
		}

		// simulate brief dropout of all data
		if (timestamp_sample_s > 5.5 && timestamp_sample_s < 5.6) {
			esc_status.esc[0].esc_rpm = 0;
			esc_status.esc[1].esc_rpm = 0;
			esc_status.esc[2].esc_rpm = 0;
		}

		esc_status.timestamp = hrt_absolute_time();
		_esc_status_pub.update();
	}

#endif // FAKE_IMU_FAKE_ESC_STATUS
}

int FakeImu::task_spawn(int argc, char *argv[])
{
	FakeImu *instance = new FakeImu();

	if (instance) {
		_object.store(instance);
		_task_id = task_id_is_work_queue;

		if (instance->init()) {
			return PX4_OK;
		}

	} else {
		PX4_ERR("alloc failed");
	}

	delete instance;
	_object.store(nullptr);
	_task_id = -1;

	return PX4_ERROR;
}

int FakeImu::custom_command(int argc, char *argv[])
{
	return print_usage("unknown command");
}

int FakeImu::print_usage(const char *reason)
{
	if (reason) {
		PX4_WARN("%s\n", reason);
	}

	PRINT_MODULE_DESCRIPTION(
		R"DESCR_STR(
### Description

)DESCR_STR");

	PRINT_MODULE_USAGE_NAME("fake_imu", "driver");
	PRINT_MODULE_USAGE_COMMAND("start");
	PRINT_MODULE_USAGE_DEFAULT_COMMANDS();
	return 0;
}

extern "C" __EXPORT int fake_imu_main(int argc, char *argv[])
{
	return FakeImu::main(argc, argv);
}
<|endoftext|>


<commit_before>/* Copyright 2019 Benjamin Worpitz
 *
 * This file is part of Alpaka.
 *
 * 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/.
 */

#include <alpaka/kernel/Traits.hpp>

#include <alpaka/test/acc/TestAccs.hpp>
#include <alpaka/test/KernelExecutionFixture.hpp>
#include <alpaka/core/BoostPredef.hpp>

#include <catch2/catch.hpp>

#include <functional>
#if BOOST_LANG_CUDA
#include <nvfunctional>
#endif

//-----------------------------------------------------------------------------
template<
    typename TAcc>
void ALPAKA_FN_ACC kernelFn(
    TAcc const & acc,
    bool * success,
    std::int32_t val)
{
    alpaka::ignore_unused(acc);

    ALPAKA_CHECK(*success, 42 == val);
}

// std::function and std::bind is only allowed on CPU
#if !BOOST_LANG_CUDA && !BOOST_LANG_HIP
//-----------------------------------------------------------------------------
struct TestTemplateStdFunction
{
template< typename TAcc >
void operator()()
{
    using Dim = alpaka::dim::Dim<TAcc>;
    using Idx = alpaka::idx::Idx<TAcc>;

    alpaka::test::KernelExecutionFixture<TAcc> fixture(
        alpaka::vec::Vec<Dim, Idx>::ones());

    const auto kernel = std::function<void(TAcc const &, bool *, std::int32_t)>( kernelFn<TAcc> );
    REQUIRE(fixture(kernel, 42));
  }
};

TEST_CASE( "stdFunctionKernelIsWorking", "[kernel]")
{
    alpaka::meta::forEachType< alpaka::test::acc::TestAccs >( TestTemplateStdFunction() );
}

//-----------------------------------------------------------------------------
struct TestTemplateStdBind
{
template< typename TAcc >
void operator()()
{
    using Dim = alpaka::dim::Dim<TAcc>;
    using Idx = alpaka::idx::Idx<TAcc>;

    alpaka::test::KernelExecutionFixture<TAcc> fixture(
        alpaka::vec::Vec<Dim, Idx>::ones());

    const auto kernel = std::bind( kernelFn<TAcc>, std::placeholders::_1, std::placeholders::_2, 42 );
    REQUIRE(fixture(kernel));
  }
};

TEST_CASE( "stdBindKernelIsWorking", "[kernel]")
{
    alpaka::meta::forEachType< alpaka::test::acc::TestAccs >( TestTemplateStdBind() );
}
#endif

#if BOOST_LANG_CUDA
// clang as a native CUDA compiler does not seem to support nvstd::function when ALPAKA_ACC_GPU_CUDA_ONLY_MODE is used.
// error: reference to __device__ function 'kernelFn<alpaka::acc::AccGpuCudaRt<std::__1::integral_constant<unsigned long, 1>, unsigned long> >' in __host__ function const auto kernel = nvstd::function<void(TAcc const &, bool *, std::int32_t)>( kernelFn<TAcc> );
#if !(defined(ALPAKA_ACC_GPU_CUDA_ONLY_MODE) && BOOST_COMP_CLANG_CUDA)
//-----------------------------------------------------------------------------
struct TestTemplateNvstdFunction
{
template< typename TAcc >
void operator()()
{
    using Dim = alpaka::dim::Dim<TAcc>;
    using Idx = alpaka::idx::Idx<TAcc>;

    alpaka::test::KernelExecutionFixture<TAcc> fixture(
        alpaka::vec::Vec<Dim, Idx>::ones());

    const auto kernel = nvstd::function<void(TAcc const &, bool *, std::int32_t)>( kernelFn<TAcc> );
    REQUIRE(fixture(kernel, 42));
  }
};

TEST_CASE( "nvstdFunctionKernelIsWorking", "[kernel]")
{
    alpaka::meta::forEachType< alpaka::test::acc::TestAccs >( TestTemplateNvstdFunction() );
}
#endif
#endif
<commit_msg>Disable nvstd::function test due to cudaErrorIllegalInstruction crashes<commit_after>/* Copyright 2019 Benjamin Worpitz
 *
 * This file is part of Alpaka.
 *
 * 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/.
 */

#include <alpaka/kernel/Traits.hpp>

#include <alpaka/test/acc/TestAccs.hpp>
#include <alpaka/test/KernelExecutionFixture.hpp>
#include <alpaka/core/BoostPredef.hpp>

#include <catch2/catch.hpp>

#include <functional>
#if BOOST_LANG_CUDA
#include <nvfunctional>
#endif

//-----------------------------------------------------------------------------
template<
    typename TAcc>
void ALPAKA_FN_ACC kernelFn(
    TAcc const & acc,
    bool * success,
    std::int32_t val)
{
    alpaka::ignore_unused(acc);

    ALPAKA_CHECK(*success, 42 == val);
}

// std::function and std::bind is only allowed on CPU
#if !BOOST_LANG_CUDA && !BOOST_LANG_HIP
//-----------------------------------------------------------------------------
struct TestTemplateStdFunction
{
template< typename TAcc >
void operator()()
{
    using Dim = alpaka::dim::Dim<TAcc>;
    using Idx = alpaka::idx::Idx<TAcc>;

    alpaka::test::KernelExecutionFixture<TAcc> fixture(
        alpaka::vec::Vec<Dim, Idx>::ones());

    const auto kernel = std::function<void(TAcc const &, bool *, std::int32_t)>( kernelFn<TAcc> );
    REQUIRE(fixture(kernel, 42));
  }
};

TEST_CASE( "stdFunctionKernelIsWorking", "[kernel]")
{
    alpaka::meta::forEachType< alpaka::test::acc::TestAccs >( TestTemplateStdFunction() );
}

//-----------------------------------------------------------------------------
struct TestTemplateStdBind
{
template< typename TAcc >
void operator()()
{
    using Dim = alpaka::dim::Dim<TAcc>;
    using Idx = alpaka::idx::Idx<TAcc>;

    alpaka::test::KernelExecutionFixture<TAcc> fixture(
        alpaka::vec::Vec<Dim, Idx>::ones());

    const auto kernel = std::bind( kernelFn<TAcc>, std::placeholders::_1, std::placeholders::_2, 42 );
    REQUIRE(fixture(kernel));
  }
};

TEST_CASE( "stdBindKernelIsWorking", "[kernel]")
{
    alpaka::meta::forEachType< alpaka::test::acc::TestAccs >( TestTemplateStdBind() );
}
#endif

// This test is disabled due to #836 (cudaErrorIllegalInstruction crash)
#if 0
//#if BOOST_LANG_CUDA
// clang as a native CUDA compiler does not seem to support nvstd::function when ALPAKA_ACC_GPU_CUDA_ONLY_MODE is used.
// error: reference to __device__ function 'kernelFn<alpaka::acc::AccGpuCudaRt<std::__1::integral_constant<unsigned long, 1>, unsigned long> >' in __host__ function const auto kernel = nvstd::function<void(TAcc const &, bool *, std::int32_t)>( kernelFn<TAcc> );
#if !(defined(ALPAKA_ACC_GPU_CUDA_ONLY_MODE) && BOOST_COMP_CLANG_CUDA)
//-----------------------------------------------------------------------------
struct TestTemplateNvstdFunction
{
template< typename TAcc >
void operator()()
{
    using Dim = alpaka::dim::Dim<TAcc>;
    using Idx = alpaka::idx::Idx<TAcc>;

    alpaka::test::KernelExecutionFixture<TAcc> fixture(
        alpaka::vec::Vec<Dim, Idx>::ones());

    const auto kernel = nvstd::function<void(TAcc const &, bool *, std::int32_t)>( kernelFn<TAcc> );
    REQUIRE(fixture(kernel, 42));
  }
};

TEST_CASE( "nvstdFunctionKernelIsWorking", "[kernel]")
{
    alpaka::meta::forEachType< alpaka::test::acc::TestAccs >( TestTemplateNvstdFunction() );
}
#endif
#endif
<|endoftext|>