<commit_before>/*************************************************************************
 *
 *  $RCSfile: AStatement.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: fs $ $Date: 2002-01-18 16:23:14 $
 *
 *  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_ADO_ASTATEMENT_HXX_
#define _CONNECTIVITY_ADO_ASTATEMENT_HXX_

#ifndef _COM_SUN_STAR_SDBC_XSTATEMENT_HPP_
#include <com/sun/star/sdbc/XStatement.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XWARNINGSSUPPLIER_HPP_
#include <com/sun/star/sdbc/XWarningsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XMULTIPLERESULTS_HPP_
#include <com/sun/star/sdbc/XMultipleResults.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XBATCHEXECUTION_HPP_
#include <com/sun/star/sdbc/XBatchExecution.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCLOSEABLE_HPP_
#include <com/sun/star/sdbc/XCloseable.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_
#include <com/sun/star/sdbc/SQLWarning.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XCANCELLABLE_HPP_
#include <com/sun/star/util/XCancellable.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE5_HXX_
#include <cppuhelper/compbase5.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef _CONNECTIVITY_ADO_ACONNECTION_HXX_
#include "ado/AConnection.hxx"
#endif
#ifndef _LIST_
#include <list>
#endif
#ifndef _CONNECTIVITY_ADO_AWRAPADO_HXX_
#include "ado/Awrapado.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

namespace connectivity
{
    namespace ado
    {
        typedef ::cppu::WeakComponentImplHelper5<   ::com::sun::star::sdbc::XStatement,
                                                    ::com::sun::star::sdbc::XWarningsSupplier,
                                                    ::com::sun::star::util::XCancellable,
                                                    ::com::sun::star::sdbc::XCloseable,
                                                    ::com::sun::star::sdbc::XMultipleResults> OStatement_BASE;

        //**************************************************************
        //************ Class: java.sql.Statement
        //**************************************************************
        class OStatement_Base       :   public comphelper::OBaseMutex,
                                        public  OStatement_BASE,
                                        public  ::cppu::OPropertySetHelper,
                                        public  ::comphelper::OPropertyArrayUsageHelper<OStatement_Base>,
                                        public  connectivity::OSubComponent<OStatement_Base, OStatement_BASE>

        {
            friend class connectivity::OSubComponent<OStatement_Base, OStatement_BASE>;
            friend class OResultSet;

            ::com::sun::star::sdbc::SQLWarning          m_aLastWarning;

        protected:
            ::std::list< ::rtl::OUString>               m_aBatchList;

            ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XResultSet>    m_xResultSet;   // The last ResultSet created
                                                                        //  for this Statement

            OConnection*                                m_pConnection;// The owning Connection object
            WpADOCommand                                m_Command;
            WpADORecordset                              m_RecordSet;
            OLEVariant                                  m_RecordsAffected;
            OLEVariant                                  m_Parameters;
            ::std::vector<connectivity::OTypeInfo>      m_aTypeInfo;    // Hashtable containing an entry
                                                                        //  for each row returned by
                                                                        //  DatabaseMetaData.getTypeInfo.
            sal_Int32                                   m_nMaxRows;
            sal_Int32                                   m_nFetchSize;
            LockTypeEnum                                m_eLockType;
            CursorTypeEnum                              m_eCursorType;

            using OStatement_BASE::rBHelper;
        private:

            sal_Int32 getQueryTimeOut()         const throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            sal_Int32 getMaxFieldSize()         const throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            sal_Int32 getMaxRows()              const throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            sal_Int32 getResultSetConcurrency() const throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            sal_Int32 getResultSetType()        const throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            sal_Int32 getFetchDirection()       const throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            sal_Int32 getFetchSize()            const throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            ::rtl::OUString getCursorName()     const throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

            void setQueryTimeOut(sal_Int32 _par0)           throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            void setMaxFieldSize(sal_Int32 _par0)           throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            void setMaxRows(sal_Int32 _par0)                throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            void setResultSetConcurrency(sal_Int32 _par0)   throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            void setResultSetType(sal_Int32 _par0)          throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            void setFetchDirection(sal_Int32 _par0)         throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            void setFetchSize(sal_Int32 _par0)              throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            void setCursorName(const ::rtl::OUString &_par0) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

        protected:

            void assignRecordSet( ADORecordset* _pRS );

            void reset () throw( ::com::sun::star::sdbc::SQLException);
            void clearMyResultSet () throw( ::com::sun::star::sdbc::SQLException);
            void setWarning (const  ::com::sun::star::sdbc::SQLWarning &ex) throw( ::com::sun::star::sdbc::SQLException);
            sal_Int32 getColumnCount () throw( ::com::sun::star::sdbc::SQLException);
            sal_Int32 getRowCount () throw( ::com::sun::star::sdbc::SQLException);
            sal_Int32 getPrecision ( sal_Int32 sqlType);

            void disposeResultSet();

            // OPropertyArrayUsageHelper
            virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;
            // OPropertySetHelper
            virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();
            virtual sal_Bool SAL_CALL convertFastPropertyValue(
                                ::com::sun::star::uno::Any & rConvertedValue,
                                ::com::sun::star::uno::Any & rOldValue,
                                sal_Int32 nHandle,
                                const ::com::sun::star::uno::Any& rValue )
                                    throw (::com::sun::star::lang::IllegalArgumentException);
            virtual void SAL_CALL setFastPropertyValue_NoBroadcast(
                                    sal_Int32 nHandle,
                                    const ::com::sun::star::uno::Any& rValue
                                    )
                                    throw (::com::sun::star::uno::Exception);
            virtual void SAL_CALL getFastPropertyValue(
                                    ::com::sun::star::uno::Any& rValue,
                                    sal_Int32 nHandle
                                    ) const;
        public:
            OStatement_Base(OConnection* _pConnection );

            using OStatement_BASE::operator ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >;
            // OComponentHelper
            virtual void SAL_CALL disposing(void);
            // XInterface
            virtual void SAL_CALL acquire() throw();
            virtual void SAL_CALL release() throw();
            virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
            //XTypeProvider
            virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(  ) throw(::com::sun::star::uno::RuntimeException);

            // XPropertySet
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException);
            // XStatement
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL executeQuery( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ;
            virtual sal_Int32 SAL_CALL executeUpdate( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ;
            virtual sal_Bool SAL_CALL execute( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ;
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ;
            // XWarningsSupplier
            virtual ::com::sun::star::uno::Any SAL_CALL getWarnings(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL clearWarnings(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            // XCancellable
            virtual void SAL_CALL cancel(  ) throw(::com::sun::star::uno::RuntimeException);
            // XCloseable
            virtual void SAL_CALL close(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            // XMultipleResults
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getResultSet(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getUpdateCount(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL getMoreResults(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        };

        class OStatement :  public OStatement_Base,
                            public ::com::sun::star::sdbc::XBatchExecution,
                            public ::com::sun::star::lang::XServiceInfo
        {
        public:
            // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
            OStatement( OConnection* _pConnection) : OStatement_Base( _pConnection){};
            ~OStatement();

            DECLARE_SERVICE_INFO();

            virtual void SAL_CALL acquire() throw();
            virtual void SAL_CALL release() throw();
            virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
            // XBatchExecution
            virtual void SAL_CALL addBatch( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL clearBatch(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL executeBatch(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        };
    }
}
#endif // _CONNECTIVITY_ADO_ASTATEMENT_HXX_

<commit_msg>INTEGRATION: CWS ooo19126 (1.8.332); FILE MERGED 2005/09/05 17:25:05 rt 1.8.332.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AStatement.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 06:53:46 $
 *
 *  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_ADO_ASTATEMENT_HXX_
#define _CONNECTIVITY_ADO_ASTATEMENT_HXX_

#ifndef _COM_SUN_STAR_SDBC_XSTATEMENT_HPP_
#include <com/sun/star/sdbc/XStatement.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XWARNINGSSUPPLIER_HPP_
#include <com/sun/star/sdbc/XWarningsSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XMULTIPLERESULTS_HPP_
#include <com/sun/star/sdbc/XMultipleResults.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XBATCHEXECUTION_HPP_
#include <com/sun/star/sdbc/XBatchExecution.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCLOSEABLE_HPP_
#include <com/sun/star/sdbc/XCloseable.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_
#include <com/sun/star/sdbc/SQLWarning.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XCANCELLABLE_HPP_
#include <com/sun/star/util/XCancellable.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE5_HXX_
#include <cppuhelper/compbase5.hxx>
#endif
#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_
#include <comphelper/proparrhlp.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef _CONNECTIVITY_ADO_ACONNECTION_HXX_
#include "ado/AConnection.hxx"
#endif
#ifndef _LIST_
#include <list>
#endif
#ifndef _CONNECTIVITY_ADO_AWRAPADO_HXX_
#include "ado/Awrapado.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

namespace connectivity
{
    namespace ado
    {
        typedef ::cppu::WeakComponentImplHelper5<   ::com::sun::star::sdbc::XStatement,
                                                    ::com::sun::star::sdbc::XWarningsSupplier,
                                                    ::com::sun::star::util::XCancellable,
                                                    ::com::sun::star::sdbc::XCloseable,
                                                    ::com::sun::star::sdbc::XMultipleResults> OStatement_BASE;

        //**************************************************************
        //************ Class: java.sql.Statement
        //**************************************************************
        class OStatement_Base       :   public comphelper::OBaseMutex,
                                        public  OStatement_BASE,
                                        public  ::cppu::OPropertySetHelper,
                                        public  ::comphelper::OPropertyArrayUsageHelper<OStatement_Base>,
                                        public  connectivity::OSubComponent<OStatement_Base, OStatement_BASE>

        {
            friend class connectivity::OSubComponent<OStatement_Base, OStatement_BASE>;
            friend class OResultSet;

            ::com::sun::star::sdbc::SQLWarning          m_aLastWarning;

        protected:
            ::std::list< ::rtl::OUString>               m_aBatchList;

            ::com::sun::star::uno::WeakReference< ::com::sun::star::sdbc::XResultSet>    m_xResultSet;   // The last ResultSet created
                                                                        //  for this Statement

            OConnection*                                m_pConnection;// The owning Connection object
            WpADOCommand                                m_Command;
            WpADORecordset                              m_RecordSet;
            OLEVariant                                  m_RecordsAffected;
            OLEVariant                                  m_Parameters;
            ::std::vector<connectivity::OTypeInfo>      m_aTypeInfo;    // Hashtable containing an entry
                                                                        //  for each row returned by
                                                                        //  DatabaseMetaData.getTypeInfo.
            sal_Int32                                   m_nMaxRows;
            sal_Int32                                   m_nFetchSize;
            LockTypeEnum                                m_eLockType;
            CursorTypeEnum                              m_eCursorType;

            using OStatement_BASE::rBHelper;
        private:

            sal_Int32 getQueryTimeOut()         const throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            sal_Int32 getMaxFieldSize()         const throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            sal_Int32 getMaxRows()              const throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            sal_Int32 getResultSetConcurrency() const throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            sal_Int32 getResultSetType()        const throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            sal_Int32 getFetchDirection()       const throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            sal_Int32 getFetchSize()            const throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            ::rtl::OUString getCursorName()     const throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

            void setQueryTimeOut(sal_Int32 _par0)           throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            void setMaxFieldSize(sal_Int32 _par0)           throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            void setMaxRows(sal_Int32 _par0)                throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            void setResultSetConcurrency(sal_Int32 _par0)   throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            void setResultSetType(sal_Int32 _par0)          throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            void setFetchDirection(sal_Int32 _par0)         throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            void setFetchSize(sal_Int32 _par0)              throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            void setCursorName(const ::rtl::OUString &_par0) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

        protected:

            void assignRecordSet( ADORecordset* _pRS );

            void reset () throw( ::com::sun::star::sdbc::SQLException);
            void clearMyResultSet () throw( ::com::sun::star::sdbc::SQLException);
            void setWarning (const  ::com::sun::star::sdbc::SQLWarning &ex) throw( ::com::sun::star::sdbc::SQLException);
            sal_Int32 getColumnCount () throw( ::com::sun::star::sdbc::SQLException);
            sal_Int32 getRowCount () throw( ::com::sun::star::sdbc::SQLException);
            sal_Int32 getPrecision ( sal_Int32 sqlType);

            void disposeResultSet();

            // OPropertyArrayUsageHelper
            virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;
            // OPropertySetHelper
            virtual ::cppu::IPropertyArrayHelper & SAL_CALL getInfoHelper();
            virtual sal_Bool SAL_CALL convertFastPropertyValue(
                                ::com::sun::star::uno::Any & rConvertedValue,
                                ::com::sun::star::uno::Any & rOldValue,
                                sal_Int32 nHandle,
                                const ::com::sun::star::uno::Any& rValue )
                                    throw (::com::sun::star::lang::IllegalArgumentException);
            virtual void SAL_CALL setFastPropertyValue_NoBroadcast(
                                    sal_Int32 nHandle,
                                    const ::com::sun::star::uno::Any& rValue
                                    )
                                    throw (::com::sun::star::uno::Exception);
            virtual void SAL_CALL getFastPropertyValue(
                                    ::com::sun::star::uno::Any& rValue,
                                    sal_Int32 nHandle
                                    ) const;
        public:
            OStatement_Base(OConnection* _pConnection );

            using OStatement_BASE::operator ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >;
            // OComponentHelper
            virtual void SAL_CALL disposing(void);
            // XInterface
            virtual void SAL_CALL acquire() throw();
            virtual void SAL_CALL release() throw();
            virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
            //XTypeProvider
            virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(  ) throw(::com::sun::star::uno::RuntimeException);

            // XPropertySet
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException);
            // XStatement
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL executeQuery( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ;
            virtual sal_Int32 SAL_CALL executeUpdate( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ;
            virtual sal_Bool SAL_CALL execute( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ;
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL getConnection(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException) ;
            // XWarningsSupplier
            virtual ::com::sun::star::uno::Any SAL_CALL getWarnings(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL clearWarnings(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            // XCancellable
            virtual void SAL_CALL cancel(  ) throw(::com::sun::star::uno::RuntimeException);
            // XCloseable
            virtual void SAL_CALL close(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            // XMultipleResults
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL getResultSet(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getUpdateCount(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL getMoreResults(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        };

        class OStatement :  public OStatement_Base,
                            public ::com::sun::star::sdbc::XBatchExecution,
                            public ::com::sun::star::lang::XServiceInfo
        {
        public:
            // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
            OStatement( OConnection* _pConnection) : OStatement_Base( _pConnection){};
            ~OStatement();

            DECLARE_SERVICE_INFO();

            virtual void SAL_CALL acquire() throw();
            virtual void SAL_CALL release() throw();
            virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
            // XBatchExecution
            virtual void SAL_CALL addBatch( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL clearBatch(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Sequence< sal_Int32 > SAL_CALL executeBatch(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        };
    }
}
#endif // _CONNECTIVITY_ADO_ASTATEMENT_HXX_

<|endoftext|>


<commit_before>#include "toast/net/socket.hpp"
#include "toast/ipc.hpp"
#include "toast/logger.hpp"

#include <thread>
#include <map>
#include <regex>
#include <queue>

#include "toast/crash.hpp"
#include "toast/concurrent/mutex.hpp"
#include "toast/concurrent/condition.hpp"

using namespace Toast;

static bool started = false;
static Logger _log("Toast-IPC");
static Net::Socket::SOCKET sock;
static std::thread read_thread;
static std::map<long, std::tuple<std::string, IPC::MessageListener, void *> > listeners;
static std::queue<long> remove_queue;
static long id = 0;

static Net::Socket::SocketAddress temp_addr("127.0.0.1", 6300);
static Net::Socket::SocketAddress temp_addr_recv;
static int my_module_idx = 0;

static char message[4096];
static Concurrent::Mutex mtx_send;
static uint8_t ack_id;
static Concurrent::ConditionVariable ack_cond;
static uint8_t ack_response_id = -1;
static int8_t ack_response_module = -2;	// Set this to -2 so the first wait doesn't default to true for bootstrap messages

static void read_thread_func() {
	char msg[4096];
	char ack_msg[10];
#ifdef OS_WIN
	int *ptr = temp_addr_recv.raw_address_len_ptr();
#else
	unsigned int *ptr = (unsigned int *)temp_addr_recv.raw_address_len_ptr();
#endif
	while (1) {
		int len = ::recvfrom(sock, &msg[0], 4096, 0, (struct sockaddr *)temp_addr_recv.raw_address(), ptr);
		int source_module = (int8_t)msg[0];
		int handle_len = (uint8_t)msg[1];
		bool ack = (uint8_t)(msg[2]) != 0;
		char *handle_chars = &msg[3];
		std::string handle(handle_chars, handle_len);

		if (len == -1) {
			_log.error("IPC Socket Receive Error: " + std::to_string(Net::Socket::socket_last_error()));
		}

		if (handle == IPC::HANDLE_ACK) {
			ack_response_module = source_module;
			ack_response_id = msg[2];
			ack_cond.signal_all();
			continue;
		}

		while (!remove_queue.empty()) {
			listeners.erase(remove_queue.front());
			remove_queue.pop();
		}

		for (auto it = listeners.begin(); it != listeners.end(); it++) {
			auto entry = *it;
			std::string s = std::get<0>(entry.second);
			IPC::MessageListener l = std::get<1>(entry.second);
			void *param = std::get<2>(entry.second);
			if (handle == s) {
				l(handle, (void *)&msg[2 + handle_len], len - handle_len - 2, source_module, param);	// Call the listener
			}
		}

		if (ack) {
			mtx_send.lock();
			temp_addr.set_port(6300 + source_module + 1);
			ack_msg[0] = my_module_idx;
			ack_msg[1] = IPC::HANDLE_ACK.length();
			ack_msg[2] = msg[2];
			memcpy(ack_msg + 3, IPC::HANDLE_ACK.c_str(), IPC::HANDLE_ACK.length());
			int ret = ::sendto(sock, ack_msg, 3 + IPC::HANDLE_ACK.length(), 0, (struct sockaddr *)temp_addr.raw_address(), temp_addr.raw_address_length());
			if (ret == -1) {
				_log.error("IPC Socket ACK Error: " + std::to_string(Net::Socket::socket_last_error()));
			}
			mtx_send.unlock();
		}
	}
}

void IPC::start(int module_id) {
	if (!started) {
		my_module_idx = module_id;
		sock = Net::Socket::socket_udp_create();

		struct sockaddr_in addr;
		addr.sin_family = AF_INET;
		addr.sin_addr.s_addr = inet_addr("127.0.0.1");
		addr.sin_port = htons(6300 + module_id + 1);	// Bootstrap is module_id=-1, therefore port 6300
		if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
			_log.error("Could not bind UDP socket to localhost!");
			return;
		}

		read_thread = std::thread(read_thread_func);
		read_thread.detach();

		started = true;
	}
}

void IPC::send(std::string handle, void *data, int data_length) {
	IPC::sendto(handle, data, data_length, -1);
}

void IPC::broadcast(std::string handle, void *data, int data_length, bool bootstrap) {
	if (bootstrap) IPC::sendto(handle, data, data_length, -1);
	for (ModuleData mdata : get_all_modules()) {
		IPC::sendto(handle, data, data_length, mdata.module_idx);
	}
}

// TODO Send w/ ack, use condition var

void IPC::sendto(std::string handle, void *data, int data_length, int module_idx) {
	mtx_send.lock();
	temp_addr.set_port(6300 + module_idx + 1);
	int total_length = handle.length() + data_length + 3;
	message[0] = (int8_t)(my_module_idx);
	message[1] = (uint8_t)(handle.length());
	message[2] = 0;
	memcpy(message + 3, handle.c_str(), handle.length());
	if (data_length > 0 && data != NULL)
		memcpy(message + 3 + handle.length(), data, data_length);
	int ret = ::sendto(sock, message, total_length, 0, (struct sockaddr *)temp_addr.raw_address(), temp_addr.raw_address_length());
	if (ret == -1) {
		_log.error("IPC Socket Send Error: " + std::to_string(Net::Socket::socket_last_error()));
	}
	mtx_send.unlock();
}

void IPC::send_with_ack(std::string handle, void *data, int data_length, int module_idx) {
	mtx_send.lock();

	// We can't have this be 0 otherwise we don't detect it as an ACK packet
	ack_id++;
	if (ack_id == 0) ack_id++;
	uint8_t aid = ack_id;

	temp_addr.set_port(6300 + module_idx + 1);
	int total_length = handle.length() + data_length + 3;
	message[0] = (int8_t)(my_module_idx);
	message[1] = (uint8_t)(handle.length());
	message[2] = aid;
	memcpy(message + 3, handle.c_str(), handle.length());
	if (data_length > 0 && data != NULL)
		memcpy(message + 3 + handle.length(), data, data_length);
	int ret = ::sendto(sock, message, total_length, 0, (struct sockaddr *)temp_addr.raw_address(), temp_addr.raw_address_length());
	if (ret == -1) {
		_log.error("IPC Socket Send Error: " + std::to_string(Net::Socket::socket_last_error()));
	}
	mtx_send.unlock();

	ack_cond.lock();
	while (ack_response_id != aid || ack_response_module != module_idx) {
		ack_cond.wait();
	}
	ack_cond.unlock();
}

long IPC::listen(std::string handle, IPC::MessageListener listener, void *param) {
	int i = id++;
	listeners[i] = std::make_tuple(handle, listener, param);
	return i;
}

void IPC::stop_listening(long id) {
	remove_queue.push(id);
}<commit_msg>Fix slight issue with IPC w/ extra data<commit_after>#include "toast/net/socket.hpp"
#include "toast/ipc.hpp"
#include "toast/logger.hpp"

#include <thread>
#include <map>
#include <regex>
#include <queue>

#include "toast/crash.hpp"
#include "toast/concurrent/mutex.hpp"
#include "toast/concurrent/condition.hpp"

using namespace Toast;

static bool started = false;
static Logger _log("Toast-IPC");
static Net::Socket::SOCKET sock;
static std::thread read_thread;
static std::map<long, std::tuple<std::string, IPC::MessageListener, void *> > listeners;
static std::queue<long> remove_queue;
static long id = 0;

static Net::Socket::SocketAddress temp_addr("127.0.0.1", 6300);
static Net::Socket::SocketAddress temp_addr_recv;
static int my_module_idx = 0;

static char message[4096];
static Concurrent::Mutex mtx_send;
static uint8_t ack_id;
static Concurrent::ConditionVariable ack_cond;
static uint8_t ack_response_id = -1;
static int8_t ack_response_module = -2;	// Set this to -2 so the first wait doesn't default to true for bootstrap messages

static void read_thread_func() {
	char msg[4096];
	char ack_msg[10];
#ifdef OS_WIN
	int *ptr = temp_addr_recv.raw_address_len_ptr();
#else
	unsigned int *ptr = (unsigned int *)temp_addr_recv.raw_address_len_ptr();
#endif
	while (1) {
		int len = ::recvfrom(sock, &msg[0], 4096, 0, (struct sockaddr *)temp_addr_recv.raw_address(), ptr);
		int source_module = (int8_t)msg[0];
		int handle_len = (uint8_t)msg[1];
		bool ack = (uint8_t)(msg[2]) != 0;
		char *handle_chars = &msg[3];
		std::string handle(handle_chars, handle_len);

		if (len == -1) {
			_log.error("IPC Socket Receive Error: " + std::to_string(Net::Socket::socket_last_error()));
		}

		if (handle == IPC::HANDLE_ACK) {
			ack_response_module = source_module;
			ack_response_id = msg[2];
			ack_cond.signal_all();
			continue;
		}

		while (!remove_queue.empty()) {
			listeners.erase(remove_queue.front());
			remove_queue.pop();
		}

		for (auto it = listeners.begin(); it != listeners.end(); it++) {
			auto entry = *it;
			std::string s = std::get<0>(entry.second);
			IPC::MessageListener l = std::get<1>(entry.second);
			void *param = std::get<2>(entry.second);
			if (handle == s) {
				l(handle, (void *)&msg[3 + handle_len], len - handle_len - 2, source_module, param);	// Call the listener
			}
		}

		if (ack) {
			mtx_send.lock();
			temp_addr.set_port(6300 + source_module + 1);
			ack_msg[0] = my_module_idx;
			ack_msg[1] = IPC::HANDLE_ACK.length();
			ack_msg[2] = msg[2];
			memcpy(ack_msg + 3, IPC::HANDLE_ACK.c_str(), IPC::HANDLE_ACK.length());
			int ret = ::sendto(sock, ack_msg, 3 + IPC::HANDLE_ACK.length(), 0, (struct sockaddr *)temp_addr.raw_address(), temp_addr.raw_address_length());
			if (ret == -1) {
				_log.error("IPC Socket ACK Error: " + std::to_string(Net::Socket::socket_last_error()));
			}
			mtx_send.unlock();
		}
	}
}

void IPC::start(int module_id) {
	if (!started) {
		my_module_idx = module_id;
		sock = Net::Socket::socket_udp_create();

		struct sockaddr_in addr;
		addr.sin_family = AF_INET;
		addr.sin_addr.s_addr = inet_addr("127.0.0.1");
		addr.sin_port = htons(6300 + module_id + 1);	// Bootstrap is module_id=-1, therefore port 6300
		if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
			_log.error("Could not bind UDP socket to localhost!");
			return;
		}

		read_thread = std::thread(read_thread_func);
		read_thread.detach();

		started = true;
	}
}

void IPC::send(std::string handle, void *data, int data_length) {
	IPC::sendto(handle, data, data_length, -1);
}

void IPC::broadcast(std::string handle, void *data, int data_length, bool bootstrap) {
	if (bootstrap) IPC::sendto(handle, data, data_length, -1);
	for (ModuleData mdata : get_all_modules()) {
		IPC::sendto(handle, data, data_length, mdata.module_idx);
	}
}

// TODO Send w/ ack, use condition var

void IPC::sendto(std::string handle, void *data, int data_length, int module_idx) {
	mtx_send.lock();
	temp_addr.set_port(6300 + module_idx + 1);
	int total_length = handle.length() + data_length + 3;
	message[0] = (int8_t)(my_module_idx);
	message[1] = (uint8_t)(handle.length());
	message[2] = 0;
	memcpy(message + 3, handle.c_str(), handle.length());
	if (data_length > 0 && data != NULL)
		memcpy(message + 3 + handle.length(), data, data_length);
	int ret = ::sendto(sock, message, total_length, 0, (struct sockaddr *)temp_addr.raw_address(), temp_addr.raw_address_length());
	if (ret == -1) {
		_log.error("IPC Socket Send Error: " + std::to_string(Net::Socket::socket_last_error()));
	}
	mtx_send.unlock();
}

void IPC::send_with_ack(std::string handle, void *data, int data_length, int module_idx) {
	mtx_send.lock();

	// We can't have this be 0 otherwise we don't detect it as an ACK packet
	ack_id++;
	if (ack_id == 0) ack_id++;
	uint8_t aid = ack_id;

	temp_addr.set_port(6300 + module_idx + 1);
	int total_length = handle.length() + data_length + 3;
	message[0] = (int8_t)(my_module_idx);
	message[1] = (uint8_t)(handle.length());
	message[2] = aid;
	memcpy(message + 3, handle.c_str(), handle.length());
	if (data_length > 0 && data != NULL)
		memcpy(message + 3 + handle.length(), data, data_length);
	int ret = ::sendto(sock, message, total_length, 0, (struct sockaddr *)temp_addr.raw_address(), temp_addr.raw_address_length());
	if (ret == -1) {
		_log.error("IPC Socket Send Error: " + std::to_string(Net::Socket::socket_last_error()));
	}
	mtx_send.unlock();

	ack_cond.lock();
	while (ack_response_id != aid || ack_response_module != module_idx) {
		ack_cond.wait();
	}
	ack_cond.unlock();
}

long IPC::listen(std::string handle, IPC::MessageListener listener, void *param) {
	int i = id++;
	listeners[i] = std::make_tuple(handle, listener, param);
	return i;
}

void IPC::stop_listening(long id) {
	remove_queue.push(id);
}<|endoftext|>


<commit_before>#include <nana/gui.hpp>
#include <nana/gui/widgets/button.hpp>
#include <nana/gui/widgets/textbox.hpp>
#include <nana/gui/widgets/label.hpp>
#include "nlohmann\json.hpp"

#include <iostream>

using namespace std;
using namespace nana;

class TextBoxWrapper
{
public:
	textbox tbx_;	// (fm, rectangle{ 20, 20, 150, 30 });
	string text_;	// text buffer
	label lab_;

	TextBoxWrapper(const form& _fm, const rectangle& _rect_label, const rectangle& _rect_textbox)
		: lab_(_fm, _rect_label), tbx_(_fm, _rect_textbox)
	{
		lab_.caption("int res_x");
		lab_.text_align(align::left, align_v::center);

		tbx_.multi_lines(false);
		tbx_.caption("Hello, Textbox");
		tbx_.events().key_release([&](const nana::arg_keyboard& a_k) {
			if (a_k.key == 13) {
				cout << "Enter Key pressed " << endl;
				cout << this->text_ << endl;
			}
		});

		tbx_.events().text_changed([&](const nana::arg_textbox& a_b) {
			string text_line;
			a_b.widget.getline(0, text_line);
			text_ = text_line;
		});

		tbx_.getline(0, text_);

		cout << text_ << endl;
	}

	void foo(const nana::arg_keyboard& a_k)
	{
		if (a_k.key == 13)
		{
			cout << "Enter Key pressed " << endl;
		}
	}

};

using json = nlohmann::json;

int main()
{
	json j, j2;

	j["type"] = "int";
	j["name"] = "x_res";
	j["value"] = "256";

	j2["variable"] = j;
	j2["variable2"] = j;

	// special iterator member functions for objects
	for (json::iterator it = j.begin(); it != j.end(); ++it) {
		//std::cout << it.key() << " : " << it.value() << "\n";
		cout << it.value().get<string>() << endl;
	}

	form fm;
	fm.caption(L"Hello, World!");

	TextBoxWrapper tbx(fm, rectangle{ 20, 20, 60, 20 }, rectangle{ 100, 20, 150, 20 });

	//textbox tbx(fm, rectangle{ 20, 20, 150, 30 });
	//tbx.caption("Hello, Textbox");
	///*tbx.set_highlight("sqlrev", colors::dark_blue, colors::yellow);
	//tbx.set_keywords("sqlrev", false, true, { "select", "from", "where" });*/
	//tbx.multi_lines(false);
	//tbx.events().key_release(foo);

	// add a button
	button btn(fm, rectangle{ 20, 50, 150, 30 });
	btn.caption(L"Quit");
	btn.events().click(API::exit);

	fm.show();
	exec();
}<commit_msg>scripting::Variable, VariableBase, Manager.<commit_after>#include <nana/gui.hpp>
#include <nana/gui/widgets/button.hpp>
#include <nana/gui/widgets/textbox.hpp>
#include <nana/gui/widgets/label.hpp>
#include "nlohmann\json.hpp"

#include <iostream>

using namespace std;
using namespace nana;

namespace scripting
{
	typedef enum { INT, FLOAT, DOUBLE, STRING, BOOL } VariableType;

	class VariableBase
	{
	public:
		string name_;
		VariableType type_;
	};

	template<class T>
	class Variable : public VariableBase
	{
	public:
		T &v_;

		Variable(T& _v)
			: v_(_v)
		{}
	};

	class Manager
	{
	public:
		map<string, VariableBase*> vars_;
		vector<VariableBase*> vars_vec_; // to remember order

		~Manager()
		{
			for (const auto& itr : vars_vec_)	delete itr;
		}

		void checkIntegrity(const string& name, const VariableType& vt)
		{
			// check if 'name' key exists
			if (vars_.count(name) == 0) {
				cout << __FUNCTION__ << endl;
				cout << "Key " << name << "Not found " << endl;
				exit(1);
			}

			// check if type is correct
			if (vars_[name]->type_ != vt) {
				cout << __FUNCTION__ << endl;
				cout << "Wrong type " << endl;
				exit(1);
			}
		}

		//TODO: implement addNew(..., int/float/double/string/bool)
		void addNew(const string& name, int& v)
		{
			if (vars_.count(name) > 0) {
				cout << __FUNCTION__ << endl;
				cout << "Key " << name << " already exists " << endl;
				exit(1);
			}

			VariableBase *new_var = new Variable<int>(v);

			new_var->name_ = name;
			new_var->type_ = VariableType::INT;

			vars_[name] = new_var;
			vars_vec_.push_back(new_var);
		}

		int& getInt(const string& name)
		{
			checkIntegrity(name, VariableType::INT);

			Variable<int> *var = (Variable<int>*)vars_[name];

			return var->v_;
		}

		//TODO: getFloat, getDouble, getString, getBool
	};
}

class TextBoxWrapper
{
public:
	textbox tbx_;	// (fm, rectangle{ 20, 20, 150, 30 });
	string text_;	// text buffer
	label lab_;

	TextBoxWrapper(const form& _fm, const rectangle& _rect_label, const rectangle& _rect_textbox)
		: lab_(_fm, _rect_label), tbx_(_fm, _rect_textbox)
	{
		lab_.caption("int res_x");
		lab_.text_align(align::left, align_v::center);

		tbx_.multi_lines(false);
		tbx_.caption("Hello, Textbox");
		tbx_.events().key_release([&](const nana::arg_keyboard& a_k) {
			if (a_k.key == 13) {
				cout << "Enter Key pressed " << endl;
				cout << this->text_ << endl;
			}
		});

		tbx_.events().text_changed([&](const nana::arg_textbox& a_b) {
			string text_line;
			a_b.widget.getline(0, text_line);
			text_ = text_line;
		});

		tbx_.getline(0, text_);

		cout << text_ << endl;
	}

	void foo(const nana::arg_keyboard& a_k)
	{
		if (a_k.key == 13)
		{
			cout << "Enter Key pressed " << endl;
		}
	}

};

using json = nlohmann::json;
using namespace scripting;

int main()
{
	json j, j2;

	j["type"] = "int";
	j["name"] = "x_res";
	j["value"] = "256";

	j2["variable"] = j;
	j2["variable2"] = j;

	// special iterator member functions for objects
	for (json::iterator it = j.begin(); it != j.end(); ++it) {
		//std::cout << it.key() << " : " << it.value() << "\n";
		cout << it.value().get<string>() << endl;
	}

	int test_int;
	Manager var_manager;
	var_manager.addNew("zebra", test_int);
	var_manager.addNew("test_int", test_int);
	var_manager.getInt("test_int") = 2048;
	cout << "test_int " << test_int << endl;

	for (const auto& itr : var_manager.vars_)
	{
		cout << itr.first << endl;
	}

	form fm;
	fm.caption(L"Hello, World!");

	TextBoxWrapper tbx(fm, rectangle{ 20, 20, 60, 20 }, rectangle{ 100, 20, 150, 20 });

	//textbox tbx(fm, rectangle{ 20, 20, 150, 30 });
	//tbx.caption("Hello, Textbox");
	///*tbx.set_highlight("sqlrev", colors::dark_blue, colors::yellow);
	//tbx.set_keywords("sqlrev", false, true, { "select", "from", "where" });*/
	//tbx.multi_lines(false);
	//tbx.events().key_release(foo);

	// add a button
	button btn(fm, rectangle{ 20, 50, 150, 30 });
	btn.caption(L"Quit");
	btn.events().click(API::exit);

	fm.show();
	exec();
}<|endoftext|>


<commit_before>/*******************************************************************************
FILE : scene_filters.hpp

LAST MODIFIED : 16 October 2008

DESCRIPTION :
==============================================================================*/
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is cmgui.
 *
 * The Initial Developer of the Original Code is
 * Auckland Uniservices Ltd, Auckland, New Zealand.
 * Portions created by the Initial Developer are Copyright (C) 2005
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#ifndef SCENE_FILTERS_HPP
#define SCENE_FILTERS_HPP

#include <map>
#include <string>

template <typename ObjectType>
class SceneFiltersBaseFunctor
{
protected:
  int inclusive;
public:
  virtual int call(ObjectType object) = 0;

  virtual ~SceneFiltersBaseFunctor()
  {
  };
};

template <typename ObjectType>
class SceneFiltersNoValueFunctor :  public SceneFiltersBaseFunctor<ObjectType>
{
private:
  int(*fpt)(ObjectType);
public:

  SceneFiltersNoValueFunctor(int(*fpt_in)(ObjectType), int inclusive_in)
  { fpt=fpt_in; inclusive=inclusive_in;};

  virtual int call(ObjectType object)
  {
  	if (fpt)
  		return inclusive == (*fpt)(object);
  	else
  		return 0;
  }

  ~SceneFiltersNoValueFunctor()
  {
  };
};

template <typename ObjectType, typename ValueType> class SceneFiltersValueFunctor :
  public SceneFiltersBaseFunctor<ObjectType>
{
private:
  int(*fpt)(ObjectType, ValueType);
  int inclusive;
  ValueType value;

public:

  SceneFiltersValueFunctor(int(*fpt_in)(ObjectType, ValueType),
  	ValueType value_in, int inclusive_in)
  { fpt=fpt_in; value=value_in; inclusive=inclusive_in;};

  virtual int call(ObjectType object)
  {
  	if (fpt)
  		return inclusive == (*fpt)(object, value);
  	else
  		return 0;
  };             // execute member function

  ~SceneFiltersValueFunctor()
  {
  };

};

typedef std::multimap<std::string, void *> Filtering_list;
typedef std::multimap<std::string, void *>::iterator Filtering_list_iterator;

#endif /* SCENE_FILTERS_HPP_ */
<commit_msg>Adding this pointer to uses of inclusive and changing spaces for tabs.<commit_after>/*******************************************************************************
FILE : scene_filters.hpp

LAST MODIFIED : 16 October 2008

DESCRIPTION :
==============================================================================*/
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is cmgui.
 *
 * The Initial Developer of the Original Code is
 * Auckland Uniservices Ltd, Auckland, New Zealand.
 * Portions created by the Initial Developer are Copyright (C) 2005
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#ifndef SCENE_FILTERS_HPP
#define SCENE_FILTERS_HPP

#include <map>
#include <string>

template <typename ObjectType>
class SceneFiltersBaseFunctor
{
protected:
	int inclusive;

public:
	SceneFiltersBaseFunctor(int inclusive_in)
		: inclusive(inclusive_in)
	{
	}

	virtual ~SceneFiltersBaseFunctor()
	{
	}

	virtual int call(ObjectType object) = 0;

};

template <typename ObjectType>
class SceneFiltersNoValueFunctor :  public SceneFiltersBaseFunctor<ObjectType>
{
private:
	int(*fpt)(ObjectType);

public:
	SceneFiltersNoValueFunctor(int(*fpt_in)(ObjectType), int inclusive_in)
		: SceneFiltersBaseFunctor<ObjectType>(inclusive_in)
		, fpt(fpt_in)
	{}

	virtual int call(ObjectType object)
	{
		if (fpt)
			return this->inclusive == (*fpt)(object);
		else
			return 0;
	}

	~SceneFiltersNoValueFunctor()
	{
	}

};

template <typename ObjectType, typename ValueType> class SceneFiltersValueFunctor :
	public SceneFiltersBaseFunctor<ObjectType>
{
private:
	int(*fpt)(ObjectType, ValueType);
	ValueType value;

public:

	SceneFiltersValueFunctor(int(*fpt_in)(ObjectType, ValueType),
		ValueType value_in, int inclusive_in)
		: SceneFiltersBaseFunctor<ObjectType>(inclusive_in)
		, fpt(fpt_in)
		, value(value_in)
	{
	}

	virtual int call(ObjectType object)
	{
		if (fpt)
			return this->inclusive == (*fpt)(object, value);
		else
			return 0;
	} // execute member function

	~SceneFiltersValueFunctor()
	{
	}

};

typedef std::multimap<std::string, void *> Filtering_list;
typedef std::multimap<std::string, void *>::iterator Filtering_list_iterator;

#endif /* SCENE_FILTERS_HPP_ */
<|endoftext|>


<commit_before>// Copyright (c) 2013 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/common/sandbox_linux/bpf_gpu_policy_linux.h"

#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include <string>
#include <vector>

#include "base/bind.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "build/build_config.h"
#include "content/common/sandbox_linux/sandbox_bpf_base_policy_linux.h"
#include "content/common/sandbox_linux/sandbox_seccomp_bpf_linux.h"
#include "content/common/set_process_title.h"
#include "content/public/common/content_switches.h"
#include "sandbox/linux/seccomp-bpf-helpers/syscall_sets.h"
#include "sandbox/linux/seccomp-bpf/trap.h"
#include "sandbox/linux/services/broker_process.h"
#include "sandbox/linux/services/linux_syscalls.h"

using sandbox::BrokerProcess;
using sandbox::SyscallSets;
using sandbox::arch_seccomp_data;
using sandbox::bpf_dsl::Allow;
using sandbox::bpf_dsl::ResultExpr;

namespace content {

namespace {

inline bool IsChromeOS() {
#if defined(OS_CHROMEOS)
  return true;
#else
  return false;
#endif
}

inline bool IsArchitectureX86_64() {
#if defined(__x86_64__)
  return true;
#else
  return false;
#endif
}

inline bool IsArchitectureI386() {
#if defined(__i386__)
  return true;
#else
  return false;
#endif
}

inline bool IsArchitectureArm() {
#if defined(__arm__)
  return true;
#else
  return false;
#endif
}

bool IsAcceleratedVideoEnabled() {
  const base::CommandLine& command_line =
      *base::CommandLine::ForCurrentProcess();
  bool accelerated_encode_enabled = false;
#if defined(OS_CHROMEOS)
  accelerated_encode_enabled =
      !command_line.HasSwitch(switches::kDisableVaapiAcceleratedVideoEncode);
#endif
  return !command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode) ||
         accelerated_encode_enabled;
}

intptr_t GpuSIGSYS_Handler(const struct arch_seccomp_data& args,
                           void* aux_broker_process) {
  RAW_CHECK(aux_broker_process);
  BrokerProcess* broker_process =
      static_cast<BrokerProcess*>(aux_broker_process);
  switch (args.nr) {
    case __NR_access:
      return broker_process->Access(reinterpret_cast<const char*>(args.args[0]),
                                    static_cast<int>(args.args[1]));
    case __NR_open:
#if defined(MEMORY_SANITIZER)
      // http://crbug.com/372840
      __msan_unpoison_string(reinterpret_cast<const char*>(args.args[0]));
#endif
      return broker_process->Open(reinterpret_cast<const char*>(args.args[0]),
                                  static_cast<int>(args.args[1]));
    case __NR_openat:
      // Allow using openat() as open().
      if (static_cast<int>(args.args[0]) == AT_FDCWD) {
        return
            broker_process->Open(reinterpret_cast<const char*>(args.args[1]),
                                 static_cast<int>(args.args[2]));
      } else {
        return -EPERM;
      }
    default:
      RAW_CHECK(false);
      return -ENOSYS;
  }
}

class GpuBrokerProcessPolicy : public GpuProcessPolicy {
 public:
  static sandbox::bpf_dsl::SandboxBPFDSLPolicy* Create() {
    return new GpuBrokerProcessPolicy();
  }
  virtual ~GpuBrokerProcessPolicy() {}

  virtual ResultExpr EvaluateSyscall(int system_call_number) const OVERRIDE;

 private:
  GpuBrokerProcessPolicy() {}
  DISALLOW_COPY_AND_ASSIGN(GpuBrokerProcessPolicy);
};

// x86_64/i386 or desktop ARM.
// A GPU broker policy is the same as a GPU policy with open and
// openat allowed.
ResultExpr GpuBrokerProcessPolicy::EvaluateSyscall(int sysno) const {
  switch (sysno) {
    case __NR_access:
    case __NR_open:
    case __NR_openat:
      return Allow();
    default:
      return GpuProcessPolicy::EvaluateSyscall(sysno);
  }
}

void UpdateProcessTypeToGpuBroker() {
  base::CommandLine::StringVector exec =
      base::CommandLine::ForCurrentProcess()->GetArgs();
  base::CommandLine::Reset();
  base::CommandLine::Init(0, NULL);
  base::CommandLine::ForCurrentProcess()->InitFromArgv(exec);
  base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
      switches::kProcessType, "gpu-broker");

  // Update the process title. The argv was already cached by the call to
  // SetProcessTitleFromCommandLine in content_main_runner.cc, so we can pass
  // NULL here (we don't have the original argv at this point).
  SetProcessTitleFromCommandLine(NULL);
}

bool UpdateProcessTypeAndEnableSandbox(sandbox::bpf_dsl::SandboxBPFDSLPolicy* (
    *broker_sandboxer_allocator)(void)) {
  DCHECK(broker_sandboxer_allocator);
  UpdateProcessTypeToGpuBroker();
  return SandboxSeccompBPF::StartSandboxWithExternalPolicy(
      make_scoped_ptr(broker_sandboxer_allocator()));
}

}  // namespace

GpuProcessPolicy::GpuProcessPolicy() : broker_process_(NULL) {}

GpuProcessPolicy::~GpuProcessPolicy() {}

// Main policy for x86_64/i386. Extended by CrosArmGpuProcessPolicy.
ResultExpr GpuProcessPolicy::EvaluateSyscall(int sysno) const {
  switch (sysno) {
    case __NR_ioctl:
#if defined(__i386__) || defined(__x86_64__) || defined(__mips__)
    // The Nvidia driver uses flags not in the baseline policy
    // (MAP_LOCKED | MAP_EXECUTABLE | MAP_32BIT)
    case __NR_mmap:
#endif
    // We also hit this on the linux_chromeos bot but don't yet know what
    // weird flags were involved.
    case __NR_mprotect:
    // TODO(jln): restrict prctl.
    case __NR_prctl:
    case __NR_sched_getaffinity:
    case __NR_sched_setaffinity:
    case __NR_setpriority:
      return Allow();
    case __NR_access:
    case __NR_open:
    case __NR_openat:
      DCHECK(broker_process_);
      return Trap(GpuSIGSYS_Handler, broker_process_);
    default:
      if (SyscallSets::IsEventFd(sysno))
        return Allow();

      // Default on the baseline policy.
      return SandboxBPFBasePolicy::EvaluateSyscall(sysno);
  }
}

bool GpuProcessPolicy::PreSandboxHook() {
  // Warm up resources needed by the policy we're about to enable and
  // eventually start a broker process.
  const bool chromeos_arm_gpu = IsChromeOS() && IsArchitectureArm();
  // This policy is for x86 or Desktop.
  DCHECK(!chromeos_arm_gpu);

  DCHECK(!broker_process());
  // Create a new broker process.
  InitGpuBrokerProcess(
      GpuBrokerProcessPolicy::Create,
      std::vector<std::string>(),  // No extra files in whitelist.
      std::vector<std::string>());

  if (IsArchitectureX86_64() || IsArchitectureI386()) {
    // Accelerated video dlopen()'s some shared objects
    // inside the sandbox, so preload them now.
    if (IsAcceleratedVideoEnabled()) {
      const char* I965DrvVideoPath = NULL;

      if (IsArchitectureX86_64()) {
        I965DrvVideoPath = "/usr/lib64/va/drivers/i965_drv_video.so";
      } else if (IsArchitectureI386()) {
        I965DrvVideoPath = "/usr/lib/va/drivers/i965_drv_video.so";
      }

      dlopen(I965DrvVideoPath, RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE);
      dlopen("libva.so.1", RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE);
      dlopen("libva-x11.so.1", RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE);
    }
  }

  return true;
}

void GpuProcessPolicy::InitGpuBrokerProcess(
    sandbox::bpf_dsl::SandboxBPFDSLPolicy* (*broker_sandboxer_allocator)(void),
    const std::vector<std::string>& read_whitelist_extra,
    const std::vector<std::string>& write_whitelist_extra) {
  static const char kDriRcPath[] = "/etc/drirc";
  static const char kDriCard0Path[] = "/dev/dri/card0";

  CHECK(broker_process_ == NULL);

  // All GPU process policies need these files brokered out.
  std::vector<std::string> read_whitelist;
  read_whitelist.push_back(kDriCard0Path);
  read_whitelist.push_back(kDriRcPath);
  // Add eventual extra files from read_whitelist_extra.
  read_whitelist.insert(read_whitelist.end(),
                        read_whitelist_extra.begin(),
                        read_whitelist_extra.end());

  std::vector<std::string> write_whitelist;
  write_whitelist.push_back(kDriCard0Path);
  // Add eventual extra files from write_whitelist_extra.
  write_whitelist.insert(write_whitelist.end(),
                         write_whitelist_extra.begin(),
                         write_whitelist_extra.end());

  broker_process_ = new BrokerProcess(GetFSDeniedErrno(),
                                      read_whitelist,
                                      write_whitelist);
  // The initialization callback will perform generic initialization and then
  // call broker_sandboxer_callback.
  CHECK(broker_process_->Init(base::Bind(&UpdateProcessTypeAndEnableSandbox,
                                         broker_sandboxer_allocator)));
}

}  // namespace content
<commit_msg>[Tizen] Hard code for va driver<commit_after>// Copyright (c) 2013 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/common/sandbox_linux/bpf_gpu_policy_linux.h"

#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include <string>
#include <vector>

#include "base/bind.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "build/build_config.h"
#include "content/common/sandbox_linux/sandbox_bpf_base_policy_linux.h"
#include "content/common/sandbox_linux/sandbox_seccomp_bpf_linux.h"
#include "content/common/set_process_title.h"
#include "content/public/common/content_switches.h"
#include "sandbox/linux/seccomp-bpf-helpers/syscall_sets.h"
#include "sandbox/linux/seccomp-bpf/trap.h"
#include "sandbox/linux/services/broker_process.h"
#include "sandbox/linux/services/linux_syscalls.h"

using sandbox::BrokerProcess;
using sandbox::SyscallSets;
using sandbox::arch_seccomp_data;
using sandbox::bpf_dsl::Allow;
using sandbox::bpf_dsl::ResultExpr;

namespace content {

namespace {

inline bool IsChromeOS() {
#if defined(OS_CHROMEOS)
  return true;
#else
  return false;
#endif
}

inline bool IsArchitectureX86_64() {
#if defined(__x86_64__)
  return true;
#else
  return false;
#endif
}

inline bool IsArchitectureI386() {
#if defined(__i386__)
  return true;
#else
  return false;
#endif
}

inline bool IsArchitectureArm() {
#if defined(__arm__)
  return true;
#else
  return false;
#endif
}

bool IsAcceleratedVideoEnabled() {
  const base::CommandLine& command_line =
      *base::CommandLine::ForCurrentProcess();
  bool accelerated_encode_enabled = false;
#if defined(OS_CHROMEOS)
  accelerated_encode_enabled =
      !command_line.HasSwitch(switches::kDisableVaapiAcceleratedVideoEncode);
#endif
  return !command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode) ||
         accelerated_encode_enabled;
}

intptr_t GpuSIGSYS_Handler(const struct arch_seccomp_data& args,
                           void* aux_broker_process) {
  RAW_CHECK(aux_broker_process);
  BrokerProcess* broker_process =
      static_cast<BrokerProcess*>(aux_broker_process);
  switch (args.nr) {
    case __NR_access:
      return broker_process->Access(reinterpret_cast<const char*>(args.args[0]),
                                    static_cast<int>(args.args[1]));
    case __NR_open:
#if defined(MEMORY_SANITIZER)
      // http://crbug.com/372840
      __msan_unpoison_string(reinterpret_cast<const char*>(args.args[0]));
#endif
      return broker_process->Open(reinterpret_cast<const char*>(args.args[0]),
                                  static_cast<int>(args.args[1]));
    case __NR_openat:
      // Allow using openat() as open().
      if (static_cast<int>(args.args[0]) == AT_FDCWD) {
        return
            broker_process->Open(reinterpret_cast<const char*>(args.args[1]),
                                 static_cast<int>(args.args[2]));
      } else {
        return -EPERM;
      }
    default:
      RAW_CHECK(false);
      return -ENOSYS;
  }
}

class GpuBrokerProcessPolicy : public GpuProcessPolicy {
 public:
  static sandbox::bpf_dsl::SandboxBPFDSLPolicy* Create() {
    return new GpuBrokerProcessPolicy();
  }
  virtual ~GpuBrokerProcessPolicy() {}

  virtual ResultExpr EvaluateSyscall(int system_call_number) const OVERRIDE;

 private:
  GpuBrokerProcessPolicy() {}
  DISALLOW_COPY_AND_ASSIGN(GpuBrokerProcessPolicy);
};

// x86_64/i386 or desktop ARM.
// A GPU broker policy is the same as a GPU policy with open and
// openat allowed.
ResultExpr GpuBrokerProcessPolicy::EvaluateSyscall(int sysno) const {
  switch (sysno) {
    case __NR_access:
    case __NR_open:
    case __NR_openat:
      return Allow();
    default:
      return GpuProcessPolicy::EvaluateSyscall(sysno);
  }
}

void UpdateProcessTypeToGpuBroker() {
  base::CommandLine::StringVector exec =
      base::CommandLine::ForCurrentProcess()->GetArgs();
  base::CommandLine::Reset();
  base::CommandLine::Init(0, NULL);
  base::CommandLine::ForCurrentProcess()->InitFromArgv(exec);
  base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
      switches::kProcessType, "gpu-broker");

  // Update the process title. The argv was already cached by the call to
  // SetProcessTitleFromCommandLine in content_main_runner.cc, so we can pass
  // NULL here (we don't have the original argv at this point).
  SetProcessTitleFromCommandLine(NULL);
}

bool UpdateProcessTypeAndEnableSandbox(sandbox::bpf_dsl::SandboxBPFDSLPolicy* (
    *broker_sandboxer_allocator)(void)) {
  DCHECK(broker_sandboxer_allocator);
  UpdateProcessTypeToGpuBroker();
  return SandboxSeccompBPF::StartSandboxWithExternalPolicy(
      make_scoped_ptr(broker_sandboxer_allocator()));
}

}  // namespace

GpuProcessPolicy::GpuProcessPolicy() : broker_process_(NULL) {}

GpuProcessPolicy::~GpuProcessPolicy() {}

// Main policy for x86_64/i386. Extended by CrosArmGpuProcessPolicy.
ResultExpr GpuProcessPolicy::EvaluateSyscall(int sysno) const {
  switch (sysno) {
    case __NR_ioctl:
#if defined(__i386__) || defined(__x86_64__) || defined(__mips__)
    // The Nvidia driver uses flags not in the baseline policy
    // (MAP_LOCKED | MAP_EXECUTABLE | MAP_32BIT)
    case __NR_mmap:
#endif
    // We also hit this on the linux_chromeos bot but don't yet know what
    // weird flags were involved.
    case __NR_mprotect:
    // TODO(jln): restrict prctl.
    case __NR_prctl:
    case __NR_sched_getaffinity:
    case __NR_sched_setaffinity:
    case __NR_setpriority:
      return Allow();
    case __NR_access:
    case __NR_open:
    case __NR_openat:
      DCHECK(broker_process_);
      return Trap(GpuSIGSYS_Handler, broker_process_);
    default:
      if (SyscallSets::IsEventFd(sysno))
        return Allow();

      // Default on the baseline policy.
      return SandboxBPFBasePolicy::EvaluateSyscall(sysno);
  }
}

bool GpuProcessPolicy::PreSandboxHook() {
  // Warm up resources needed by the policy we're about to enable and
  // eventually start a broker process.
  const bool chromeos_arm_gpu = IsChromeOS() && IsArchitectureArm();
  // This policy is for x86 or Desktop.
  DCHECK(!chromeos_arm_gpu);

  DCHECK(!broker_process());
  // Create a new broker process.
  InitGpuBrokerProcess(
      GpuBrokerProcessPolicy::Create,
      std::vector<std::string>(),  // No extra files in whitelist.
      std::vector<std::string>());

  if (IsArchitectureX86_64() || IsArchitectureI386()) {
    // Accelerated video dlopen()'s some shared objects
    // inside the sandbox, so preload them now.
    if (IsAcceleratedVideoEnabled()) {
      const char* I965DrvVideoPath = NULL;

#if defined(OS_TIZEN)
      if (IsArchitectureX86_64()) {
        // TODO(halton): Add 64-bit VA driver when 64-bit Tizen support
        // is ready.
        return false;
      } else if (IsArchitectureI386()) {
        I965DrvVideoPath = "/usr/lib/dri/i965_dri.so";
      }
#else
      if (IsArchitectureX86_64()) {
        I965DrvVideoPath = "/usr/lib64/va/drivers/i965_drv_video.so";
      } else if (IsArchitectureI386()) {
        I965DrvVideoPath = "/usr/lib/va/drivers/i965_drv_video.so";
      }
#endif

      dlopen(I965DrvVideoPath, RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE);
      dlopen("libva.so.1", RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE);
      dlopen("libva-x11.so.1", RTLD_NOW|RTLD_GLOBAL|RTLD_NODELETE);
    }
  }

  return true;
}

void GpuProcessPolicy::InitGpuBrokerProcess(
    sandbox::bpf_dsl::SandboxBPFDSLPolicy* (*broker_sandboxer_allocator)(void),
    const std::vector<std::string>& read_whitelist_extra,
    const std::vector<std::string>& write_whitelist_extra) {
  static const char kDriRcPath[] = "/etc/drirc";
  static const char kDriCard0Path[] = "/dev/dri/card0";

  CHECK(broker_process_ == NULL);

  // All GPU process policies need these files brokered out.
  std::vector<std::string> read_whitelist;
  read_whitelist.push_back(kDriCard0Path);
  read_whitelist.push_back(kDriRcPath);
  // Add eventual extra files from read_whitelist_extra.
  read_whitelist.insert(read_whitelist.end(),
                        read_whitelist_extra.begin(),
                        read_whitelist_extra.end());

  std::vector<std::string> write_whitelist;
  write_whitelist.push_back(kDriCard0Path);
  // Add eventual extra files from write_whitelist_extra.
  write_whitelist.insert(write_whitelist.end(),
                         write_whitelist_extra.begin(),
                         write_whitelist_extra.end());

  broker_process_ = new BrokerProcess(GetFSDeniedErrno(),
                                      read_whitelist,
                                      write_whitelist);
  // The initialization callback will perform generic initialization and then
  // call broker_sandboxer_callback.
  CHECK(broker_process_->Init(base::Bind(&UpdateProcessTypeAndEnableSandbox,
                                         broker_sandboxer_allocator)));
}

}  // namespace content
<|endoftext|>


<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
**    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
**      disclaimer.
**    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
**      following disclaimer in the documentation and/or other materials provided with the distribution.
**    * Neither the name of the ETH Zurich 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 "DeclarationVisitor.h"
#include "ExpressionVisitor.h"
#include "StatementVisitor.h"
#include "ElementVisitor.h"

#include "OOModel/src/elements/FormalArgument.h"
#include "OOModel/src/elements/FormalResult.h"
#include "OOModel/src/elements/FormalTypeArgument.h"
#include "OOModel/src/elements/CatchClause.h"
#include "OOModel/src/elements/Enumerator.h"
#include "OOModel/src/elements/MemberInitializer.h"
#include "OOModel/src/expressions/types/PointerTypeExpression.h"
#include "OOModel/src/expressions/types/FunctionTypeExpression.h"

using namespace Export;
using namespace OOModel;

namespace CppExport {

SourceFragment* ElementVisitor::visit(FormalArgument* argument)
{
	auto fragment = new CompositeFragment(argument);

	auto pointerTypeExpression = DCast<PointerTypeExpression>(argument->typeExpression());
	if (pointerTypeExpression && DCast<FunctionTypeExpression>(pointerTypeExpression->typeExpression()))
		*fragment << ExpressionVisitor(data()).visitFunctionPointer(pointerTypeExpression, argument->name());
	else
		*fragment << expression(argument->typeExpression()) << " " << argument->nameNode();

	return fragment;
}

SourceFragment* ElementVisitor::visit(FormalResult* result)
{
	auto fragment = new CompositeFragment(result);
	*fragment << "RESULT";
	return fragment;
}

SourceFragment* ElementVisitor::visit(FormalTypeArgument* typeArgument)
{
	auto fragment = new CompositeFragment(typeArgument);
	*fragment << "typename " << typeArgument->nameNode();
	return fragment;
}

SourceFragment* ElementVisitor::visit(CatchClause* catchClause)
{
	auto fragment = new CompositeFragment(catchClause);

	required(catchClause, catchClause->exceptionToCatch(), "Exception type to catch");

	*fragment << "catch (";
	if (catchClause->exceptionToCatch()) *fragment << expression(catchClause->exceptionToCatch());
	*fragment << ")";
	*fragment << list(catchClause->body(), StatementVisitor(data()), "body");

	return fragment;
}

SourceFragment* ElementVisitor::visit(Enumerator* enumerator)
{
	auto fragment = new CompositeFragment(enumerator);
	*fragment << enumerator->name();
	if (auto value = enumerator->value())
	{
		*fragment << " = " << expression(value);
	}
	return fragment;
}

SourceFragment* ElementVisitor::visit(MemberInitializer* memberInitializer)
{
	auto fragment = new CompositeFragment(memberInitializer);
	*fragment << expression(memberInitializer->memberReference())
				 << list(memberInitializer->arguments(), ExpressionVisitor(data()), "initializerList");
	return fragment;
}

}
<commit_msg>export default argument values<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
**    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
**      disclaimer.
**    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
**      following disclaimer in the documentation and/or other materials provided with the distribution.
**    * Neither the name of the ETH Zurich 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 "DeclarationVisitor.h"
#include "ExpressionVisitor.h"
#include "StatementVisitor.h"
#include "ElementVisitor.h"

#include "OOModel/src/elements/FormalArgument.h"
#include "OOModel/src/elements/FormalResult.h"
#include "OOModel/src/elements/FormalTypeArgument.h"
#include "OOModel/src/elements/CatchClause.h"
#include "OOModel/src/elements/Enumerator.h"
#include "OOModel/src/elements/MemberInitializer.h"
#include "OOModel/src/expressions/types/PointerTypeExpression.h"
#include "OOModel/src/expressions/types/FunctionTypeExpression.h"

using namespace Export;
using namespace OOModel;

namespace CppExport {

SourceFragment* ElementVisitor::visit(FormalArgument* argument)
{
	auto fragment = new CompositeFragment(argument);

	auto pointerTypeExpression = DCast<PointerTypeExpression>(argument->typeExpression());
	if (pointerTypeExpression && DCast<FunctionTypeExpression>(pointerTypeExpression->typeExpression()))
		*fragment << ExpressionVisitor(data()).visitFunctionPointer(pointerTypeExpression, argument->name());
	else
		*fragment << expression(argument->typeExpression()) << " " << argument->nameNode();

	if (argument->initialValue())
		*fragment << " = " << ExpressionVisitor(data()).visit(argument->initialValue());

	return fragment;
}

SourceFragment* ElementVisitor::visit(FormalResult* result)
{
	auto fragment = new CompositeFragment(result);
	*fragment << "RESULT";
	return fragment;
}

SourceFragment* ElementVisitor::visit(FormalTypeArgument* typeArgument)
{
	auto fragment = new CompositeFragment(typeArgument);
	*fragment << "typename " << typeArgument->nameNode();
	return fragment;
}

SourceFragment* ElementVisitor::visit(CatchClause* catchClause)
{
	auto fragment = new CompositeFragment(catchClause);

	required(catchClause, catchClause->exceptionToCatch(), "Exception type to catch");

	*fragment << "catch (";
	if (catchClause->exceptionToCatch()) *fragment << expression(catchClause->exceptionToCatch());
	*fragment << ")";
	*fragment << list(catchClause->body(), StatementVisitor(data()), "body");

	return fragment;
}

SourceFragment* ElementVisitor::visit(Enumerator* enumerator)
{
	auto fragment = new CompositeFragment(enumerator);
	*fragment << enumerator->name();
	if (auto value = enumerator->value())
	{
		*fragment << " = " << expression(value);
	}
	return fragment;
}

SourceFragment* ElementVisitor::visit(MemberInitializer* memberInitializer)
{
	auto fragment = new CompositeFragment(memberInitializer);
	*fragment << expression(memberInitializer->memberReference())
				 << list(memberInitializer->arguments(), ExpressionVisitor(data()), "initializerList");
	return fragment;
}

}
<|endoftext|>


<commit_before>#ifndef CTLL__GRAMMARS__HPP
#define CTLL__GRAMMARS__HPP

namespace ctll {

// terminal type representing symbol / character of any type
template <auto v> struct term {
	static constexpr auto value = v;
};

// epsilon = nothing on input tape
// also used as an command for parsing means "do nothing"
struct epsilon {
	static constexpr auto value = '-';
};

// empty_stack_symbol = nothing on stack
struct empty_stack_symbol {};

// push<T...> is alias to list<T...>
template <typename... Ts> using push = list<Ts...>;

// accept/reject type for controlling output of LL1 machine
struct accept { constexpr explicit operator bool() noexcept { return true; } };
struct reject { constexpr explicit operator bool() noexcept { return false; } };

// action type, every action item in grammar must inherit from
struct action {
	struct action_tag { };
};

// move one character forward and pop it from stack command
struct pop_input {
	struct pop_input_tag { };
};

// additional overloads for type list
template <typename... Ts> constexpr auto push_front(pop_input, list<Ts...>) -> list<Ts...> { return {}; }

template <typename... Ts> constexpr auto push_front(epsilon, list<Ts...>) -> list<Ts...> { return {}; }

template <typename... As, typename... Bs> constexpr auto push_front(list<As...>, list<Bs...>) -> list<As..., Bs...> { return {}; }

template <typename T, typename... As> constexpr auto pop_front_and_push_front(T item, list<As...> l) {
	return push_front(item, pop_front(l));
}

// SPECIAL matching types for nicer grammars

// match any term
struct anything {
	constexpr inline anything() noexcept { };
	template <auto V> constexpr anything(term<V>) noexcept;
};

// match range of term A-B
template <auto A, decltype(A) B> struct range {
	constexpr inline range() noexcept { };
	//template <auto V> constexpr range(term<V>) noexcept requires (A <= V) && (V <= B);
	template <auto V, typename = std::enable_if_t<(A <= V) && (V <= B)>> constexpr inline range(term<V>) noexcept;
};

#ifdef __EDG__
template <auto V, auto... Set> struct contains {
	static constexpr bool value = ((Set == V) || ... || false);
};
#endif

// match terms defined in set
template <auto... Def> struct set {
	constexpr inline set() noexcept { };
	#ifdef __EDG__
	template <auto V, typename = std::enable_if_t<contains<V, Def...>::value>> constexpr inline set(term<V>) noexcept;
	#else
	template <auto V, typename = std::enable_if_t<((Set == V) || ... || false)>> constexpr inline set(term<V>) noexcept;
	#endif
};

// match terms not defined in set
template <auto... Def> struct neg_set {
	constexpr inline neg_set() noexcept { };

	#ifdef __EDG__
	template <auto V, typename = std::enable_if_t<!contains<V, Def...>::value>> constexpr inline neg_set(term<V>) noexcept;
	#else
	template <auto V, typename = std::enable_if_t<!(Set == V) || ... || false)>> constexpr inline neg_set(term<V>) noexcept;
	#endif
};

// AUGMENTED grammar which completes user-defined grammar for all other cases
template <typename Grammar> struct augment_grammar: public Grammar {
	// start nonterminal is defined in parent type
	using typename Grammar::_start;

	// grammar rules are inherited from Grammar parent type
	using Grammar::rule;

	// term on stack and on input means pop_input;
	template <auto A> static constexpr auto rule(term<A>, term<A>) -> ctll::pop_input;

	// if the type on stack (range, set, neg_set, anything) is constructible from the terminal => pop_input
	template <typename Expected, auto V> static constexpr auto rule(Expected, term<V>) -> std::enable_if_t<std::is_constructible_v<Expected, term<V>>, ctll::pop_input>;

	// empty stack and empty input means we are accepting
	static constexpr auto rule(empty_stack_symbol, epsilon) -> ctll::accept;

	// not matching anything else => reject
	static constexpr auto rule(...) -> ctll::reject;

	// start stack is just a list<Grammar::_start>;
	using start_stack = list<typename Grammar::_start>;
};

}

#endif

<commit_msg>#63: fix after fixing :)<commit_after>#ifndef CTLL__GRAMMARS__HPP
#define CTLL__GRAMMARS__HPP

namespace ctll {

// terminal type representing symbol / character of any type
template <auto v> struct term {
	static constexpr auto value = v;
};

// epsilon = nothing on input tape
// also used as an command for parsing means "do nothing"
struct epsilon {
	static constexpr auto value = '-';
};

// empty_stack_symbol = nothing on stack
struct empty_stack_symbol {};

// push<T...> is alias to list<T...>
template <typename... Ts> using push = list<Ts...>;

// accept/reject type for controlling output of LL1 machine
struct accept { constexpr explicit operator bool() noexcept { return true; } };
struct reject { constexpr explicit operator bool() noexcept { return false; } };

// action type, every action item in grammar must inherit from
struct action {
	struct action_tag { };
};

// move one character forward and pop it from stack command
struct pop_input {
	struct pop_input_tag { };
};

// additional overloads for type list
template <typename... Ts> constexpr auto push_front(pop_input, list<Ts...>) -> list<Ts...> { return {}; }

template <typename... Ts> constexpr auto push_front(epsilon, list<Ts...>) -> list<Ts...> { return {}; }

template <typename... As, typename... Bs> constexpr auto push_front(list<As...>, list<Bs...>) -> list<As..., Bs...> { return {}; }

template <typename T, typename... As> constexpr auto pop_front_and_push_front(T item, list<As...> l) {
	return push_front(item, pop_front(l));
}

// SPECIAL matching types for nicer grammars

// match any term
struct anything {
	constexpr inline anything() noexcept { };
	template <auto V> constexpr anything(term<V>) noexcept;
};

// match range of term A-B
template <auto A, decltype(A) B> struct range {
	constexpr inline range() noexcept { };
	//template <auto V> constexpr range(term<V>) noexcept requires (A <= V) && (V <= B);
	template <auto V, typename = std::enable_if_t<(A <= V) && (V <= B)>> constexpr inline range(term<V>) noexcept;
};

#ifdef __EDG__
template <auto V, auto... Set> struct contains {
	static constexpr bool value = ((Set == V) || ... || false);
};
#endif

// match terms defined in set
template <auto... Def> struct set {
	constexpr inline set() noexcept { };
	#ifdef __EDG__
	template <auto V, typename = std::enable_if_t<contains<V, Def...>::value>> constexpr inline set(term<V>) noexcept;
	#else
	template <auto V, typename = std::enable_if_t<((Def == V) || ... || false)>> constexpr inline set(term<V>) noexcept;
	#endif
};

// match terms not defined in set
template <auto... Def> struct neg_set {
	constexpr inline neg_set() noexcept { };

	#ifdef __EDG__
	template <auto V, typename = std::enable_if_t<!contains<V, Def...>::value>> constexpr inline neg_set(term<V>) noexcept;
	#else
	template <auto V, typename = std::enable_if_t<!((Def == V) || ... || false)>> constexpr inline neg_set(term<V>) noexcept;
	#endif
};

// AUGMENTED grammar which completes user-defined grammar for all other cases
template <typename Grammar> struct augment_grammar: public Grammar {
	// start nonterminal is defined in parent type
	using typename Grammar::_start;

	// grammar rules are inherited from Grammar parent type
	using Grammar::rule;

	// term on stack and on input means pop_input;
	template <auto A> static constexpr auto rule(term<A>, term<A>) -> ctll::pop_input;

	// if the type on stack (range, set, neg_set, anything) is constructible from the terminal => pop_input
	template <typename Expected, auto V> static constexpr auto rule(Expected, term<V>) -> std::enable_if_t<std::is_constructible_v<Expected, term<V>>, ctll::pop_input>;

	// empty stack and empty input means we are accepting
	static constexpr auto rule(empty_stack_symbol, epsilon) -> ctll::accept;

	// not matching anything else => reject
	static constexpr auto rule(...) -> ctll::reject;

	// start stack is just a list<Grammar::_start>;
	using start_stack = list<typename Grammar::_start>;
};

}

#endif

<|endoftext|>