<commit_before>#include <GarrysMod/Lua/Interface.h>
#include <GarrysMod/Lua/LuaInterface.h>
#include <SymbolFinder.hpp>
#include <MologieDetours/detours.h>
#include <stdexcept>
#include <stdint.h>
#include <sha1.h>

#if defined _WIN32

#define snprintf _snprintf

#define FASTCALL __fastcall
#define THISCALL __thiscall

#define SERVER_BINARY "server.dll"

#define ADDORUPDATEFILE_SYM reinterpret_cast<const uint8_t *>( "\x55\x8B\xEC\x83\xEC\x18\x53\x56\x8B\x75\x08\x83\xC6\x04\x83\x7E" )
#define ADDORUPDATEFILE_SYMLEN 16

#elif defined __linux || defined __APPLE__

#define CDECL __attribute__((cdecl))

#if defined __linux

#define SERVER_BINARY "garrysmod/bin/server_srv.so"

#define SYMBOL_PREFIX "@"

#else

#define SERVER_BINARY "garrysmod/bin/server.dylib"

#define SYMBOL_PREFIX "@_"

#endif

#define ADDORUPDATEFILE_SYM reinterpret_cast<const uint8_t *>( SYMBOL_PREFIX "_ZN12GModDataPack15AddOrUpdateFileEP7LuaFileb" )
#define ADDORUPDATEFILE_SYMLEN 0

#endif

GarrysMod::Lua::ILuaInterface *lua = NULL;

class GModDataPack;

struct LuaFile
{
	uint32_t skip;
	const char *path;
};

#if defined _WIN32

typedef void ( THISCALL *AddOrUpdateFile_t ) ( GModDataPack *self, LuaFile *file, bool force );

#elif defined __linux || defined __APPLE__

typedef void ( CDECL *AddOrUpdateFile_t ) ( GModDataPack *self, LuaFile *file, bool force );

#endif

AddOrUpdateFile_t AddOrUpdateFile = NULL;
MologieDetours::Detour<AddOrUpdateFile_t> *AddOrUpdateFile_d = NULL;

#if defined _WIN32

void FASTCALL AddOrUpdateFile_h( GModDataPack *self, void *, LuaFile *file, bool b )

#elif defined __linux || defined __APPLE__

void CDECL AddOrUpdateFile_h( GModDataPack *self, LuaFile *file, bool b )

#endif

{
	lua->PushSpecial( GarrysMod::Lua::SPECIAL_GLOB );
	if( lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) )
	{
		lua->GetField( -1, "hook" );
		if( lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) )
		{
			lua->GetField( -1, "Run" );
			if( lua->IsType( -1, GarrysMod::Lua::Type::FUNCTION ) )
			{
				lua->PushString( "AddOrUpdateCSLuaFile" );

				lua->PushString( file->path );
				lua->PushBool( b );

				if( lua->PCall( 3, 1, 0 ) != 0 )
				{
					lua->Msg( "[luapack_internal] %s\n", lua->GetString( ) );
					lua->Pop( 3 );
					return AddOrUpdateFile( self, file, b );
				}

				if( lua->IsType( -1, GarrysMod::Lua::Type::BOOL ) && lua->GetBool( ) )
				{
					lua->Pop( 3 );
					return;
				}

				lua->Pop( 1 );
			}
			else
			{
				lua->Pop( 1 );
			}
		}

		lua->Pop( 1 );
	}

	lua->Pop( 1 );
	return AddOrUpdateFile( self, file, b );
}

#define HASHER_METATABLE "SHA1"
#define HASHER_TYPE 31

#define THROW_ERROR( error ) ( LUA->ThrowError( error ), 0 )
#define LUA_ERROR( ) THROW_ERROR( LUA->GetString( ) )

#define GET_USERDATA( index ) reinterpret_cast<GarrysMod::Lua::UserData *>( LUA->GetUserdata( index ) )
#define GET_HASHER( index ) reinterpret_cast<sha1_context *>( GET_USERDATA( index )->data )
#define VALIDATE_HASHER( hasher ) if( hasher == 0 ) return THROW_ERROR( HASHER_METATABLE " object is not valid" )

LUA_FUNCTION_STATIC( hasher__new )
{
	try
	{
		sha1_context *context = new sha1_context;
		sha1_starts( context );

		void *luadata = LUA->NewUserdata( sizeof( GarrysMod::Lua::UserData ) );
		GarrysMod::Lua::UserData *userdata = reinterpret_cast<GarrysMod::Lua::UserData *>( luadata );
		userdata->data = context;
		userdata->type = HASHER_TYPE;

		LUA->CreateMetaTableType( HASHER_METATABLE, HASHER_TYPE );
		LUA->SetMetaTable( -2 );

		return 1;
	}
	catch( std::exception &e )
	{
		LUA->PushString( e.what( ) );
	}

	return LUA_ERROR( );
}

LUA_FUNCTION_STATIC( hasher__gc )
{
	LUA->CheckType( 1, HASHER_TYPE );

	GarrysMod::Lua::UserData *userdata = GET_USERDATA( 1 );
	sha1_context *hasher = reinterpret_cast<sha1_context *>( userdata->data );
	VALIDATE_HASHER( hasher );

	userdata->data = 0;

	delete hasher;
	return 0;
}

LUA_FUNCTION_STATIC( hasher_update )
{
	LUA->CheckType( 1, HASHER_TYPE );
	LUA->CheckType( 2, GarrysMod::Lua::Type::STRING );

	sha1_context *hasher = GET_HASHER( 1 );
	VALIDATE_HASHER( hasher );

	uint32_t len = 0;
	const uint8_t *data = reinterpret_cast<const uint8_t *>( LUA->GetString( 2, &len ) );

	sha1_update( hasher, data, len );

	return 0;
}

LUA_FUNCTION_STATIC( hasher_final )
{
	LUA->CheckType( 1, HASHER_TYPE );

	sha1_context *hasher = GET_HASHER( 1 );
	VALIDATE_HASHER( hasher );

	uint8_t digest[20];
	sha1_finish( hasher, digest );

	LUA->PushString( reinterpret_cast<const char *>( digest ), sizeof( digest ) );
	return 1;
}

LUA_FUNCTION_STATIC( luapack_rename )
{
	LUA->CheckType( 1, GarrysMod::Lua::Type::STRING );

	char newto[70];
	snprintf( newto, sizeof( newto ), "garrysmod/data/luapack/%s.dat", LUA->GetString( 1 ) );

	LUA->PushBool( rename( "garrysmod/data/luapack/temp.dat", newto ) == 0 );
	return 1;
}

GMOD_MODULE_OPEN( )
{
	lua = reinterpret_cast<GarrysMod::Lua::ILuaInterface *>( LUA );

	try
	{
		lua->PushSpecial( GarrysMod::Lua::SPECIAL_GLOB );

		lua->GetField( -1, "luapack" );
		if( !lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) )
			throw std::exception( "luapack table not found" );

		lua->PushCFunction( luapack_rename );
		lua->SetField( -2, "Rename" );

		lua->PushCFunction( hasher__new );
		lua->SetField( -2, HASHER_METATABLE );

		LUA->CreateMetaTableType( HASHER_METATABLE, HASHER_TYPE );

		LUA->Push( -1 );
		LUA->SetField( -2, "__index" );

		LUA->PushCFunction( hasher__gc );
		LUA->SetField( -2, "__gc" );

		LUA->PushCFunction( hasher_update );
		LUA->SetField( -2, "Update" );

		LUA->PushCFunction( hasher_final );
		LUA->SetField( -2, "Final" );

		SymbolFinder symfinder;

		AddOrUpdateFile = reinterpret_cast<AddOrUpdateFile_t>( symfinder.ResolveOnBinary( SERVER_BINARY, ADDORUPDATEFILE_SYM, ADDORUPDATEFILE_SYMLEN ) );
		if( AddOrUpdateFile == NULL )
			throw std::exception( "GModDataPack::AddOrUpdateFile detour failed" );

		AddOrUpdateFile_d = new MologieDetours::Detour<AddOrUpdateFile_t>( AddOrUpdateFile, reinterpret_cast<AddOrUpdateFile_t>( AddOrUpdateFile_h ) );

		AddOrUpdateFile = AddOrUpdateFile_d->GetOriginalFunction( );

		lua->Msg( "[luapack_internal] GModDataPack::AddOrUpdateFile detoured.\n" );

		return 0;
	}
	catch( std::exception &e )
	{
		LUA->PushString( e.what( ) );
	}

	return LUA_ERROR( );
}

GMOD_MODULE_CLOSE( )
{
	delete AddOrUpdateFile_d;
	return 0;
}<commit_msg>Linux fix.<commit_after>#include <GarrysMod/Lua/Interface.h>
#include <GarrysMod/Lua/LuaInterface.h>
#include <SymbolFinder.hpp>
#include <MologieDetours/detours.h>
#include <stdexcept>
#include <stdint.h>
#include <stdio.h>
#include <sha1.h>

#if defined _WIN32

#define snprintf _snprintf

#define FASTCALL __fastcall
#define THISCALL __thiscall

#define SERVER_BINARY "server.dll"

#define ADDORUPDATEFILE_SYM reinterpret_cast<const uint8_t *>( "\x55\x8B\xEC\x83\xEC\x18\x53\x56\x8B\x75\x08\x83\xC6\x04\x83\x7E" )
#define ADDORUPDATEFILE_SYMLEN 16

#elif defined __linux || defined __APPLE__

#define CDECL __attribute__((cdecl))

#if defined __linux

#define SERVER_BINARY "garrysmod/bin/server_srv.so"

#define SYMBOL_PREFIX "@"

#else

#define SERVER_BINARY "garrysmod/bin/server.dylib"

#define SYMBOL_PREFIX "@_"

#endif

#define ADDORUPDATEFILE_SYM reinterpret_cast<const uint8_t *>( SYMBOL_PREFIX "_ZN12GModDataPack15AddOrUpdateFileEP7LuaFileb" )
#define ADDORUPDATEFILE_SYMLEN 0

#endif

GarrysMod::Lua::ILuaInterface *lua = NULL;

class GModDataPack;

struct LuaFile
{
	uint32_t skip;
	const char *path;
};

#if defined _WIN32

typedef void ( THISCALL *AddOrUpdateFile_t ) ( GModDataPack *self, LuaFile *file, bool force );

#elif defined __linux || defined __APPLE__

typedef void ( CDECL *AddOrUpdateFile_t ) ( GModDataPack *self, LuaFile *file, bool force );

#endif

AddOrUpdateFile_t AddOrUpdateFile = NULL;
MologieDetours::Detour<AddOrUpdateFile_t> *AddOrUpdateFile_d = NULL;

#if defined _WIN32

void FASTCALL AddOrUpdateFile_h( GModDataPack *self, void *, LuaFile *file, bool b )

#elif defined __linux || defined __APPLE__

void CDECL AddOrUpdateFile_h( GModDataPack *self, LuaFile *file, bool b )

#endif

{
	lua->PushSpecial( GarrysMod::Lua::SPECIAL_GLOB );
	if( lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) )
	{
		lua->GetField( -1, "hook" );
		if( lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) )
		{
			lua->GetField( -1, "Run" );
			if( lua->IsType( -1, GarrysMod::Lua::Type::FUNCTION ) )
			{
				lua->PushString( "AddOrUpdateCSLuaFile" );

				lua->PushString( file->path );
				lua->PushBool( b );

				if( lua->PCall( 3, 1, 0 ) != 0 )
				{
					lua->Msg( "[luapack_internal] %s\n", lua->GetString( ) );
					lua->Pop( 3 );
					return AddOrUpdateFile( self, file, b );
				}

				if( lua->IsType( -1, GarrysMod::Lua::Type::BOOL ) && lua->GetBool( ) )
				{
					lua->Pop( 3 );
					return;
				}

				lua->Pop( 1 );
			}
			else
			{
				lua->Pop( 1 );
			}
		}

		lua->Pop( 1 );
	}

	lua->Pop( 1 );
	return AddOrUpdateFile( self, file, b );
}

#define HASHER_METATABLE "SHA1"
#define HASHER_TYPE 31

#define THROW_ERROR( error ) ( LUA->ThrowError( error ), 0 )
#define LUA_ERROR( ) THROW_ERROR( LUA->GetString( ) )

#define GET_USERDATA( index ) reinterpret_cast<GarrysMod::Lua::UserData *>( LUA->GetUserdata( index ) )
#define GET_HASHER( index ) reinterpret_cast<sha1_context *>( GET_USERDATA( index )->data )
#define VALIDATE_HASHER( hasher ) if( hasher == 0 ) return THROW_ERROR( HASHER_METATABLE " object is not valid" )

LUA_FUNCTION_STATIC( hasher__new )
{
	try
	{
		sha1_context *context = new sha1_context;
		sha1_starts( context );

		void *luadata = LUA->NewUserdata( sizeof( GarrysMod::Lua::UserData ) );
		GarrysMod::Lua::UserData *userdata = reinterpret_cast<GarrysMod::Lua::UserData *>( luadata );
		userdata->data = context;
		userdata->type = HASHER_TYPE;

		LUA->CreateMetaTableType( HASHER_METATABLE, HASHER_TYPE );
		LUA->SetMetaTable( -2 );

		return 1;
	}
	catch( std::exception &e )
	{
		LUA->PushString( e.what( ) );
	}

	return LUA_ERROR( );
}

LUA_FUNCTION_STATIC( hasher__gc )
{
	LUA->CheckType( 1, HASHER_TYPE );

	GarrysMod::Lua::UserData *userdata = GET_USERDATA( 1 );
	sha1_context *hasher = reinterpret_cast<sha1_context *>( userdata->data );
	VALIDATE_HASHER( hasher );

	userdata->data = 0;

	delete hasher;
	return 0;
}

LUA_FUNCTION_STATIC( hasher_update )
{
	LUA->CheckType( 1, HASHER_TYPE );
	LUA->CheckType( 2, GarrysMod::Lua::Type::STRING );

	sha1_context *hasher = GET_HASHER( 1 );
	VALIDATE_HASHER( hasher );

	uint32_t len = 0;
	const uint8_t *data = reinterpret_cast<const uint8_t *>( LUA->GetString( 2, &len ) );

	sha1_update( hasher, data, len );

	return 0;
}

LUA_FUNCTION_STATIC( hasher_final )
{
	LUA->CheckType( 1, HASHER_TYPE );

	sha1_context *hasher = GET_HASHER( 1 );
	VALIDATE_HASHER( hasher );

	uint8_t digest[20];
	sha1_finish( hasher, digest );

	LUA->PushString( reinterpret_cast<const char *>( digest ), sizeof( digest ) );
	return 1;
}

LUA_FUNCTION_STATIC( luapack_rename )
{
	LUA->CheckType( 1, GarrysMod::Lua::Type::STRING );

	char newto[70];
	snprintf( newto, sizeof( newto ), "garrysmod/data/luapack/%s.dat", LUA->GetString( 1 ) );

	LUA->PushBool( rename( "garrysmod/data/luapack/temp.dat", newto ) == 0 );
	return 1;
}

GMOD_MODULE_OPEN( )
{
	lua = reinterpret_cast<GarrysMod::Lua::ILuaInterface *>( LUA );

	try
	{
		lua->PushSpecial( GarrysMod::Lua::SPECIAL_GLOB );

		lua->GetField( -1, "luapack" );
		if( !lua->IsType( -1, GarrysMod::Lua::Type::TABLE ) )
			throw std::exception( "luapack table not found" );

		lua->PushCFunction( luapack_rename );
		lua->SetField( -2, "Rename" );

		lua->PushCFunction( hasher__new );
		lua->SetField( -2, HASHER_METATABLE );

		LUA->CreateMetaTableType( HASHER_METATABLE, HASHER_TYPE );

		LUA->Push( -1 );
		LUA->SetField( -2, "__index" );

		LUA->PushCFunction( hasher__gc );
		LUA->SetField( -2, "__gc" );

		LUA->PushCFunction( hasher_update );
		LUA->SetField( -2, "Update" );

		LUA->PushCFunction( hasher_final );
		LUA->SetField( -2, "Final" );

		SymbolFinder symfinder;

		AddOrUpdateFile = reinterpret_cast<AddOrUpdateFile_t>( symfinder.ResolveOnBinary( SERVER_BINARY, ADDORUPDATEFILE_SYM, ADDORUPDATEFILE_SYMLEN ) );
		if( AddOrUpdateFile == NULL )
			throw std::exception( "GModDataPack::AddOrUpdateFile detour failed" );

		AddOrUpdateFile_d = new MologieDetours::Detour<AddOrUpdateFile_t>( AddOrUpdateFile, reinterpret_cast<AddOrUpdateFile_t>( AddOrUpdateFile_h ) );

		AddOrUpdateFile = AddOrUpdateFile_d->GetOriginalFunction( );

		lua->Msg( "[luapack_internal] GModDataPack::AddOrUpdateFile detoured.\n" );

		return 0;
	}
	catch( std::exception &e )
	{
		LUA->PushString( e.what( ) );
	}

	return LUA_ERROR( );
}

GMOD_MODULE_CLOSE( )
{
	delete AddOrUpdateFile_d;
	return 0;
}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2010-2014, Delft University of Technology
 * Copyright (c) 2010-2014, K. Kumar (me@kartikkumar.com)
 * All rights reserved.
 * See http://bit.ly/12SHPLR for license details.
 */

#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <string>

#include <boost/algorithm/string/predicate.hpp>
#include <boost/timer/timer.hpp>

#include <Assist/InputOutput/basicInputOutput.h>

#include <Tudat/InputOutput/dictionaryTools.h>
#include <Tudat/InputOutput/fieldType.h>
#include <Tudat/InputOutput/separatedParser.h>
#include <Tudat/InputOutput/parsedDataVectorUtilities.h>

#include "Stomi/ApplicationModes/randomWalkDatabaseGenerator.h"
#include "Stomi/ApplicationModes/randomWalkSimulator.h"
#include "Stomi/ApplicationModes/testParticleDatabaseGenerator.h"
#include "Stomi/ApplicationModes/testParticleSimulator.h"
#include "Stomi/InputOutput/dictionaries.h"

//! Execute Stomi.
int main( const int numberOfInputs, const char* inputArguments[ ] )
{
    ///////////////////////////////////////////////////////////////////////////

    // Start timer. Timer automatically ends when this object goes out of scope.
    boost::timer::auto_cpu_timer timer;

    ///////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////

    // Declare using-statements.
    using std::cout;
    using std::endl;
    using std::runtime_error;
    using std::string;

    using boost::iequals;

    using namespace assist::input_output;

    using namespace tudat::input_output;
    using namespace tudat::input_output::dictionary;
    using namespace tudat::input_output::field_types::general;
    using namespace tudat::input_output::parsed_data_vector_utilities;

    using namespace stomi::application_modes;
    using namespace stomi::input_output;

    ///////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////

    // Set up input deck.

    // Check number of input parameters is correct (the numberOfInputs variable includes the
    // application itself, so one is subtracted from this number).
    checkNumberOfInputArguments( numberOfInputs - 1 );

    // Read and filter input stream (this can't be declared const because the parser's parse
    // function is not const-correct at the moment).
    string filteredInput = readAndFilterInputFile( inputArguments[ 1 ] );

    // Declare a separated parser.
    SeparatedParser parser( string( ": " ), 2, parameterName, parameterValue );

    // Parse filtered data.
    const ParsedDataVectorPtr parsedData = parser.parse( filteredInput );

    // Get general parameters dictionary.
    DictionaryPointer dictionary = getGeneralParametersDictionary( );

    // Extract application mode.
    const string applicationMode = extractParameterValue< string >(
                parsedData->begin( ), parsedData->end( ), findEntry( dictionary, "MODE" ) );

    const string databasePath = extractParameterValue< string >(
                parsedData->begin( ), parsedData->end( ),
                findEntry( dictionary, "DATABASEPATH" ) );

    ///////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////

    // Call selected application mode.
    cout << endl;
    cout << "----------------------------------------------------------------------------" << endl;
    cout << endl;
    cout << "                                    STOMI                                   " << endl;
    cout << "                                    2.0.0                                   " << endl;
    cout << endl;
    cout << "          Copyright (c) 2010-2014, Delft University of Technology           " << endl;
    cout << "           Copyright (c) 2010-2014, K. Kumar (me@kartikkumar.com)           " << endl;
    cout << "         Copyright (c) 2013-2014, S. Hirsh (sethhirsh@berkeley.edu)         " << endl;
    cout << endl;
    cout << "----------------------------------------------------------------------------" << endl;

    cout << endl;
    cout << "****************************************************************************" << endl;
    cout << "Input parameters" << endl;
    cout << "****************************************************************************" << endl;
    cout << endl;

    cout << endl;
    cout << "Application mode                                          ";

    if ( iequals( applicationMode, "TPDB" ) )
    {
        cout << "TEST PARTICLE DATABASE GENERATOR" << endl;
        executeTestParticleDatabaseGenerator( databasePath, parsedData );
    }

    else if ( iequals( applicationMode, "TPSIM" ) )
    {
        cout << "TEST PARTICLE SIMULATOR" << endl;
        executeTestParticleSimulator( databasePath, parsedData );
    }

    else if ( iequals( applicationMode, "RWDB" ) )
    {
        cout << "RANDOM WALK DATABASE GENERATOR" << endl;
        executeRandomWalkDatabaseGenerator( databasePath, parsedData );
    }

    else if ( iequals( applicationMode, "RWSIM" ) )
    {
        cout << "RANDOM WALK SIMULATOR" << endl;
        executeRandomWalkSimulator( databasePath, parsedData );
    }

    else
    {
        throw runtime_error( "ERROR: Application mode not recognized!" );
    }

    cout << endl;

    ///////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////

    // Print timing information.
    cout << "Timing information: ";

    // If program is successfully completed, return 0.
    return EXIT_SUCCESS;

    ///////////////////////////////////////////////////////////////////////////
}

/*
 *    TODO:
 *      - encapsulate code in try-catch blocks to capture exceptions.
 *      - execute verification of existing data against input parameters provided to ensure
 *        consistency of inputs and possibly warn user.
 *      - expand code to enable interactive interface for user to provide inputs and select
 *        options (capture command line user input).
 */
<commit_msg>Remove erroneous copyright statement.<commit_after>/*
 * Copyright (c) 2010-2014, Delft University of Technology
 * Copyright (c) 2010-2014, K. Kumar (me@kartikkumar.com)
 * All rights reserved.
 * See http://bit.ly/12SHPLR for license details.
 */

#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <string>

#include <boost/algorithm/string/predicate.hpp>
#include <boost/timer/timer.hpp>

#include <Assist/InputOutput/basicInputOutput.h>

#include <Tudat/InputOutput/dictionaryTools.h>
#include <Tudat/InputOutput/fieldType.h>
#include <Tudat/InputOutput/separatedParser.h>
#include <Tudat/InputOutput/parsedDataVectorUtilities.h>

#include "Stomi/ApplicationModes/randomWalkDatabaseGenerator.h"
#include "Stomi/ApplicationModes/randomWalkSimulator.h"
#include "Stomi/ApplicationModes/testParticleDatabaseGenerator.h"
#include "Stomi/ApplicationModes/testParticleSimulator.h"
#include "Stomi/InputOutput/dictionaries.h"

//! Execute Stomi.
int main( const int numberOfInputs, const char* inputArguments[ ] )
{
    ///////////////////////////////////////////////////////////////////////////

    // Start timer. Timer automatically ends when this object goes out of scope.
    boost::timer::auto_cpu_timer timer;

    ///////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////

    // Declare using-statements.
    using std::cout;
    using std::endl;
    using std::runtime_error;
    using std::string;

    using boost::iequals;

    using namespace assist::input_output;

    using namespace tudat::input_output;
    using namespace tudat::input_output::dictionary;
    using namespace tudat::input_output::field_types::general;
    using namespace tudat::input_output::parsed_data_vector_utilities;

    using namespace stomi::application_modes;
    using namespace stomi::input_output;

    ///////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////

    // Set up input deck.

    // Check number of input parameters is correct (the numberOfInputs variable includes the
    // application itself, so one is subtracted from this number).
    checkNumberOfInputArguments( numberOfInputs - 1 );

    // Read and filter input stream (this can't be declared const because the parser's parse
    // function is not const-correct at the moment).
    string filteredInput = readAndFilterInputFile( inputArguments[ 1 ] );

    // Declare a separated parser.
    SeparatedParser parser( string( ": " ), 2, parameterName, parameterValue );

    // Parse filtered data.
    const ParsedDataVectorPtr parsedData = parser.parse( filteredInput );

    // Get general parameters dictionary.
    DictionaryPointer dictionary = getGeneralParametersDictionary( );

    // Extract application mode.
    const string applicationMode = extractParameterValue< string >(
                parsedData->begin( ), parsedData->end( ), findEntry( dictionary, "MODE" ) );

    const string databasePath = extractParameterValue< string >(
                parsedData->begin( ), parsedData->end( ),
                findEntry( dictionary, "DATABASEPATH" ) );

    ///////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////

    // Call selected application mode.
    cout << endl;
    cout << "----------------------------------------------------------------------------" << endl;
    cout << endl;
    cout << "                                    STOMI                                   " << endl;
    cout << "                                    2.0.0                                   " << endl;
    cout << endl;
    cout << "          Copyright (c) 2010-2014, Delft University of Technology           " << endl;
    cout << "           Copyright (c) 2010-2014, K. Kumar (me@kartikkumar.com)           " << endl;
    cout << endl;
    cout << "----------------------------------------------------------------------------" << endl;

    cout << endl;
    cout << "****************************************************************************" << endl;
    cout << "Input parameters" << endl;
    cout << "****************************************************************************" << endl;
    cout << endl;

    cout << endl;
    cout << "Application mode                                          ";

    if ( iequals( applicationMode, "TPDB" ) )
    {
        cout << "TEST PARTICLE DATABASE GENERATOR" << endl;
        executeTestParticleDatabaseGenerator( databasePath, parsedData );
    }

    else if ( iequals( applicationMode, "TPSIM" ) )
    {
        cout << "TEST PARTICLE SIMULATOR" << endl;
        executeTestParticleSimulator( databasePath, parsedData );
    }

    else if ( iequals( applicationMode, "RWDB" ) )
    {
        cout << "RANDOM WALK DATABASE GENERATOR" << endl;
        executeRandomWalkDatabaseGenerator( databasePath, parsedData );
    }

    else if ( iequals( applicationMode, "RWSIM" ) )
    {
        cout << "RANDOM WALK SIMULATOR" << endl;
        executeRandomWalkSimulator( databasePath, parsedData );
    }

    else
    {
        throw runtime_error( "ERROR: Application mode not recognized!" );
    }

    cout << endl;

    ///////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////

    // Print timing information.
    cout << "Timing information: ";

    // If program is successfully completed, return 0.
    return EXIT_SUCCESS;

    ///////////////////////////////////////////////////////////////////////////
}

/*
 *    TODO:
 *      - encapsulate code in try-catch blocks to capture exceptions.
 *      - execute verification of existing data against input parameters provided to ensure
 *        consistency of inputs and possibly warn user.
 *      - expand code to enable interactive interface for user to provide inputs and select
 *        options (capture command line user input).
 */
<|endoftext|>


<commit_before>

#include "TMainWindow.h"
#include <Application.h>
#include <MenuItem.h>
#include <MenuBar.h>
#include <Menu.h>
#include <Directory.h>
#include <iostream>

using namespace org::toxic;
using namespace std;

TMainWindow::TMainWindow(BRect frame): BWindow(frame,"Guitar Master",B_TITLED_WINDOW,B_NOT_ZOOMABLE | B_NOT_RESIZABLE)
{
	cout<<"Main window"<<endl;

	timer = new BMessageRunner(this,new BMessage(T_MSG_FRAME),50000,-1);

	BDirectory songs_dir("songs");

	if(songs_dir.InitCheck()!=B_OK)
	{
		cout<<"Songs dir not found"<<endl;
	}
	else
	{
		cout<<"Found :"<<songs_dir.CountEntries()<<endl;
	}

	ResizeTo(640,480);

	BRect bounds = Bounds();
	bounds.bottom = bounds.top + 15;
	BMenuBar * menubar = new BMenuBar(bounds,"main menu");

	BMenu * menu;
	BMenuItem * item;

	//Game menu
	menu = new BMenu("Game");
	//----items
	item = new BMenuItem("Quit",new BMessage(B_QUIT_REQUESTED),'Q');
	menu->AddItem(item);

	menubar->AddItem(menu);

	//Songs menu
	menu = new BMenu("Songs");
	// fill with available song list...
	menubar->AddItem(menu);

	AddChild(menubar);
	//menubar->ResizeToPreferred();

	//BGLView
	bounds.top=menubar->Bounds().bottom+1;
	bounds.bottom = Bounds().bottom;
	gameview = new TGameView(bounds);

	AddChild(gameview);
	Show();
}

TMainWindow::~TMainWindow()
{

	cout<<"main window destructor"<<endl;
	delete timer;
}

void TMainWindow::MessageReceived(BMessage * mesg)
{
	switch(mesg->what)
	{
		case T_MSG_FRAME:
			gameview->Render();
		break;

	}
}

bool TMainWindow::QuitRequested()
{
	be_app->PostMessage(B_QUIT_REQUESTED);
	return true;
}
<commit_msg>Songs listed on bmenu<commit_after>

#include "TMainWindow.h"
#include <Application.h>
#include <MenuItem.h>
#include <MenuBar.h>
#include <Menu.h>
#include <Directory.h>
#include <iostream>

using namespace org::toxic;
using namespace std;

TMainWindow::TMainWindow(BRect frame): BWindow(frame,"Guitar Master",B_TITLED_WINDOW,B_NOT_ZOOMABLE | B_NOT_RESIZABLE)
{
	cout<<"Main window"<<endl;

	timer = new BMessageRunner(this,new BMessage(T_MSG_FRAME),50000,-1);

	ResizeTo(640,480);

	BRect bounds = Bounds();
	bounds.bottom = bounds.top + 15;
	BMenuBar * menubar = new BMenuBar(bounds,"main menu");

	BMenu * menu;
	BMenuItem * item;

	//Game menu
	menu = new BMenu("Game");
	//----items
	item = new BMenuItem("Quit",new BMessage(B_QUIT_REQUESTED),'Q');
	menu->AddItem(item);

	menubar->AddItem(menu);

	//Songs menu
	menu = new BMenu("Songs");
	// fill with available song list...
	cout<<"Reading songs directory..."<<endl;

	BDirectory songs_dir("songs");
	BEntry entry;
	char str[B_FILE_NAME_LENGTH];

	if(songs_dir.InitCheck()!=B_OK)
	{
		cout<<"Songs dir not found"<<endl;
	}
	else
	{
		int num = songs_dir.CountEntries();
		cout<<"Found :"<<num<<endl;

		for(int i=0;i<num;i++)
		{
			songs_dir.GetNextEntry(&entry,false);
			entry.GetName(str);
			cout<<"name: "<<str<<endl;

			item = new BMenuItem(str,NULL);
			menu->AddItem(item);

		}
	}
	menubar->AddItem(menu);

	//Play menu
	menu = new BMenu("Play");
	item = new BMenuItem("Easy",NULL);
	menu->AddItem(item);
	item = new BMenuItem("Normal",NULL);
	menu->AddItem(item);
	item = new BMenuItem("Amazing",NULL);
	menu->AddItem(item);
	menubar->AddItem(menu);

	AddChild(menubar);
	//menubar->ResizeToPreferred();

	//BGLView
	bounds.top=menubar->Bounds().bottom+1;
	bounds.bottom = Bounds().bottom;
	gameview = new TGameView(bounds);

	AddChild(gameview);
	Show();
}

TMainWindow::~TMainWindow()
{

	cout<<"main window destructor"<<endl;
	delete timer;
}

void TMainWindow::MessageReceived(BMessage * mesg)
{
	switch(mesg->what)
	{
		case T_MSG_FRAME:
			gameview->Render();
		break;

	}
}

bool TMainWindow::QuitRequested()
{
	be_app->PostMessage(B_QUIT_REQUESTED);
	return true;
}
<|endoftext|>


<commit_before>/*
TPC DA for online calibration

Contact: Haavard.Helstrup@cern.ch
Link:
Run Type: PHYSICS STANDALONE DAQ
DA Type: MON
Number of events needed: 500
Input Files:
Output Files: tpcCE.root, to be exported to the DAQ FXS
fileId:   CE
Trigger types used: PHYSICS_EVENT

*/

/*

TPCCEda.cxx - calibration algorithm for TPC Central Electrode events

10/06/2007  sylvain.chapeland@cern.ch :  first version - clean skeleton based on DAQ DA case1
06/12/2007  haavard.helstrup@cern.ch  :  created CE DA based on pulser code
19/09/2008  J.Wiechula@gsi.de:           Added support for configuration files.

contact: marian.ivanov@cern.ch

This process reads RAW data from the files provided as command line arguments
and save results in a file (named from RESULT_FILE define - see below).

*/

#define RESULT_FILE "tpcCE.root"
#define FILE_ID "CE"
#define MAPPING_FILE "tpcMapping.root"
#define CONFIG_FILE "TPCCEda.conf"

#include <daqDA.h>
#include "event.h"
#include "monitor.h"
#include <stdio.h>
#include <stdlib.h>

//
//Root includes
//
#include <TFile.h>
#include "TROOT.h"
#include "TPluginManager.h"
#include "TSystem.h"
#include "TString.h"
#include "TObjString.h"
#include "TDatime.h"
//
//AliRoot includes
//
#include "AliRawReader.h"
#include "AliRawReaderDate.h"
#include "AliTPCmapper.h"
#include "AliTPCRawStream.h"
#include "AliTPCROC.h"
#include "AliTPCCalROC.h"
#include "AliTPCCalPad.h"
#include "AliMathBase.h"
#include "TTreeStream.h"
#include "AliLog.h"
#include "AliTPCConfigDA.h"
//
//AMORE
//
#include <AmoreDA.h>
//
// TPC calibration algorithm includes
//
#include "AliTPCCalibCE.h"

/* Main routine
      Arguments: list of DATE raw data files
*/
int main(int argc, char **argv) {
  /* log start of process */
  printf("TPC CE DA started - %s\n",__FILE__);

  if (argc<2) {
    printf("Wrong number of arguments\n");
    return -1;
  }

  AliLog::SetClassDebugLevel("AliTPCRawStream",-5);
  AliLog::SetClassDebugLevel("AliRawReaderDate",-5);
  AliLog::SetClassDebugLevel("AliTPCAltroMapping",-5);
  AliLog::SetModuleDebugLevel("RAW",-5);

 gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
                                         "*",
                                         "TStreamerInfo",
                                         "RIO",
                                         "TStreamerInfo()");

 /* declare monitoring program */
 int i,status;
 status=monitorDeclareMp( __FILE__ );
 if (status!=0) {
   printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
   return -1;
 }
 monitorSetNowait();
 monitorSetNoWaitNetworkTimeout(1000);

  //variables
  AliTPCmapper *mapping = 0;   // The TPC mapping
  char localfile[255];
  unsigned long32 runNb=0;      //run number
  // configuration options
  Bool_t fastDecoding = kFALSE;

  // if  test setup get parameters from $DAQDA_TEST_DIR
  if (!mapping){
    /* copy locally the mapping file from daq detector config db */
    sprintf(localfile,"./%s",MAPPING_FILE);
    status = daqDA_DB_getFile(MAPPING_FILE,localfile);
    if (status) {
      printf("Failed to get mapping file (%s) from DAQdetDB, status=%d\n", MAPPING_FILE, status);
      return -1;
    }

    /* open the mapping file and retrieve mapping object */
    TFile *fileMapping = new TFile(MAPPING_FILE, "read");
    mapping = (AliTPCmapper*) fileMapping->Get("tpcMapping");
    delete fileMapping;
  }

  if (mapping == 0) {
    printf("Failed to get mapping object from %s.  ...\n", MAPPING_FILE);
    return -1;
  } else {
    printf("Got mapping object from %s\n", MAPPING_FILE);
  }

  //
  // DA configuration from configuration file
  //
 //retrieve configuration file
  sprintf(localfile,"./%s",CONFIG_FILE);
  status = daqDA_DB_getFile(CONFIG_FILE,localfile);
  if (status) {
    printf("Failed to get configuration file (%s) from DAQdetDB, status=%d\n", CONFIG_FILE, status);
    return -1;
  }
  AliTPCConfigDA config(CONFIG_FILE);
  // check configuration
  if ( (Int_t)config.GetValue("UseFastDecoder") == 1 ){
    printf("Info: The fast decoder will be used for the processing.\n");
    fastDecoding=kTRUE;
  }

  //create calibration object
  AliTPCCalibCE calibCE(config.GetConfigurationMap());   // central electrode calibration
  calibCE.SetAltroMapping(mapping->GetAltroMapping()); // Use altro mapping we got from daqDetDb

  //===========================//
  // loop over RAW data files //
  //==========================//
  int nevents=0;
  for ( i=1; i<argc; i++) {

    /* define data source : this is argument i */
    printf("Processing file %s\n", argv[i]);
    status=monitorSetDataSource( argv[i] );
    if (status!=0) {
      printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
      return -1;
    }

    /* read until EOF */
    while (true) {
      struct eventHeaderStruct *event;

      /* check shutdown condition */
      if (daqDA_checkShutdown()) {break;}

      /* get next event (blocking call until timeout) */
      status=monitorGetEventDynamic((void **)&event);
      if (status==MON_ERR_EOF) {
        printf ("End of File %d detected\n",i);
        break; /* end of monitoring file has been reached */
      }

      if (status!=0) {
        printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
        break;
      }

      /* retry if got no event */
      if (event==NULL)
        continue;

      /* skip start/end of run events */
      if ( (event->eventType != physicsEvent) && (event->eventType != calibrationEvent) )
        continue;

      nevents++;
      // get the run number
      runNb = event->eventRunNb;
      //  CE calibration
        calibCE.ProcessEvent(event);

      /* free resources */
      free(event);
    }
  }

  //
  // Analyse CE data and write them to rootfile
  //
  calibCE.Analyse();
  printf ("%d events processed\n",nevents);

  TFile * fileTPC = new TFile (RESULT_FILE,"recreate");
  calibCE.Write("tpcCalibCE");
  delete fileTPC;
  printf("Wrote %s\n",RESULT_FILE);

  /* store the result file on FES */

  status=daqDA_FES_storeFile(RESULT_FILE,FILE_ID);
  if (status) {
    status = -2;
  }

  //
  //Send objects to the AMORE DB
  //
  printf ("AMORE part\n");
  const char *amoreDANameorig=gSystem->Getenv("AMORE_DA_NAME");
  //cheet a little -- temporary solution (hopefully)
  //
  //currently amoreDA uses the environment variable AMORE_DA_NAME to create the mysql
  //table in which the calib objects are stored. This table is dropped each time AmoreDA
  //is initialised. This of course makes a problem if we would like to store different
  //calibration entries in the AMORE DB. Therefore in each DA which writes to the AMORE DB
  //the AMORE_DA_NAME env variable is overwritten.
  gSystem->Setenv("AMORE_DA_NAME",Form("TPC-%s",FILE_ID));
  //
  // end cheet
  TDatime time;
  TObjString info(Form("Run: %u; Date: %s",runNb,time.AsSQLString()));
  amore::da::AmoreDA amoreDA(amore::da::AmoreDA::kSender);
  Int_t statusDA=0;
  statusDA+=amoreDA.Send("CET0",calibCE.GetCalPadT0());
  statusDA+=amoreDA.Send("CEQ",calibCE.GetCalPadQ());
  statusDA+=amoreDA.Send("CERMS",calibCE.GetCalPadRMS());
  statusDA+=amoreDA.Send("Info",&info);
  if ( statusDA!=0 )
    printf("Waring: Failed to write one of the calib objects to the AMORE database\n");
  if (amoreDANameorig) gSystem->Setenv("AMORE_DA_NAME",amoreDANameorig);

  return status;
}
<commit_msg>TPCCEda.cxx.diff        update CEda for interleaved laser trigger running. Allow for minimum number of events in standalone.                         Using a ring buffer for the events arriving, second thread processes the events.<commit_after>/*
TPC DA for online calibration

Contact: Haavard.Helstrup@cern.ch
Link:
Run Type: PHYSICS STANDALONE DAQ
DA Type: MON
Number of events needed: 500
Input Files:
Output Files: tpcCE.root, to be exported to the DAQ FXS
fileId:   CE
Trigger types used: PHYSICS_EVENT

*/

/*

TPCCEda.cxx - calibration algorithm for TPC Central Electrode events

10/06/2007  sylvain.chapeland@cern.ch :  first version - clean skeleton based on DAQ DA case1
06/12/2007  haavard.helstrup@cern.ch  :  created CE DA based on pulser code
19/09/2008  J.Wiechula@gsi.de:           Added support for configuration files.

contact: marian.ivanov@cern.ch

This process reads RAW data from the files provided as command line arguments
and save results in a file (named from RESULT_FILE define - see below).

*/

#define RESULT_FILE "tpcCE.root"
#define FILE_ID "CE"
#define MAPPING_FILE "tpcMapping.root"
#define CONFIG_FILE "TPCCEda.conf"

#include <daqDA.h>
#include "event.h"
#include "monitor.h"
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <vector>
//
//Root includes
//
#include <TFile.h>
#include "TROOT.h"
#include "TPluginManager.h"
#include "TSystem.h"
#include "TString.h"
#include "TObjString.h"
#include "TDatime.h"
#include "TMap.h"
#include "TGraph.h"
#include "TMath.h"
//
//AliRoot includes
//
#include "AliRawReader.h"
#include "AliRawReaderDate.h"
#include "AliTPCmapper.h"
#include "AliTPCRawStream.h"
#include "AliTPCROC.h"
#include "AliTPCCalROC.h"
#include "AliTPCCalPad.h"
#include "AliMathBase.h"
#include "TTreeStream.h"
#include "AliLog.h"
#include "AliTPCConfigDA.h"
//
//AMORE
//
#include <AmoreDA.h>
//
// TPC calibration algorithm includes
//
#include "AliTPCCalibCE.h"

//functios, implementation below
void SendToAmoreDB(AliTPCCalibCE &calibCE, unsigned long32 runNb);
//for threaded processing
void *processEventBuffer(void *arg);

//common event processing variables for threaded processing
std::vector<eventHeaderStruct*> eventBuffer;
volatile int bStop = false;
struct timespec duree_nanosleep;
Int_t  forceNevents=-1;
Bool_t forceBufferEnds=kFALSE;

/* Main routine
      Arguments: list of DATE raw data files
*/
int main(int argc, char **argv) {
  /* log start of process */
  printf("TPC CE DA started - %s\n",__FILE__);

  if (argc<2) {
    printf("Wrong number of arguments\n");
    return -1;
  }

  AliLog::SetClassDebugLevel("AliTPCRawStream",-5);
  AliLog::SetClassDebugLevel("AliRawReaderDate",-5);
  AliLog::SetClassDebugLevel("AliTPCAltroMapping",-5);
  AliLog::SetModuleDebugLevel("RAW",-5);

  gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
                                        "*",
                                        "TStreamerInfo",
                                        "RIO",
                                        "TStreamerInfo()");

 /* declare monitoring program */
  int i,status;
  status=monitorDeclareMp( __FILE__ );
  if (status!=0) {
    printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
    return -1;
  }
  monitorSetNowait();
  monitorSetNoWaitNetworkTimeout(1000);

  //variables
  AliTPCmapper *mapping = 0;   // The TPC mapping
  char localfile[255];
  unsigned long32 runNb=0;      //run number

  //
  // thread wait time
  //
  duree_nanosleep.tv_sec=0;
  duree_nanosleep.tv_nsec=1000000; //1 ms

  //
  // DA configuration from configuration file
  //
  //retrieve configuration file
  sprintf(localfile,"./%s",CONFIG_FILE);
  status = daqDA_DB_getFile(CONFIG_FILE,localfile);
  if (status) {
    printf("Failed to get configuration file (%s) from DAQdetDB, status=%d\n", CONFIG_FILE, status);
    return -1;
  }
  AliTPCConfigDA config(CONFIG_FILE);
  // check configuration options
  TString laserTriggerName("C0LSR-ABCE-NOPF-CENT");
  size_t  bufferSize=30;
  Int_t   forceTriggerId=-1;
  Int_t   forceNeventsStandalone=-1;
  Bool_t  forceBufferEndsGlobal=kTRUE;
//   Bool_t  forceBufferEndsGlobalDummy=kFALSE;
  if ( config.GetConfigurationMap()->GetValue("LaserTriggerName") ) {
    laserTriggerName=config.GetConfigurationMap()->GetValue("LaserTriggerName")->GetName();
    printf("Laser trigger class name set to: %s.\n",laserTriggerName.Data());
  }

  if ( config.GetConfigurationMap()->GetValue("BufferSize") ) {
    bufferSize=(size_t)config.GetValue("BufferSize");
    printf("Setting event buffer size to: %d.\n",bufferSize);
  }

  if ( config.GetConfigurationMap()->GetValue("ForceTriggerId") ) {
    forceTriggerId=TMath::Nint(config.GetValue("ForceTriggerId"));
    printf("Only processing triggers with Id: %d.\n",forceTriggerId);
  }

  if ( config.GetConfigurationMap()->GetValue("ForceBufferEndsGlobal") ) {
    forceBufferEndsGlobal=config.GetValue("ForceBufferEndsGlobal")!=0.;
    printf("Process all buffered events in global partition: %s.\n",forceBufferEndsGlobal?"yes":"no");
  }

  if ( config.GetConfigurationMap()->GetValue("ForceNMaxEvents") ) {
    forceNevents=TMath::Nint(config.GetValue("ForceNMaxEvents"));
    printf("Forcing maximum number of %d events.\n",forceNeventsStandalone);
  }

  //subsribe to laser triggers only in physics partition
  //if the trigger class is not available the return value is -1
  //in this case we are most probably running as a standalone
  //  laser run and should request all events
  unsigned char *classIdptr=0;
  int retClassId=daqDA_getClassIdFromName(laserTriggerName.Data(),classIdptr);
  if (retClassId==0){
    //interleaved laser in physics runs
    char c[5];
    sprintf(c,"%u",*classIdptr);
    char *table[5] = {"PHY","Y","*",c,NULL};
    monitorDeclareTableExtended(table);
    printf("Using trigger class Id: %s\n",c);
//     forceBufferEndsGlobal=forceBufferEndsGlobalDummy;
  } else if (retClassId==-1){
    //defaul case, accept all physics events
    char *table[3] = {"PHY","Y",NULL};
    monitorDeclareTableExtended(table);
    printf("Using all trigger class Ids\n");
//     forceNevents=forceNeventsStandalone;
  } else {
    printf("Unknown return value of 'daqDA_getClassIdFromName': %d\n",retClassId);
    return -2;
  }

  //see if we should force the trigger id
  if (forceTriggerId>-1){
    char c[5];
    sprintf(c,"%d",forceTriggerId);
    char *table[5] = {"PHY","Y","*",c,NULL};
    monitorDeclareTableExtended(table);
//     forceBufferEndsGlobal=forceBufferEndsGlobalDummy;
  }

  // if  test setup get parameters from $DAQDA_TEST_DIR
  if (!mapping){
    /* copy locally the mapping file from daq detector config db */
    sprintf(localfile,"./%s",MAPPING_FILE);
    status = daqDA_DB_getFile(MAPPING_FILE,localfile);
    if (status) {
      printf("Failed to get mapping file (%s) from DAQdetDB, status=%d\n", MAPPING_FILE, status);
      return -1;
    }

    /* open the mapping file and retrieve mapping object */
    TFile *fileMapping = new TFile(MAPPING_FILE, "read");
    mapping = (AliTPCmapper*) fileMapping->Get("tpcMapping");
    delete fileMapping;
  }

  if (mapping == 0) {
    printf("Failed to get mapping object from %s.  ...\n", MAPPING_FILE);
    return -1;
  } else {
    printf("Got mapping object from %s\n", MAPPING_FILE);
  }

  //create calibration object
  AliTPCCalibCE calibCE(config.GetConfigurationMap());   // central electrode calibration
  calibCE.SetAltroMapping(mapping->GetAltroMapping()); // Use altro mapping we got from daqDetDb

  //
  // start thread
  //
//   sleep(5);
  pthread_t threadId=0;
  int threadStatus=0;
  threadStatus = pthread_create( &threadId, NULL, processEventBuffer, (void*)(&calibCE));
  eventBuffer.resize(bufferSize);
  struct timespec duree_out;
  //===========================//
  // loop over RAW data files //
  //==========================//
  int nevents=0;
  size_t counter=0;
  for ( i=1; i<argc; i++) {

    /* define data source : this is argument i */
    printf("Processing file %s\n", argv[i]);
    status=monitorSetDataSource( argv[i] );
    if (status!=0) {
      printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
      return -1;
    }

    /* read until EOF */
    while (true) {
      struct eventHeaderStruct *event;

      /* check shutdown condition */
      if (daqDA_checkShutdown()) {break;}

      //check for predefined number of events
      if (forceNevents>0 && calibCE.GetNeventsProcessed()>=forceNevents) {
        printf("Requested number of events reached (%d).\n",forceNevents);
        break;
      }

      //buffer events, only read them if a buffer position is free
      if (eventBuffer[counter]==0) {

        /* get next event (blocking call until timeout) */
        status=monitorGetEventDynamic((void **)&event);
        if (status==MON_ERR_EOF) {
          printf ("End of File %d detected\n",i);
          break; /* end of monitoring file has been reached */
        }

        if (status!=0) {
          printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
          break;
        }

        /* retry if got no event */
        if (event==NULL)
          continue;

      /* skip start/end of run events */
        if ( (event->eventType != physicsEvent) && (event->eventType != calibrationEvent) ){
          free(event);
          continue;
        }

        // get the run number
        runNb = event->eventRunNb;

//         printf(" trigger (%05d-%03d) = %8.8x %8.8x - %02u\n",nevents, calibCE.GetNeventsProcessed(),
//                event->eventTriggerPattern[1], event->eventTriggerPattern[0],event->eventType);

//         printf("filling buffer %d\n",counter);
        eventBuffer[counter]=event;

        ++nevents;
        ++counter;
        if (counter >= eventBuffer.size()) {counter=0;}
      }else{
//         printf("buffer already used: %d\n",counter);
        nanosleep(&duree_nanosleep,&duree_out);
      }
    }
  }

  //
  // wait for thread to end
  //
  if (!forceBufferEndsGlobal) bStop = true;
  else forceBufferEnds=forceBufferEndsGlobal;

  pthread_join( threadId, NULL);
//   printf("Event Processing Thread ended with: %d\n",threadStatus);

  //
  // free unprocessed events
  //
  for (size_t i=0;i<eventBuffer.size();++i){
    if (eventBuffer[i]) {
      free(eventBuffer[i]);
      eventBuffer[i]=0;
//       printf("freeing buffer %d\n",i);
    }
  }

  //
  // Analyse CE data and write them to rootfile
  //
  calibCE.Analyse();
  printf ("%d events processed, %d used\n",nevents,calibCE.GetNeventsProcessed());

  TFile * fileTPC = new TFile (RESULT_FILE,"recreate");
  calibCE.Write("tpcCalibCE");
  delete fileTPC;
  printf("Wrote %s\n",RESULT_FILE);

  /* store the result file on FES */

  status=daqDA_FES_storeFile(RESULT_FILE,FILE_ID);
  if (status) {
    status = -2;
  }

  SendToAmoreDB(calibCE,runNb);

  return status;
}

void *processEventBuffer(void *arg)
{
  //
  // event procssing thread functio
  //

  //cast argument
  AliTPCCalibCE *ce=(AliTPCCalibCE*)arg;
  AliTPCCalibCE &calibCE=*ce;

  size_t counter=0;
  unsigned long32 runNb=0;
  Bool_t published=kTRUE;
  struct timespec duree_out;

  struct eventHeaderStruct *event;

  //wait for the first buffer to be filled
  while (!eventBuffer[0]) nanosleep(&duree_nanosleep,&duree_out);
  //loop over buffer
  while (!bStop){
//     printf("testing buffer: %d\n",counter);
    if (eventBuffer[counter]) {
      event=eventBuffer[counter];
      runNb = event->eventRunNb;
//       printf("processing buffer: %d\n",counter);
      eventBuffer[counter]=0;
      calibCE.ProcessEvent(event);
      free(event);
      published=kFALSE;
    } else {
      //in case of empty buffer publish the results it this was not done
      if (!published) {
        SendToAmoreDB(calibCE,runNb);
        published=kTRUE;
      }
      nanosleep(&duree_nanosleep,&duree_out);
    }
    ++counter;
    if (counter >= eventBuffer.size()) {
      counter=0;
      if (forceBufferEnds) break;
    }
  }
}

void SendToAmoreDB(AliTPCCalibCE &calibCE, unsigned long32 runNb)
{
  //AMORE
  printf ("AMORE part\n");
  const char *amoreDANameorig=gSystem->Getenv("AMORE_DA_NAME");
  //cheet a little -- temporary solution (hopefully)
  //
  //currently amoreDA uses the environment variable AMORE_DA_NAME to create the mysql
  //table in which the calib objects are stored. This table is dropped each time AmoreDA
  //is initialised. This of course makes a problem if we would like to store different
  //calibration entries in the AMORE DB. Therefore in each DA which writes to the AMORE DB
  //the AMORE_DA_NAME env variable is overwritten.
  gSystem->Setenv("AMORE_DA_NAME",Form("TPC-%s",FILE_ID));
  //
  // end cheet
  TGraph *grA=calibCE.MakeGraphTimeCE(-1,0,2);
  TGraph *grC=calibCE.MakeGraphTimeCE(-2,0,2);
  TDatime time;
  TObjString info(Form("Run: %u; Date: %s",runNb,time.AsSQLString()));
  amore::da::AmoreDA amoreDA(amore::da::AmoreDA::kSender);
  Int_t statusDA=0;
  statusDA+=amoreDA.Send("CET0",calibCE.GetCalPadT0());
  statusDA+=amoreDA.Send("CEQ",calibCE.GetCalPadQ());
  statusDA+=amoreDA.Send("CERMS",calibCE.GetCalPadRMS());
  statusDA+=amoreDA.Send("DriftA",grA);
  statusDA+=amoreDA.Send("DriftC",grC);
  statusDA+=amoreDA.Send("Info",&info);
  if ( statusDA!=0 )
    printf("Waring: Failed to write one of the calib objects to the AMORE database\n");
  // reset env var
  if (amoreDANameorig) gSystem->Setenv("AMORE_DA_NAME",amoreDANameorig);
  if (grA) delete grA;
  if (grC) delete grC;
}

<|endoftext|>


<commit_before>#include <QFileDialog>
#include <QMessageBox>
#include "../QSCPIDev/qserial.h"
#include "configui.h"
#include "ui_configui.h"

ConfigUI::ConfigUI(QWidget *parent) :
    QDialog(parent),
    config(),
    ui(new Ui::ConfigUI)
{
    ui->setupUi(this);
    QStringList ports = QSerial::list();
    ui->eurothermPortComboBox->addItems(ports);
    ui->hp34970PortComboBox->addItems(ports);
    ui->msdpPortComboBox->addItems(ports);
    ui->ps6220PortComboBox->addItems(ports);

    ui->dataDirLineEdit->setText(config.dataDir());
    ui->eurothermPortComboBox->setEditText(config.eurothermPort());
    ui->eurothermSleaveSpinBox->setValue(config.eurothermSlave());
    ui->hp34970PortComboBox->setEditText(config.hp34970Port());
    ui->msdpPortComboBox->setEditText(config.msdpPort());
    ui->ps6220PortComboBox->setEditText(config.ps6220Port());

    ui->devicesTableWidget->setVisible(false);
    QSize s(size());
    s.setHeight(0);
    resize(s);
}

ConfigUI::~ConfigUI()
{
    delete ui;
}

void ConfigUI::accept()
{
    QDir dataDir(ui->dataDirLineEdit->text());

    if (!dataDir.exists()) {
        QString msg("Directory: \"" + dataDir.path() +
                    "\"\ndoes not exists.\nCreate this directory?");
        if (QMessageBox::Yes != QMessageBox::question(
                    this, "Create data storage directory?", msg,
                    QMessageBox::Yes | QMessageBox::No)) {
            return;
        }
        if (!dataDir.mkpath(".")) {
            msg = "Failed to create directory: \"" + dataDir.path() + "\"";
            QMessageBox::critical(this, "Failed to create directory.", msg);
            return;
        }
    }

    config.setDataDir(dataDir.path());
    config.setEurothermPort(ui->eurothermPortComboBox->currentText());
    config.setEurothermSlave(ui->eurothermSleaveSpinBox->value());
    config.setHp34970Port(ui->hp34970PortComboBox->currentText());
    config.setMsdpPort(ui->msdpPortComboBox->currentText());
    config.setPs6220Port(ui->ps6220PortComboBox->currentText());

    QDialog::accept();
}

void ConfigUI::on_dataDirToolButton_clicked()
{
    QString dirName = QFileDialog::getExistingDirectory(
                this, "Directory to store experiment progress logs.");
    if (dirName.isEmpty())
        return;

    ui->dataDirLineEdit->setText(dirName);
}

void ConfigUI::on_detectPushButton_clicked()
{
    ui->detectPushButton->setVisible(false);
    ui->devicesTableWidget->setVisible(true);

    on_detectPushButton_clicked();
}

void ConfigUI::on_devicesRefreshToolButton_clicked()
{
    ui->devicesTableWidget->setRowCount(0);
     const QSerialPortProbe::DeviceList &devices = probe.list();
     ui->devicesTableWidget->setRowCount(devices.size());

     int row(0);
     for (QSerialPortProbe::DeviceList::ConstIterator i(devices.begin());
                                                        i != devices.end();
                                                        ++i) {
         QTableWidgetItem *item;

         item = new QTableWidgetItem(i->port());
         ui->devicesTableWidget->setItem(row, 0, item);

         item = new QTableWidgetItem(i->protocolString());
         ui->devicesTableWidget->setItem(row, 1, item);

         item = new QTableWidgetItem(i->deviceName());
         ui->devicesTableWidget->setItem(row, 2, item);
         ++row;
     }
}
<commit_msg>simlify device listing<commit_after>#include <QFileDialog>
#include <QMessageBox>
#include "../QSCPIDev/qserial.h"
#include "configui.h"
#include "ui_configui.h"

ConfigUI::ConfigUI(QWidget *parent) :
    QDialog(parent),
    config(),
    ui(new Ui::ConfigUI)
{
    ui->setupUi(this);
    QStringList ports = QSerial::list();
    ui->eurothermPortComboBox->addItems(ports);
    ui->hp34970PortComboBox->addItems(ports);
    ui->msdpPortComboBox->addItems(ports);
    ui->ps6220PortComboBox->addItems(ports);

    ui->dataDirLineEdit->setText(config.dataDir());
    ui->eurothermPortComboBox->setEditText(config.eurothermPort());
    ui->eurothermSleaveSpinBox->setValue(config.eurothermSlave());
    ui->hp34970PortComboBox->setEditText(config.hp34970Port());
    ui->msdpPortComboBox->setEditText(config.msdpPort());
    ui->ps6220PortComboBox->setEditText(config.ps6220Port());

    ui->devicesTableWidget->setVisible(false);
    QSize s(size());
    s.setHeight(0);
    resize(s);
}

ConfigUI::~ConfigUI()
{
    delete ui;
}

void ConfigUI::accept()
{
    QDir dataDir(ui->dataDirLineEdit->text());

    if (!dataDir.exists()) {
        QString msg("Directory: \"" + dataDir.path() +
                    "\"\ndoes not exists.\nCreate this directory?");
        if (QMessageBox::Yes != QMessageBox::question(
                    this, "Create data storage directory?", msg,
                    QMessageBox::Yes | QMessageBox::No)) {
            return;
        }
        if (!dataDir.mkpath(".")) {
            msg = "Failed to create directory: \"" + dataDir.path() + "\"";
            QMessageBox::critical(this, "Failed to create directory.", msg);
            return;
        }
    }

    config.setDataDir(dataDir.path());
    config.setEurothermPort(ui->eurothermPortComboBox->currentText());
    config.setEurothermSlave(ui->eurothermSleaveSpinBox->value());
    config.setHp34970Port(ui->hp34970PortComboBox->currentText());
    config.setMsdpPort(ui->msdpPortComboBox->currentText());
    config.setPs6220Port(ui->ps6220PortComboBox->currentText());

    QDialog::accept();
}

void ConfigUI::on_dataDirToolButton_clicked()
{
    QString dirName = QFileDialog::getExistingDirectory(
                this, "Directory to store experiment progress logs.");
    if (dirName.isEmpty())
        return;

    ui->dataDirLineEdit->setText(dirName);
}

void ConfigUI::on_detectPushButton_clicked()
{
    ui->detectPushButton->setVisible(false);
    ui->devicesTableWidget->setVisible(true);

    on_detectPushButton_clicked();
}

void ConfigUI::on_devicesRefreshToolButton_clicked()
{
    ui->devicesTableWidget->setRowCount(0);
     const QSerialPortProbe::DeviceList &devices = probe.list();
     ui->devicesTableWidget->setRowCount(devices.size());

     for (int row(0); row < devices.size(); ++row) {
         const QSerialPortProbe::Device &device(devices[row]);
         QTableWidgetItem *item;

         item = new QTableWidgetItem(device.port());
         ui->devicesTableWidget->setItem(row, 0, item);

         item = new QTableWidgetItem(device.protocolString());
         ui->devicesTableWidget->setItem(row, 1, item);

         item = new QTableWidgetItem(device.deviceName());
         ui->devicesTableWidget->setItem(row, 2, item);
     }
}
<|endoftext|>


<commit_before>/*
** Copyright 2014 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <QVariant>
#include <QSqlError>
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/notification/objects/command.hh"
#include "com/centreon/broker/notification/loaders/command_loader.hh"

using namespace com::centreon::broker::notification;
using namespace com::centreon::broker::notification::objects;

command_loader::command_loader() {}

/**
 *  Load the commands from the database.
 *
 *  @param[in] db       An open connection to the database.
 * @param[out] output   A command builder object to register the commands.
 */
void command_loader::load(QSqlDatabase* db, command_builder* output) {
  // If we don't have any db or output, don't do anything.
  if (!db || !output)
    return;

  logging::debug(logging::medium)
    << "notification: loading commands from the database";

  QSqlQuery query(*db);

  // Performance improvement, as we never go back.
  query.setForwardOnly(true);

  // Load the commands
  if (!query.exec("SELECT command_id, connector_id, command_name, command_line,"
                  "       command_example, command_type, enable_shell,"
                  "       command_comment, graph_id, cmd_cat_id"
                  "  FROM cfg_commands"))
    throw (exceptions::msg()
           << "notification: cannot load commands from database: "
           << query.lastError().text());

  while (query.next()) {
    unsigned int id = query.value(0).toUInt();
    std::string base_command = query.value(3).toString().toStdString();
    command::ptr com(new command(base_command));
    com->set_name(query.value(2).toString().toStdString());

    output->add_command(id, com);
  }
}
<commit_msg>notification: do not read non-existent properties of cfg_commands.<commit_after>/*
** Copyright 2014 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include <QVariant>
#include <QSqlError>
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/notification/objects/command.hh"
#include "com/centreon/broker/notification/loaders/command_loader.hh"

using namespace com::centreon::broker::notification;
using namespace com::centreon::broker::notification::objects;

command_loader::command_loader() {}

/**
 *  Load the commands from the database.
 *
 *  @param[in] db       An open connection to the database.
 * @param[out] output   A command builder object to register the commands.
 */
void command_loader::load(QSqlDatabase* db, command_builder* output) {
  // If we don't have any db or output, don't do anything.
  if (!db || !output)
    return;

  logging::debug(logging::medium)
    << "notification: loading commands from the database";

  QSqlQuery query(*db);

  // Performance improvement, as we never go back.
  query.setForwardOnly(true);

  // Load the commands
  if (!query.exec("SELECT command_id, connector_id, command_name, command_line,"
                  "       command_type, enable_shell"
                  "  FROM cfg_commands"))
    throw (exceptions::msg()
           << "notification: cannot load commands from database: "
           << query.lastError().text());

  while (query.next()) {
    unsigned int id = query.value(0).toUInt();
    std::string base_command = query.value(3).toString().toStdString();
    command::ptr com(new command(base_command));
    com->set_name(query.value(2).toString().toStdString());

    output->add_command(id, com);
  }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: lngprops.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2004-11-27 13:19:32 $
 *
 *  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 _LINGUISTIC_LNGPROPS_HHX_
#define _LINGUISTIC_LNGPROPS_HHX_

#ifndef _SVTOOLS_LINGUPROPS_HXX_
#include <svtools/linguprops.hxx>
#endif

// maximal number of suggestions to be returned in spelling  context-menu
// (may not include results added by looking up user dictionaries)
#define UPN_MAX_NUMBER_OF_SUGGESTIONS       "MaxNumberOfSuggestions"

// WIDs for property names
//!! Don't change values! They are used as the property handles in
//!! the service description
#define WID_IS_GERMAN_PRE_REFORM            UPH_IS_GERMAN_PRE_REFORM
#define WID_IS_USE_DICTIONARY_LIST          UPH_IS_USE_DICTIONARY_LIST
#define WID_IS_IGNORE_CONTROL_CHARACTERS    UPH_IS_IGNORE_CONTROL_CHARACTERS
#define WID_IS_SPELL_UPPER_CASE             UPH_IS_SPELL_UPPER_CASE
#define WID_IS_SPELL_WITH_DIGITS            UPH_IS_SPELL_WITH_DIGITS
#define WID_IS_SPELL_CAPITALIZATION         UPH_IS_SPELL_CAPITALIZATION
#define WID_HYPH_MIN_LEADING                UPH_HYPH_MIN_LEADING
#define WID_HYPH_MIN_TRAILING               UPH_HYPH_MIN_TRAILING
#define WID_HYPH_MIN_WORD_LENGTH            UPH_HYPH_MIN_WORD_LENGTH
#define WID_DEFAULT_LOCALE                  UPH_DEFAULT_LOCALE
#define WID_IS_SPELL_AUTO                   UPH_IS_SPELL_AUTO
#define WID_IS_SPELL_HIDE                   UPH_IS_SPELL_HIDE
#define WID_IS_SPELL_IN_ALL_LANGUAGES       UPH_IS_SPELL_IN_ALL_LANGUAGES
#define WID_IS_SPELL_SPECIAL                UPH_IS_SPELL_SPECIAL
#define WID_IS_HYPH_AUTO                    UPH_IS_HYPH_AUTO
#define WID_IS_HYPH_SPECIAL                 UPH_IS_HYPH_SPECIAL
#define WID_IS_WRAP_REVERSE                 UPH_IS_WRAP_REVERSE
#define WID_DEFAULT_LANGUAGE                UPH_DEFAULT_LANGUAGE
#define WID_DEFAULT_LOCALE_CJK              UPH_DEFAULT_LOCALE_CJK
#define WID_DEFAULT_LOCALE_CTL              UPH_DEFAULT_LOCALE_CTL

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.5.24); FILE MERGED 2005/09/05 17:29:31 rt 1.5.24.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: lngprops.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 19:46:35 $
 *
 *  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 _LINGUISTIC_LNGPROPS_HHX_
#define _LINGUISTIC_LNGPROPS_HHX_

#ifndef _SVTOOLS_LINGUPROPS_HXX_
#include <svtools/linguprops.hxx>
#endif

// maximal number of suggestions to be returned in spelling  context-menu
// (may not include results added by looking up user dictionaries)
#define UPN_MAX_NUMBER_OF_SUGGESTIONS       "MaxNumberOfSuggestions"

// WIDs for property names
//!! Don't change values! They are used as the property handles in
//!! the service description
#define WID_IS_GERMAN_PRE_REFORM            UPH_IS_GERMAN_PRE_REFORM
#define WID_IS_USE_DICTIONARY_LIST          UPH_IS_USE_DICTIONARY_LIST
#define WID_IS_IGNORE_CONTROL_CHARACTERS    UPH_IS_IGNORE_CONTROL_CHARACTERS
#define WID_IS_SPELL_UPPER_CASE             UPH_IS_SPELL_UPPER_CASE
#define WID_IS_SPELL_WITH_DIGITS            UPH_IS_SPELL_WITH_DIGITS
#define WID_IS_SPELL_CAPITALIZATION         UPH_IS_SPELL_CAPITALIZATION
#define WID_HYPH_MIN_LEADING                UPH_HYPH_MIN_LEADING
#define WID_HYPH_MIN_TRAILING               UPH_HYPH_MIN_TRAILING
#define WID_HYPH_MIN_WORD_LENGTH            UPH_HYPH_MIN_WORD_LENGTH
#define WID_DEFAULT_LOCALE                  UPH_DEFAULT_LOCALE
#define WID_IS_SPELL_AUTO                   UPH_IS_SPELL_AUTO
#define WID_IS_SPELL_HIDE                   UPH_IS_SPELL_HIDE
#define WID_IS_SPELL_IN_ALL_LANGUAGES       UPH_IS_SPELL_IN_ALL_LANGUAGES
#define WID_IS_SPELL_SPECIAL                UPH_IS_SPELL_SPECIAL
#define WID_IS_HYPH_AUTO                    UPH_IS_HYPH_AUTO
#define WID_IS_HYPH_SPECIAL                 UPH_IS_HYPH_SPECIAL
#define WID_IS_WRAP_REVERSE                 UPH_IS_WRAP_REVERSE
#define WID_DEFAULT_LANGUAGE                UPH_DEFAULT_LANGUAGE
#define WID_DEFAULT_LOCALE_CJK              UPH_DEFAULT_LOCALE_CJK
#define WID_DEFAULT_LOCALE_CTL              UPH_DEFAULT_LOCALE_CTL

#endif

<|endoftext|>


<commit_before>#include "karabiner_virtual_hid_device_methods.hpp"
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/hid/IOHIDDevice.h>
#include <IOKit/hid/IOHIDElement.h>
#include <IOKit/hid/IOHIDManager.h>
#include <IOKit/hid/IOHIDQueue.h>
#include <IOKit/hid/IOHIDValue.h>
#include <IOKit/hidsystem/IOHIDLib.h>
#include <IOKit/hidsystem/IOHIDShared.h>
#include <IOKit/hidsystem/ev_keymap.h>
#include <SystemConfiguration/SystemConfiguration.h>
#include <cmath>
#include <iostream>
#include <thread>

int main(int argc, const char* argv[]) {
  if (getuid() != 0) {
    std::cerr << "modifier_flag_manipulate_example requires root privilege." << std::endl;
  }

  kern_return_t kr;
  io_connect_t connect = IO_OBJECT_NULL;
  auto service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceNameMatching(pqrs::karabiner_virtual_hid_device::get_virtual_hid_root_name()));
  if (!service) {
    std::cerr << "IOServiceGetMatchingService error" << std::endl;
    goto finish;
  }

  kr = IOServiceOpen(service, mach_task_self(), kIOHIDServerConnectType, &connect);
  if (kr != KERN_SUCCESS) {
    std::cerr << "IOServiceOpen error" << std::endl;
    goto finish;
  }

  kr = pqrs::karabiner_virtual_hid_device_methods::initialize_virtual_hid_keyboard(connect);
  if (kr != KERN_SUCCESS) {
    std::cerr << "initialize_virtual_hid_keyboard error" << std::endl;
  }
  std::this_thread::sleep_for(std::chrono::milliseconds(500));

  {
    std::cout << "left control by virtual_hid_keyboard (3 seconds)" << std::endl;

    pqrs::karabiner_virtual_hid_device::hid_report::keyboard_input report;
    report.modifiers = 0x01;

    kr = pqrs::karabiner_virtual_hid_device_methods::post_keyboard_input_report(connect, report);
    if (kr != KERN_SUCCESS) {
      std::cerr << "post_keyboard_input_report error" << std::endl;
    }

    for (int i = 0; i < 3; ++i) {
      std::this_thread::sleep_for(std::chrono::milliseconds(1000));
      std::cout << (i + 1) << std::endl;
    }
  }

  {
    std::cout << "left control by VirtualHIDEventService (3 seconds)" << std::endl;

    pqrs::karabiner_virtual_hid_device::hid_event_service::keyboard_event keyboard_event;
    keyboard_event.usage = kHIDUsage_KeyboardRightControl;
    keyboard_event.value = 1;

    kr = pqrs::karabiner_virtual_hid_device_methods::dispatch_keyboard_event(connect, keyboard_event);
    if (kr != KERN_SUCCESS) {
      std::cerr << "dispatch_keyboard_event error" << std::endl;
    }

    for (int i = 0; i < 3; ++i) {
      std::this_thread::sleep_for(std::chrono::milliseconds(1000));
      std::cout << (i + 1) << std::endl;
    }

    keyboard_event.value = 0;

    kr = pqrs::karabiner_virtual_hid_device_methods::dispatch_keyboard_event(connect, keyboard_event);
    if (kr != KERN_SUCCESS) {
      std::cerr << "dispatch_keyboard_event error" << std::endl;
    }
  }

  {
    std::cout << "left control by post_keyboard_event (3 seconds)" << std::endl;

    pqrs::karabiner_virtual_hid_device::keyboard_event keyboard_event;
    keyboard_event.event_type = pqrs::karabiner_virtual_hid_device::event_type::flags_changed;
    keyboard_event.key = 0x3b;
    keyboard_event.flags = 0x40001;

    kr = pqrs::karabiner_virtual_hid_device_methods::post_keyboard_event(connect, keyboard_event);
    if (kr != KERN_SUCCESS) {
      std::cerr << "post_keyboard_event error" << std::endl;
    }

    for (int i = 0; i < 3; ++i) {
      std::this_thread::sleep_for(std::chrono::milliseconds(1000));
      std::cout << (i + 1) << std::endl;
    }

    keyboard_event.flags = 0;

    kr = pqrs::karabiner_virtual_hid_device_methods::post_keyboard_event(connect, keyboard_event);
    if (kr != KERN_SUCCESS) {
      std::cerr << "post_keyboard_event error" << std::endl;
    }
  }

  {
    std::cout << "left control by IOHIDPostEvent (3 seconds)" << std::endl;

    uid_t uid;
    if (auto user_name = SCDynamicStoreCopyConsoleUser(nullptr, &uid, nullptr)) {
      CFRelease(user_name);

      setuid(uid);

      if (auto hid_system = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceNameMatching(kIOHIDSystemClass))) {
        io_connect_t hid_system_connect = IO_OBJECT_NULL;
        kr = IOServiceOpen(hid_system, mach_task_self(), kIOHIDParamConnectType, &hid_system_connect);
        if (kr != KERN_SUCCESS) {
          std::cerr << "IOServiceOpen error" << std::endl;
        } else {
          IOGPoint location{};
          NXEventData event_data{};
          event_data.key.keyCode = 0x3b;
          uint32_t event_data_version = kNXEventDataVersion;
          IOOptionBits event_flags = 0x40001;
          IOOptionBits options = kIOHIDSetGlobalEventFlags;

          kr = IOHIDPostEvent(hid_system_connect, NX_FLAGSCHANGED, location, &event_data, event_data_version, event_flags, options);
          if (kr != KERN_SUCCESS) {
            std::cerr << "IOHIDPostEvent error" << std::endl;
          }

          for (int i = 0; i < 3; ++i) {
            std::this_thread::sleep_for(std::chrono::milliseconds(1000));
            std::cout << (i + 1) << std::endl;
          }

          event_flags = 0;

          kr = IOHIDPostEvent(hid_system_connect, NX_FLAGSCHANGED, location, &event_data, event_data_version, event_flags, options);
          if (kr != KERN_SUCCESS) {
            std::cerr << "IOHIDPostEvent error" << std::endl;
          }
        }
      }
    }
  }

  kr = pqrs::karabiner_virtual_hid_device_methods::terminate_virtual_hid_keyboard(connect);
  if (kr != KERN_SUCCESS) {
    std::cerr << "terminate_virtual_hid_keyboard error" << std::endl;
  }

finish:
  if (connect) {
    IOServiceClose(connect);
  }
  if (service) {
    IOObjectRelease(service);
  }

  return 0;
}
<commit_msg>fix modifier_flag_manipulate_example<commit_after>#include "karabiner_virtual_hid_device_methods.hpp"
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
#include <IOKit/hid/IOHIDDevice.h>
#include <IOKit/hid/IOHIDElement.h>
#include <IOKit/hid/IOHIDManager.h>
#include <IOKit/hid/IOHIDQueue.h>
#include <IOKit/hid/IOHIDValue.h>
#include <IOKit/hidsystem/IOHIDLib.h>
#include <IOKit/hidsystem/IOHIDShared.h>
#include <IOKit/hidsystem/ev_keymap.h>
#include <SystemConfiguration/SystemConfiguration.h>
#include <cmath>
#include <iostream>
#include <thread>

int main(int argc, const char* argv[]) {
  if (getuid() != 0) {
    std::cerr << "modifier_flag_manipulate_example requires root privilege." << std::endl;
  }

  kern_return_t kr;
  io_connect_t connect = IO_OBJECT_NULL;
  auto service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceNameMatching(pqrs::karabiner_virtual_hid_device::get_virtual_hid_root_name()));
  if (!service) {
    std::cerr << "IOServiceGetMatchingService error" << std::endl;
    goto finish;
  }

  kr = IOServiceOpen(service, mach_task_self(), kIOHIDServerConnectType, &connect);
  if (kr != KERN_SUCCESS) {
    std::cerr << "IOServiceOpen error" << std::endl;
    goto finish;
  }

  kr = pqrs::karabiner_virtual_hid_device_methods::initialize_virtual_hid_keyboard(connect);
  if (kr != KERN_SUCCESS) {
    std::cerr << "initialize_virtual_hid_keyboard error" << std::endl;
  }
  std::this_thread::sleep_for(std::chrono::milliseconds(500));

  {
    std::cout << "left control by dispatch_keyboard_event (3 seconds)" << std::endl;

    pqrs::karabiner_virtual_hid_device::hid_event_service::keyboard_event keyboard_event;
    keyboard_event.usage = kHIDUsage_KeyboardLeftControl;
    keyboard_event.value = 1;

    kr = pqrs::karabiner_virtual_hid_device_methods::dispatch_keyboard_event(connect, keyboard_event);
    if (kr != KERN_SUCCESS) {
      std::cerr << "dispatch_keyboard_event error" << std::endl;
    }

    for (int i = 0; i < 3; ++i) {
      std::this_thread::sleep_for(std::chrono::milliseconds(1000));
      std::cout << (i + 1) << std::endl;
    }

    keyboard_event.value = 0;

    kr = pqrs::karabiner_virtual_hid_device_methods::dispatch_keyboard_event(connect, keyboard_event);
    if (kr != KERN_SUCCESS) {
      std::cerr << "dispatch_keyboard_event error" << std::endl;
    }
  }

  {
    std::cout << "left control by post_keyboard_input_report (3 seconds)" << std::endl;

    pqrs::karabiner_virtual_hid_device::hid_report::keyboard_input report;
    report.modifiers = 0x01;

    kr = pqrs::karabiner_virtual_hid_device_methods::post_keyboard_input_report(connect, report);
    if (kr != KERN_SUCCESS) {
      std::cerr << "post_keyboard_input_report error" << std::endl;
    }

    for (int i = 0; i < 3; ++i) {
      std::this_thread::sleep_for(std::chrono::milliseconds(1000));
      std::cout << (i + 1) << std::endl;
    }

    report.modifiers = 0;

    kr = pqrs::karabiner_virtual_hid_device_methods::post_keyboard_input_report(connect, report);
    if (kr != KERN_SUCCESS) {
      std::cerr << "post_keyboard_input_report error" << std::endl;
    }
  }

  {
    std::cout << "left control by IOHIDPostEvent (3 seconds)" << std::endl;

    uid_t uid;
    if (auto user_name = SCDynamicStoreCopyConsoleUser(nullptr, &uid, nullptr)) {
      CFRelease(user_name);

      setuid(uid);

      if (auto hid_system = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceNameMatching(kIOHIDSystemClass))) {
        io_connect_t hid_system_connect = IO_OBJECT_NULL;
        kr = IOServiceOpen(hid_system, mach_task_self(), kIOHIDParamConnectType, &hid_system_connect);
        if (kr != KERN_SUCCESS) {
          std::cerr << "IOServiceOpen error" << std::endl;
        } else {
          IOGPoint location{};
          NXEventData event_data{};
          event_data.key.keyCode = 0x3b;
          uint32_t event_data_version = kNXEventDataVersion;
          IOOptionBits event_flags = 0x40001;
          IOOptionBits options = kIOHIDSetGlobalEventFlags;

          kr = IOHIDPostEvent(hid_system_connect, NX_FLAGSCHANGED, location, &event_data, event_data_version, event_flags, options);
          if (kr != KERN_SUCCESS) {
            std::cerr << "IOHIDPostEvent error" << std::endl;
          }

          for (int i = 0; i < 3; ++i) {
            std::this_thread::sleep_for(std::chrono::milliseconds(1000));
            std::cout << (i + 1) << std::endl;
          }

          event_flags = 0;

          kr = IOHIDPostEvent(hid_system_connect, NX_FLAGSCHANGED, location, &event_data, event_data_version, event_flags, options);
          if (kr != KERN_SUCCESS) {
            std::cerr << "IOHIDPostEvent error" << std::endl;
          }
        }
      }
    }
  }

  kr = pqrs::karabiner_virtual_hid_device_methods::terminate_virtual_hid_keyboard(connect);
  if (kr != KERN_SUCCESS) {
    std::cerr << "terminate_virtual_hid_keyboard error" << std::endl;
  }

finish:
  if (connect) {
    IOServiceClose(connect);
  }
  if (service) {
    IOObjectRelease(service);
  }

  return 0;
}
<|endoftext|>


<commit_before>#include "iteration/initializer/initialize_fixed_terms_once.h"

#include <array>

#include "system/system.h"
#include "formulation/updater/tests/fixed_updater_mock.h"
#include "test_helpers/gmock_wrapper.h"
#include "test_helpers/test_helper_functions.h"

namespace  {

using namespace bart;

using ::testing::NiceMock, ::testing::Ref, ::testing::Return;

class IterationInitializerInitializeFixedTermsOnceTest : public ::testing::Test {
 protected:
  using InitializerType = iteration::initializer::InitializeFixedTermsOnce;
  using MockFixedUpdaterType = formulation::updater::FixedUpdaterMock;

  IterationInitializerInitializeFixedTermsOnceTest()
      : total_groups_(test_helpers::RandomDouble(1, 5)),
        total_angles_(test_helpers::RandomDouble(1, 5)) {}

  // Initializer to be tested
  std::unique_ptr<InitializerType> test_initializer_;

  // Supporting objects
  system::System test_system_;

  // Pointers for observing mocks owned by other objects
  MockFixedUpdaterType* updater_obs_ptr_ = nullptr;

  // Random values for testing
  const int total_groups_;
  const int total_angles_;

  void SetUp() override;
};

void IterationInitializerInitializeFixedTermsOnceTest::SetUp() {
  // Set up testing object
  auto mock_fixed_updater_ptr =
      std::make_unique<MockFixedUpdaterType>();
  updater_obs_ptr_ = mock_fixed_updater_ptr.get();

  test_initializer_ =
      std::make_unique<InitializerType>(std::move(mock_fixed_updater_ptr),
                                        total_groups_,
                                        total_angles_);
}

TEST_F(IterationInitializerInitializeFixedTermsOnceTest, Constructor) {
  EXPECT_TRUE(updater_obs_ptr_ != nullptr);
  EXPECT_EQ(test_initializer_->total_angles(), total_angles_);
  EXPECT_EQ(test_initializer_->total_groups(), total_groups_);
}

TEST_F(IterationInitializerInitializeFixedTermsOnceTest, ConstructorThrows) {
  // Constructor should throw if fixed updater ptr is null
  std::unique_ptr<MockFixedUpdaterType> null_fixed_updater = nullptr;
  EXPECT_ANY_THROW(InitializerType initializer(std::move(null_fixed_updater),
                                               total_groups_, total_angles_););

  // Constructor should throw for bad groups and angle values
  std::array<int, 2> bad_values = {0, -1};

  for (int value : bad_values) {
    auto fixed_updater = std::make_unique<MockFixedUpdaterType>();
    EXPECT_ANY_THROW(InitializerType initializer(std::move(fixed_updater),
                                                 value, total_angles_););
    fixed_updater = std::make_unique<MockFixedUpdaterType>();
    EXPECT_ANY_THROW(InitializerType initializer(std::move(fixed_updater),
                                                 total_groups_, value););
  }
}

TEST_F(IterationInitializerInitializeFixedTermsOnceTest, Initialize) {
  // Initializer should access all left hand side terms (all groups/angles)
  for (int group = 0; group < total_groups_; ++group) {
    for (int angle = 0; angle < total_angles_; ++angle) {
      system::EnergyGroup energy_group(group);
      quadrature::QuadraturePointIndex angle_index(angle);
      EXPECT_CALL(*updater_obs_ptr_, UpdateFixedTerms(Ref(test_system_),
                                                      energy_group,
                                                      angle_index));
    }
  }
  EXPECT_FALSE(test_initializer_->initialize_was_called());
  test_initializer_->Initialize(test_system_);

  // Initialize shouldn't do anything because initialize has been called
  EXPECT_TRUE(test_initializer_->initialize_was_called());
  test_initializer_->Initialize(test_system_);

  // Reset status of initialize called
  test_initializer_->set_initialize_was_called(false);
  for (int group = 0; group < total_groups_; ++group) {
    for (int angle = 0; angle < total_angles_; ++angle) {
      system::EnergyGroup energy_group(group);
      quadrature::QuadraturePointIndex angle_index(angle);
      EXPECT_CALL(*updater_obs_ptr_, UpdateFixedTerms(Ref(test_system_),
                                                      energy_group,
                                                      angle_index));
    }
  }
  test_initializer_->Initialize(test_system_);
}

} // namespace<commit_msg>removed extra EXPECT_CALL statements from tests<commit_after>#include "iteration/initializer/initialize_fixed_terms_once.h"

#include <array>

#include "system/system.h"
#include "formulation/updater/tests/fixed_updater_mock.h"
#include "test_helpers/gmock_wrapper.h"
#include "test_helpers/test_helper_functions.h"

namespace  {

using namespace bart;

using ::testing::NiceMock, ::testing::Ref, ::testing::Return;

class IterationInitializerInitializeFixedTermsOnceTest : public ::testing::Test {
 protected:
  using InitializerType = iteration::initializer::InitializeFixedTermsOnce;
  using MockFixedUpdaterType = formulation::updater::FixedUpdaterMock;

  IterationInitializerInitializeFixedTermsOnceTest()
      : total_groups_(test_helpers::RandomDouble(1, 5)),
        total_angles_(test_helpers::RandomDouble(1, 5)) {}

  // Initializer to be tested
  std::unique_ptr<InitializerType> test_initializer_;

  // Supporting objects
  system::System test_system_;

  // Pointers for observing mocks owned by other objects
  MockFixedUpdaterType* updater_obs_ptr_ = nullptr;

  // Random values for testing
  const int total_groups_;
  const int total_angles_;

  void SetUp() override;
};

void IterationInitializerInitializeFixedTermsOnceTest::SetUp() {
  // Set up testing object
  auto mock_fixed_updater_ptr =
      std::make_unique<MockFixedUpdaterType>();
  updater_obs_ptr_ = mock_fixed_updater_ptr.get();

  test_initializer_ =
      std::make_unique<InitializerType>(std::move(mock_fixed_updater_ptr),
                                        total_groups_,
                                        total_angles_);
}

TEST_F(IterationInitializerInitializeFixedTermsOnceTest, Constructor) {
  EXPECT_TRUE(updater_obs_ptr_ != nullptr);
  EXPECT_EQ(test_initializer_->total_angles(), total_angles_);
  EXPECT_EQ(test_initializer_->total_groups(), total_groups_);
}

TEST_F(IterationInitializerInitializeFixedTermsOnceTest, ConstructorThrows) {
  // Constructor should throw if fixed updater ptr is null
  std::unique_ptr<MockFixedUpdaterType> null_fixed_updater = nullptr;
  EXPECT_ANY_THROW(InitializerType initializer(std::move(null_fixed_updater),
                                               total_groups_, total_angles_););

  // Constructor should throw for bad groups and angle values
  std::array<int, 2> bad_values = {0, -1};

  for (int value : bad_values) {
    auto fixed_updater = std::make_unique<MockFixedUpdaterType>();
    EXPECT_ANY_THROW(InitializerType initializer(std::move(fixed_updater),
                                                 value, total_angles_););
    fixed_updater = std::make_unique<MockFixedUpdaterType>();
    EXPECT_ANY_THROW(InitializerType initializer(std::move(fixed_updater),
                                                 total_groups_, value););
  }
}

TEST_F(IterationInitializerInitializeFixedTermsOnceTest, Initialize) {
  // Initializer should access all left hand side terms (all groups/angles)
  // This will run only twice despite us calling it three times.
  for (int group = 0; group < total_groups_; ++group) {
    for (int angle = 0; angle < total_angles_; ++angle) {
      system::EnergyGroup energy_group(group);
      quadrature::QuadraturePointIndex angle_index(angle);
      EXPECT_CALL(*updater_obs_ptr_, UpdateFixedTerms(Ref(test_system_),
                                                      energy_group,
                                                      angle_index))
          .Times(2);
    }
  }
  EXPECT_FALSE(test_initializer_->initialize_was_called());
  test_initializer_->Initialize(test_system_);

  // Initialize shouldn't do anything because initialize has been called
  EXPECT_TRUE(test_initializer_->initialize_was_called());
  test_initializer_->Initialize(test_system_);

  // Reset status of initialize called
  test_initializer_->set_initialize_was_called(false);
  test_initializer_->Initialize(test_system_);
  EXPECT_TRUE(test_initializer_->initialize_was_called());
}

} // namespace<|endoftext|>